Summary
A serialization injection vulnerability exists in LangChain's dumps() and dumpd() functions. The functions do not escape dictionaries with 'lc' keys when serializing free-form dictionaries. The 'lc' key is used internally by LangChain to mark serialized objects. When user-controlled data contains this key structure, it is treated as a legitimate LangChain object during deserialization rather than plain user data.
Attack surface
The core vulnerability was in dumps() and dumpd(): these functions failed to escape user-controlled dictionaries containing 'lc' keys. When this unescaped data was later deserialized via load() or loads(), the injected structures were treated as legitimate LangChain objects rather than plain user data.
This escaping bug enabled several attack vectors:
1. Injection via user data: Malicious LangChain object structures could be injected through user-controlled fields like metadata, additionalkwargs, or responsemetadata 2. Class instantiation within trusted namespaces: Injected manifests could instantiate any Serializable subclass, but only within the pre-approved trusted namespaces (langchaincore, langchain, langchaincommunity). This includes classes with side effects in init (network calls, file operations, etc.). Note that namespace validation was already enforced before this patch, so arbitrary classes outside these trusted namespaces could not be instantiated.
Security hardening
This patch fixes the escaping bug in dumps() and dumpd() and introduces new restrictive defaults in load() and loads(): allowlist enforcement via allowedobjects="core" (restricted to serialization mappings), secretsfromenv changed from True to False, and default Jinja2 template blocking via initvalidator. These are breaking changes for some use cases.
Who is affected?
Applications are vulnerable if they:
1. Use astreamevents(version="v1") — The v1 implementation internally uses vulnerable serialization. Note: astreamevents(version="v2") is not vulnerable. 2. Use Runnable.astreamlog() — This method internally uses vulnerable serialization for streaming outputs. 3. Call dumps() or dumpd() on untrusted data, then deserialize with load() or loads() — Trusting your own serialization output makes you vulnerable if user-controlled data (e.g., from LLM responses, metadata fields, or user inputs) contains 'lc' key structures. 4. Deserialize untrusted data with load() or loads() — Directly deserializing untrusted data that may contain injected 'lc' structures. 5. Use RunnableWithMessageHistory — Internal serialization in message history handling. 6. Use InMemoryVectorStore.load() to deserialize untrusted documents. 7. Load untrusted generations from cache using langchain-community caches. 8. Load untrusted manifests from the LangChain Hub via hub.pull. 9. Use StringRunEvaluatorChain on untrusted runs. 10. Use createlcstore or createkvdocstore with untrusted documents. 11. Use MultiVectorRetriever with byte stores containing untrusted documents. 12. Use LangSmithRunChatLoader with runs containing untrusted messages.
The most common attack vector is through LLM response fields like additionalkwargs or responsemetadata, which can be controlled via prompt injection and then serialized/deserialized in streaming operations.
Impact
Attackers who control serialized data can extract environment variable secrets by injecting {"lc": 1, "type": "secret", "id": ["ENVVAR"]} to load environment variables during deserialization (when secretsfromenv=True, which was the old default). They can also instantiate classes with controlled parameters by injecting constructor structures to instantiate any class within trusted namespaces with attacker-controlled parameters, potentially triggering side effects such as network calls or file operations.
Key severity factors:
- Affects the serialization path - applications trusting their own serialization output are vulnerable - Enables secret extraction when combined with secretsfromenv=True (the old default) - LLM responses in additionalkwargs can be controlled via prompt injection
Exploit example
python from langchaincore.load import dumps, load import os
Attacker injects secret structure into user-controlled data attackerdict = { "userdata": { "lc": 1, "type": "secret", "id": ["OPENAIAPIKEY"] } }
serialized = dumps(attackerdict) # Bug: does NOT escape the 'lc' key
os.environ["OPENAIAPIKEY"] = "sk-secret-key-12345" deserialized = load(serialized, secretsfromenv=True)
print(deserialized["userdata"]) # "sk-secret-key-12345" - SECRET LEAKED!
Security hardening changes (breaking changes)
This patch introduces three breaking changes to load() and loads():
1. New allowedobjects parameter (defaults to 'core'): Enforces allowlist of classes that can be deserialized. The 'all' option corresponds to the list of objects specified in mappings.py while the 'core' option limits to objects within langchaincore. We recommend that users explicitly specify which objects they want to allow for serialization/deserialization. 2. secretsfromenv default changed from True to False: Disables automatic secret loading from environment 3. New initvalidator parameter (defaults to defaultinitvalidator): Blocks Jinja2 templates by default
Migration guide
No changes needed for most users
If you're deserializing standard LangChain types (messages, documents, prompts, trusted partner integrations like ChatOpenAI, ChatAnthropic, etc.), your code will work without changes:
python from langchaincore.load import load
Uses default allowlist from serialization mappings obj = load(serializeddata)
For custom classes
If you're deserializing custom classes not in the serialization mappings, add them to the allowlist:
python from langchaincore.load import load from mypackage import MyCustomClass
Specify the classes you need obj = load(serializeddata, allowedobjects=[MyCustomClass])
For Jinja2 templates
Jinja2 templates are now blocked by default because they can execute arbitrary code. If you need Jinja2 templates, pass initvalidator=None:
python from langchaincore.load import load from langchaincore.prompts import PromptTemplate
obj = load( serializeddata, allowedobjects=[PromptTemplate], initvalidator=None )
[!WARNING] Only disable initvalidator if you trust the serialized data. Jinja2 templates can execute arbitrary Python code.
For secrets from environment
secretsfromenv now defaults to False. If you need to load secrets from environment variables:
python from langchaincore.load import load
obj = load(serializeddata, secretsfromenv=True)
Credits
Dumps bug was reported by @yardenporat Changes for security hardening due to findings from @0xn3va and @VladimirEliTokarev
Summary
Multiple functions in langchaincore.prompts.loading read files from paths embedded in deserialized config dicts without validating against directory traversal or absolute path injection. When an application passes user-influenced prompt configurations to loadprompt() or loadpromptfromconfig(), an attacker can read arbitrary files on the host filesystem, constrained only by file-extension checks (.txt for templates, .json/.yaml for examples).
Note: The affected functions (loadprompt, loadpromptfromconfig, and the .save() method on prompt classes) are undocumented legacy APIs. They are superseded by the dumpd/dumps/load/loads serialization APIs in langchaincore.load, which do not perform filesystem reads and use an allowlist-based security model. As part of this fix, the legacy APIs have been formally deprecated and will be removed in 2.0.0.
Affected component
Package: langchain-core File: langchaincore/prompts/loading.py Affected functions: loadtemplate(), loadexamples(), loadfewshotprompt()
Severity
High
The score reflects the file-extension constraints that limit which files can be read.
Vulnerable code paths
| Config key | Loaded by | Readable extensions | |---|---|---| | templatepath, suffixpath, prefixpath | loadtemplate() | .txt | | examples (when string) | loadexamples() | .json, .yaml, .yml | | examplepromptpath | loadfewshotprompt() | .json, .yaml, .yml |
None of these code paths validated the supplied path against absolute path injection or .. traversal sequences before reading from disk.
Impact
An attacker who controls or influences the prompt configuration dict can read files outside the intended directory:
- .txt files: cloud-mounted secrets (/mnt/secrets/apikey.txt), requirements.txt, internal system prompts - .json/.yaml files: cloud credentials (~/.docker/config.json, ~/.azure/accessTokens.json), Kubernetes manifests, CI/CD configs, application settings
This is exploitable in applications that accept prompt configs from untrusted sources, including low-code AI builders and API wrappers that expose loadpromptfromconfig().
Proof of concept
python from langchaincore.prompts.loading import loadpromptfromconfig
Reads /tmp/secret.txt via absolute path injection config = { "type": "prompt", "templatepath": "/tmp/secret.txt", "inputvariables": [], } prompt = loadpromptfromconfig(config) print(prompt.template) # file contents disclosed
Reads ../../etc/secret.txt via directory traversal config = { "type": "prompt", "templatepath": "../../etc/secret.txt", "inputvariables": [], } prompt = loadpromptfromconfig(config)
Reads arbitrary .json via few-shot examples config = { "type": "fewshot", "examples": "../../../../.docker/config.json", "exampleprompt": { "type": "prompt", "inputvariables": ["input", "output"], "template": "{input}: {output}", }, "prefix": "", "suffix": "{query}", "inputvariables": ["query"], } prompt = loadpromptfromconfig(config)
Mitigation
Update langchain-core to >= 1.2.22.
The fix adds path validation that rejects absolute paths and .. traversal sequences by default. An allowdangerouspaths=True keyword argument is available on loadprompt() and loadpromptfromconfig() for trusted inputs.
As described above, these legacy APIs have been formally deprecated. Users should migrate to dumpd/dumps/load/loads from langchaincore.load.
Credit
- jiayuqi7813 reporter - VladimirEliTokarev reporter - Rickidevs reporter - Kenneth Cox (cczine@gmail.com) reporter
LangChain is a framework for building agents and LLM-powered applications. Prior to 0.3.84 and 1.2.28, LangChain's f-string prompt-template validation was incomplete in two respects. First, some prompt template classes accepted f-string templates and formatted them without enforcing the same attribute-access validation as PromptTemplate. In particular, DictPromptTemplate and ImagePromptTemplate could accept templates containing attribute access or indexing expressions and subsequently evaluate those expressions during formatting. Second, f-string validation based on parsed top-level field names did not reject nested replacement fields inside format specifiers. In this pattern, the nested replacement field appears in the format specifier rather than in the top-level field name. As a result, earlier validation based on parsed field names did not reject the template even though Python formatting would still attempt to resolve the nested expression at runtime. This vulnerability is fixed in 0.3.84 and 1.2.28.
Server-Side Request Forgery (SSRF) in ChatOpenAI Image Token Counting
Summary The ChatOpenAI.getnumtokensfrommessages() method fetches arbitrary imageurl values without validation when computing token counts for vision-enabled models. This allows attackers to trigger Server-Side Request Forgery (SSRF) attacks by providing malicious image URLs in user input.
Severity Low - The vulnerability allows SSRF attacks but has limited impact due to: - Responses are not returned to the attacker (blind SSRF) - Default 5-second timeout limits resource exhaustion - Non-image responses fail at PIL image parsing
Impact An attacker who can control image URLs passed to getnumtokensfrommessages() can: - Trigger HTTP requests from the application server to arbitrary internal or external URLs - Cause the server to access internal network resources (private IPs, cloud metadata endpoints) - Cause minor resource consumption through image downloads (bounded by timeout)
Note: This vulnerability occurs during token counting, which may happen outside of model invocation (e.g., in logging, metrics, or token budgeting flows).
Details The vulnerable code path: 1. getnumtokensfrommessages() processes messages containing imageurl content blocks 2. For images without detail: "low", it calls urltosize() to fetch the image and compute token counts 3. urltosize() performs httpx.get(imagesource) on any URL without validation 4. Prior to the patch, there was no SSRF protection, size limits, or explicit timeout
File: libs/partners/openai/langchainopenai/chatmodels/base.py
Patches The vulnerability has been patched in langchain-openai==1.1.9 (requires langchain-core==1.2.11).
The patch adds: 1. SSRF validation using langchaincore.security.ssrfprotection.validatesafeurl() to block: - Private IP ranges (RFC 1918, loopback, link-local) - Cloud metadata endpoints (169.254.169.254, etc.) - Invalid URL schemes 2. Explicit size limits (50 MB maximum, matching OpenAI's payload limit) 3. Explicit timeout (5 seconds, same as httpx.get default) 4. Allow disabling image fetching via allowfetchingimages=False parameter
Workarounds If you cannot upgrade immediately:
1. Sanitize input: Validate and filter imageurl values before passing messages to token counting or model invocation 2. Use network controls: Implement egress filtering to prevent outbound requests to private IPs