CVE-2025-65106: LangChain Vulnerable to Template Injection via Attribute Access in Prompt Templates

Published Nov 20, 2025
·
Updated

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 (templateformat="f-string") - Vulnerability fixed - Mustache templates (templateformat="mustache") - Defensive hardening - Jinja2 templates (templateformat="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 langchaincore.prompts import ChatPromptTemplate

malicioustemplate = ChatPromptTemplate.frommessages( [("human", "{msg.class.name}")], templateformat="f-string" )

Note that this requires passing a placeholder variable for "msg.class.name". result = malicioustemplate.invoke({"msg": "foo", "msg.class.name": "safeplaceholder"}) Previously returned >>> result.messages[0].content >>> 'str'

2. Mustache Template Injection Before Fix: python from langchaincore.prompts import ChatPromptTemplate from langchaincore.messages import HumanMessage

msg = HumanMessage("Hello")

Attacker controls the template string malicioustemplate = ChatPromptTemplate.frommessages( [("human", "{{question.class.name}}")], templateformat="mustache" )

result = malicioustemplate.invoke({"question": msg}) Previously returned: "HumanMessage" (getattr() exposed internals)

3. Jinja2 Template Injection Before Fix: python from langchaincore.prompts import ChatPromptTemplate from langchaincore.messages import HumanMessage

msg = HumanMessage("Hello")

Attacker controls the template string malicioustemplate = ChatPromptTemplate.frommessages( [("human", "{{question.parseraw}}")], templateformat="jinja2" )

result = malicioustemplate.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([varname for (, varname, , ) 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 usertemplatestring = request.json.get("template") # DANGEROUS

prompt = ChatPromptTemplate.frommessages( [("human", usertemplatestring)], templateformat="mustache" )

result = prompt.invoke({"data": sensitiveobject})

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.frommessages( [("human", "User question: {question}")], # SAFE templateformat="f-string" )

User input only fills the 'question' variable result = prompt.invoke({"question": userinput})

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: {variablename}

python After fix - these are rejected at template creation time ChatPromptTemplate.frommessages( [("human", "{msg.class}")], # ValueError: Invalid variable name templateformat="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.frommessages( [("human", "{{msg.class}}")], templateformat="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.frommessages( [("human", "{{msg.content}}")], templateformat="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

Other sources

LangChain is a framework for building agents and LLM-powered applications. From versions 0.3.79 and prior and 1.0.0 to 1.0.6, 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. This issue has been patched in versions 0.3.80 and 1.0.7.

MITRE

Affected Software

3 affected componentsFixes available
pip/langchain-core<=0.3.79
0.3.80
pip/langchain-core>=1.0.0<=1.0.6
1.0.7
IBM Concert Software<=1.0.0-2.1.0

Event History

Nov 20, 2025
Advisory Published
via GitHub·05:42 PM
Data Sourced
via GitHub·05:42 PM
DescriptionWeaknessAffected Software
Nov 21, 2025
CVE Published
via MITRE·09:43 PM
Data Sourced
via MITRE·09:43 PM
DescriptionWeakness
Data Sourced
via NVD·10:16 PM
DescriptionSeverityWeakness
Jan 14, 2026
Data Sourced
via IBM·12:00 AM
DescriptionAffected Software

Parent advisories

This vulnerability appears in the following advisories.

Free Weekly Intel

Don't miss critical vulnerabilities

Join thousands of security professionals who receive our weekly digest of trending CVEs, zero-days, and exploited vulnerabilities.

No spam. Unsubscribe anytime.

Frequently Asked Questions

1

What is the severity of CVE-2025-65106?

CVE-2025-65106 is classified as a high severity vulnerability due to its potential exploitation in template injection attacks.

2

How do I fix CVE-2025-65106?

To fix CVE-2025-65106, upgrade to langchain-core version 0.3.80 or 1.0.7 or higher.

3

Which versions are affected by CVE-2025-65106?

CVE-2025-65106 affects langchain-core versions up to 0.3.79 and 1.0.6 and below.

4

What kind of attacks can be performed using CVE-2025-65106?

CVE-2025-65106 allows attackers to access Python object internals through untrusted template strings.

5

Is CVE-2025-65106 specific to certain software environments?

Yes, CVE-2025-65106 specifically affects applications using LangChain's prompt template system.

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203