Arbitrary Code Execution in LangChain via Maliciously Crafted Prompt Files
Overview
A critical remote code execution (RCE) vulnerability was discovered in the popular LangChain framework. The vulnerability exists within the `load_prompt` function, which is used to load prompt templates from local files. The underlying issue stems from the function's use of Python's `yaml.load()` method for parsing `.yaml` and `.json` prompt files. Unlike `yaml.safe_load()`, the standard `yaml.load()` function is insecure as it can deserialize not just data but also arbitrary Python objects, allowing an attacker to construct a malicious prompt file that executes arbitrary code when parsed. An attacker could exploit this by tricking a user or an automated system into loading a malicious prompt template from a compromised source, such as a public Git repository. Upon loading the prompt, the attacker's payload would execute with the permissions of the application running LangChain. This could lead to complete system compromise, data theft, or lateral movement within a network, posing a significant risk to applications that ingest prompt templates from untrusted sources.
Affected Systems
Testing Guide
1. **Create a malicious prompt file**: Create a file named `malicious_prompt.yaml` with the following content: ```yaml !!python/object/apply:os.system - 'touch /tmp/pwned' ``` 2. **Write a test script**: In Python, use an affected version of LangChain to load this file: ```python from langchain.prompts import load_prompt try: load_prompt('malicious_prompt.yaml') except Exception as e: print(f'Error: {e}') ``` 3. **Verify Execution**: Check if the file `/tmp/pwned` was created on your system. If it exists, your version is vulnerable.
Mitigation Steps
1. **Upgrade LangChain**: Immediately update to version `0.0.322` or newer. 2. **Audit Prompt Sources**: Never load prompt files from untrusted or unverified sources. Treat prompt templates as code. 3. **Use Safe Loading**: If upgrading is not possible, modify code to use `yaml.safe_load` or parse JSON with the standard `json` library instead of using `load_prompt` directly. 4. **Input Validation**: Implement strict validation and sanitization on any user-supplied paths or content that are fed into prompt loading functions.
Patch Details
Patched in LangChain version 0.0.322 by replacing `yaml.load` with `yaml.safe_load` in the `load_prompt` function.