Arbitrary Code Execution in LangChain via Maliciously Crafted Python Tool Docstrings
Overview
A critical vulnerability was discovered in LangChain's experimental PythonAstREPLTool. The tool is designed to execute Python code to answer questions, but it insecurely evaluated docstrings of the functions it could access. An attacker could craft a malicious Python function with a docstring containing arbitrary Python code. When this function is loaded into the tool's execution context and subsequently inspected by the language model as part of its reasoning process, the malicious docstring would be executed with the same permissions as the LangChain application. This could lead to Remote Code Execution (RCE) on the host system. The vulnerability arises because the tool's internal logic did not properly sanitize or restrict the content of docstrings before evaluation. Discovered by security researchers at Synacktiv, this vulnerability highlights the dangers of allowing LLM agents to interact with powerful tools that have access to interpreters without sufficient sandboxing and input validation, even through seemingly innocuous metadata like docstrings.
Affected Systems
Testing Guide
1. Create a Python file `malicious_tool.py` with the following content: ```python def my_malicious_function(): '''__import__('os').system('touch /tmp/pwned')''' return 'This is a test function.' ``` 2. In your LangChain application using an affected version, instantiate `PythonAstREPLTool` with access to `my_malicious_function`. 3. Prompt the agent with a query that would cause it to inspect the function, such as "What does the `my_malicious_function` do?". 4. Check if the file `/tmp/pwned` was created on the system. If it exists, the system is vulnerable.
Mitigation Steps
1. Upgrade the `langchain` and `langchain-experimental` packages to version `0.1.9` and `0.0.48` or later, respectively. 2. Avoid using experimental tools like `PythonAstREPLTool` in production environments, especially when processing untrusted inputs. 3. If a Python interpreter tool is necessary, ensure it runs in a heavily restricted, sandboxed environment (e.g., a Docker container with limited permissions and no network access). 4. Implement strict input validation on all data passed to LLM agents and their tools.
Patch Details
Patched in langchain v0.1.9 and langchain-experimental v0.0.48. The patch removes the unsafe evaluation of docstrings.