GHSA-6qv9-48xg-fc7f LangChain Vulnerable to Template Injection via Attribute Access in Prompt Templates
ContextA 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-core` packageTemplate formats:F-string templates (`template_format="f-string"`) - **Vulnerability fixed**Mustache templates (`template_format="mustache"`) - **Defensive hardening**Jinja2 templates (`template_format="jinja2"`) - **Defensive hardening**ImpactAttackers who can control template strings (not just template variables) can:Access Python object attributes and internal properties via attribute traversalExtract sensitive information from object internals (e.g., `__class__`, `__globals__`)Potentially escalate to more severe attacks depending on the objects passed to templatesAttack Vectors1. F-string Template Injection**Before Fix:**2. Mustache Template Injection**Before Fix:**3. Jinja2 Template Injection**Before Fix:**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: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.**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**Jinja2 templates**: Jinja2's 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've restricted the environment to block all attribute and method access on objects
passed to templates.Who Is Affected?High Risk ScenariosYou are affected if your application:Accepts template strings from untrusted sources (user input, external APIs, databases)Dynamically constructs prompt templates based on user-provided patternsAllows users to customize or create prompt templates**Example vulnerable code:**Low/No Risk ScenariosYou are **NOT** affected if:Template strings are hardcoded in your application codeTemplate strings come only from trusted, controlled sourcesUsers can only provide **values** for template variables, not the template structure itself**Example safe code:**The FixF-string TemplatesF-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 identifiersRejects syntax like `{obj.attr}`, `{obj[0]}`, or `{obj.__class__}`Only allows simple variable names: `{variable_name}`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 checkingOnly allows traversal into `dict`, `list`, and `tuple` typesBlocks attribute access on arbitrary Python objectsJinja2 Templates (Defensive Hardening)As defensive hardening, we've significantly restricted Jinja2 template capabilities:Introduced `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method accessOnly allows simple variable lookups from the context dictionaryRaises `SecurityError` on any attribute access attempt**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.RemediationImmediate 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 dataBest Practices**Consider if you need templates at all** - Many applications can work directly with message objects (`HumanMessage`, `AIMessage`, etc.) without templates## ContextA 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-core` packageTemplate formats:F-string templates (`template_format="f-string"`) - **Vulnerability fixed**Mustache templates (`template_format="mustache"`) - **Defensive hardening**Jinja2 templates (`template_format="jinja2"`) - **Defensive hardening**ImpactAttackers who can control template strings (not just template variables) can:Access Python object attributes and internal properties via attribute traversalExtract sensitive information from object internals (e.g., `__class__`, `__globals__`)Potentially escalate to more severe attacks depending on the objects passed to templatesAttack Vectors1. F-string Template Injection**Before Fix:**2. Mustache Template Injection**Before Fix:**3. Jinja2 Template Injection**Before Fix:**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: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.**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**Jinja2 templates**: Jinja2's 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've restricted the environment to block all attribute and method access on objects
passed to templates.Who Is Affected?High Risk ScenariosYou are affected if your application:Accepts template strings from untrusted sources (user input, external APIs, databases)Dynamically constructs prompt templates based on user-provided patternsAllows users to customize or create prompt templates**Example vulnerable code:**Low/No Risk ScenariosYou are **NOT** affected if:Template strings are hardcoded in your application codeTemplate strings come only from trusted, controlled sourcesUsers can only provide **values** for template variables, not the template structure itself**Example safe code:**The FixF-string TemplatesF-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 identifiersRejects syntax like `{obj.attr}`, `{obj[0]}`, or `{obj.__class__}`Only allows simple variable names: `{variable_name}`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 checkingOnly allows traversal into `dict`, `list`, and `tuple` typesBlocks attribute access on arbitrary Python objectsJinja2 Templates (Defensive Hardening)As defensive hardening, we've significantly restricted Jinja2 template capabilities:Introduced `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method accessOnly allows simple variable lookups from the context dictionaryRaises `SecurityError` on any attribute access attempt**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.RemediationImmediate 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 dataBest 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 contentUpdate: Jinja2 Restrictions RevertedThe 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.
CVSS v4.0 score: 8.3