CVE-2025-65106: Langchain core LangChain Vulnerable To Template Injection Vulnerability

HIGH
Advisory Identifier: GHSA-6qv9-48xg-fc7f
CWE-1336
Published
Advisory Summary

CVE-2025-65106 is a HIGH langchain vulnerable to template injection vulnerability (CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine) affecting Langchain core libraries in the PyPI ecosystem. The issue involves langchain vulnerable to template injection via attribute access in prompt templates. Remediation is available by upgrading affected packages to version 1.0.7, 0.3.80.

CVE-2025-65106 at a Glance

CVE Identifier CVE-2025-65106
GHSA Identifier GHSA-6qv9-48xg-fc7f
Severity HIGH
CVSS v3.1 Base Score N/A
CWE Classification CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine
Affected Product Langchain core
Package Ecosystem PyPI
Published Date
Last Updated

How to Fix CVE-2025-65106

To remediate this vulnerability, upgrade all affected Langchain core dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

langchain-core fixed: 1.0.7
pip install langchain-core>=1.0.7
langchain-core fixed: 0.3.80
pip install langchain-core>=0.3.80
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

pip show langchain-core

How to Check if You Are Affected

To determine whether your Python environment is affected by CVE-2025-65106, inspect your installed packages using pip:

pip show langchain-core

Analyze the terminal output to locate any version of Langchain core in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 1.0.7), your application is affected.

Note: The pip show langchain-core command checks currently installed packages in your active Python environment.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine, where 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. In Langchain core, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

## 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-core` package - 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:** ```python 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:** ```python 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:** ```python 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 1. **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 Formatter template = "{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 like `__globals__` to reach sensitive objects. 2. **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 3. **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 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:** ```python # 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:** ```python # 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}` ```python # 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`, and `tuple` types - Blocks attribute access on arbitrary Python objects ```python # 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 `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method access - Only allows simple variable lookups from the context dictionary - Raises `SecurityError` on any attribute access attempt ```python # 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 1. **Audit your code** for any locations where template strings come from untrusted sources 2. **Update to the patched version** of `langchain-core` 3. **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-core` package - 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:** ```python 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:** ```python 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:** ```python 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 1. **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 Formatter template = "{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 like `__globals__` to reach sensitive objects. 2. **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 3. **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 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:** ```python # 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:** ```python # 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}` ```python # 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`, and `tuple` types - Blocks attribute access on arbitrary Python objects ```python # 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 `_RestrictedSandboxedEnvironment` that blocks **ALL** attribute/method access - Only allows simple variable lookups from the context dictionary - Raises `SecurityError` on any attribute access attempt ```python # 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 1. **Audit your code** for any locations where template strings come from untrusted sources 2. **Update to the patched version** of `langchain-core` 3. **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.

CVE-2025-65106 Affected Langchain core Versions

2 component(s)
Fixed Versions:
1.0.70.3.80
Product / Package Ecosystem Affected Versions Fixed Version
langchain-core
PyPI
≥ 1.0.0
< 1.0.7
1.0.7
langchain-core
PyPI
< 0.3.80
0.3.80

References

Frequently Asked Questions

What is CVE-2025-65106?
CVE-2025-65106 is a security vulnerability in Langchain core involving LangChain Vulnerable to Template Injection via Attribute Access in Prompt Templates under CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine.
Which Langchain core versions are affected?
Affected versions include releases prior to 1.0.7, 0.3.80 across affected packages: langchain-core.
What version fixes CVE-2025-65106?
Upgrading to 1.0.7, 0.3.80 (or the latest patched release for your respective branch) resolves the vulnerability.
Is langchain-core affected?
Yes, langchain-core is affected in releases prior to 1.0.7, 0.3.80. Upgrade your dependency to 1.0.7, 0.3.80 or later.
What CWE is associated with CVE-2025-65106?
CVE-2025-65106 is classified under CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine (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.).
How can I check PyPI dependencies for CVE-2025-65106?
Run the dependency tree command: 'pip show langchain-core'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-6qv9-48xg-fc7f",
  "modified" : "2025-12-09T17:15:16Z",
  "published" : "2025-11-20T17:42:12Z",
  "aliases" : [ "CVE-2025-65106" ],
  "summary" : "LangChain Vulnerable to Template Injection via Attribute Access in Prompt Templates",
  "details" : "## Context\n\nA 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.\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# >>> result.messages[0].content\n# >>> 'str'\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's `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: ['msg.__class__', 'x']\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'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\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 'question' 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've 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've 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've 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'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.\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'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.\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'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.\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# >>> result.messages[0].content\n# >>> 'str'\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's `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: ['msg.__class__', 'x']\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'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\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 'question' 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've 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've 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've 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'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.\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'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.\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.",
  "severity" : [ {
    "type" : "CVSS_V4",
    "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"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "PyPI",
      "name" : "langchain-core"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "1.0.0"
      }, {
        "fixed" : "1.0.7"
      } ]
    } ],
    "database_specific" : {
      "last_known_affected_version_range" : "<= 1.0.6"
    }
  }, {
    "package" : {
      "ecosystem" : "PyPI",
      "name" : "langchain-core"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "0"
      }, {
        "fixed" : "0.3.80"
      } ]
    } ],
    "database_specific" : {
      "last_known_affected_version_range" : "<= 0.3.79"
    }
  } ],
  "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"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-1336" ],
    "severity" : "HIGH",
    "github_reviewed" : true,
    "github_reviewed_at" : "2025-11-20T17:42:12Z",
    "nvd_published_at" : "2025-11-21T22:16:32Z"
  }
}