Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

fix: prevent path traversal in FileWriterTool (#4895)

Rip&Tear713fa7d01be1
diff --git a/lib/crewai-tools/src/crewai_tools/tools/file_writer_tool/file_writer_tool.py b/lib/crewai-tools/src/crewai_tools/tools/file_writer_tool/file_writer_tool.py
index e961b57db..4cd3c1566 100644
--- a/lib/crewai-tools/src/crewai_tools/tools/file_writer_tool/file_writer_tool.py
+++ b/lib/crewai-tools/src/crewai_tools/tools/file_writer_tool/file_writer_tool.py
@@ -1,4 +1,5 @@
import os
+from pathlib import Path
from typing import Any
from crewai.tools import BaseTool
@@ -30,27 +31,39 @@ class FileWriterTool(BaseTool):
def _run(self, **kwargs: Any) -> str:
try:
- if kwargs.get("directory"):
- os.makedirs(kwargs["directory"], exist_ok=True)
+ directory = kwargs.get("directory") or "./"
+ filename = kwargs["filename"]
+
+ filepath = os.path.join(directory, filename)
- # Construct the full path
- filepath = os.path.join(kwargs.get("directory") or "", kwargs["filename"])
+ # Prevent path traversal: the resolved path must be strictly inside
+ # the resolved directory. This blocks ../sequences, absolute paths in
+ # filename, and symlink escapes regardless of how directory is set.
+ # is_relative_to() does a proper path-component comparison that is
+ # safe on case-insensitive filesystems and avoids the "// " edge case
+ # that plagues startswith(real_directory + os.sep).
+ # We also reject the case where filepath resolves to the directory
+ # itself, since that is not a valid file target.
+ real_directory = Path(directory).resolve()
+ real_filepath = Path(filepath).resolve()
+ if not real_filepath.is_relative_to(real_directory) or real_filepath == real_directory:
+ return "Error: Invalid file path — the filename must not escape the target directory."
+
+ if kwargs.get("directory"):
+ os.makedirs(real_directory, exist_ok=True)
- # Convert overwrite to boolean
kwargs["overwrite"] = strtobool(kwargs["overwrite"])
- # Check if file exists and overwrite is not allowed
- if os.path.exists(filepath) and not kwargs["overwrite"]:
- return f"File {filepath} already exists and overwrite option was not passed."
+ if os.path.exists(real_filepath) and not kwargs["overwrite"]:
+ return f"File {real_filepath} already exists and overwrite option was not passed."
- # Write content to the file
mode = "w" if kwargs["overwrite"] else "x"
- with open(filepath, mode) as file:
+ with open(real_filepath, mode) as file:
file.write(kwargs["content"])
- return f"Content successfully written to {filepath}"
+ return f"Content successfully written to {real_filepath}"
except FileExistsError:
return (
- f"File {filepath} already exists and overwrite option was not passed."
+ f"File {real_filepath} already exists and overwrite option was not passed."
)
except KeyError as e:
return f"An error occurred while accessing key: {e!s}"
diff --git a/lib/crewai-tools/tests/tools/test_file_writer_tool.py b/lib/crewai-tools/tests/tools/test_file_writer_tool.py
index 53f80b950..eb816ee38 100644
--- a/lib/crewai-tools/tests/tools/test_file_writer_tool.py
+++ b/lib/crewai-tools/tests/tools/test_file_writer_tool.py
@@ -135,3 +135,59 @@ def test_file_exists_error_handling(tool, temp_env, overwrite):
assert "already exists and overwrite option was not passed" in result
assert read_file(path) == "Pre-existing content"
+
+
+# --- Path traversal prevention ---
+
+def test_blocks_traversal_in_filename(tool, temp_env):
+ # Create a sibling "outside" directory so we can assert nothing was written there.
+ outside_dir = tempfile.mkdtemp()
+ outside_file = os.path.join(outside_dir, "outside.txt")
+ try:
+ result = tool._run(
+ filename=f"../{os.path.basename(outside_dir)}/outside.txt",
+ directory=temp_env["temp_dir"],
+ content="should not be written",
+ overwrite=True,
+ )
+ assert "Error" in result
+ assert not os.path.exists(outside_file)
+ finally:
+ shutil.rmtree(outside_dir, ignore_errors=True)
+
+
+def test_blocks_absolute_path_in_filename(tool, temp_env):
+ # Use a temp file outside temp_dir as the absolute target so we don't
+ # depend on /etc/passwd existing or being writable on the host.
+ outside_dir = tempfile.mkdtemp()
+ outside_file = os.path.join(outside_dir, "target.txt")
+ try:
+ result = tool._run(
+ filename=outside_file,
+ directory=temp_env["temp_dir"],
+ content="should not be written",
+ overwrite=True,
+ )
+ assert "Error" in result
+ assert not os.path.exists(outside_file)
+ finally:
+ shutil.rmtree(outside_dir, ignore_errors=True)
+
+
+def test_blocks_symlink_escape(tool, temp_env):
+ # Symlink inside temp_dir pointing to a separate temp "outside" directory.
+ outside_dir = tempfile.mkdtemp()
+ outside_file = os.path.join(outside_dir, "target.txt")
+ link = os.path.join(temp_env["temp_dir"], "escape")
+ os.symlink(outside_dir, link)
+ try:
+ result = tool._run(
+ filename="escape/target.txt",
+ directory=temp_env["temp_dir"],
+ content="should not be written",
+ overwrite=True,
+ )
+ assert "Error" in result
+ assert not os.path.exists(outside_file)
+ finally:
+ shutil.rmtree(outside_dir, ignore_errors=True)