Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fix(downloads): sanitize attacker-controlled filenames and verify containment

Saurav Pandac2ac67ab9080
diff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.py
index ecdc39994..148c4b460 100644
--- a/browser_use/browser/watchdogs/downloads_watchdog.py
+++ b/browser_use/browser/watchdogs/downloads_watchdog.py
@@ -243,7 +243,10 @@ class DownloadsWatchdog(BaseWatchdog):
# Cache info for later completion event handling (esp. remote browsers)
guid = event.get('guid', '')
url = event.get('url', '')
- suggested_filename = event.get('suggestedFilename', 'download')
+ # CDP suggestedFilename is page-controlled — sanitize at the ingress
+ # so every downstream consumer (callbacks, cache, events) sees only a
+ # safe basename. See _sanitize_download_filename / GHSA-rv9j-wqjp-2fv4.
+ suggested_filename = self._sanitize_download_filename(event.get('suggestedFilename', 'download'))
try:
assert suggested_filename, 'CDP DownloadWillBegin missing suggestedFilename'
self._cdp_downloads_info[guid] = {
@@ -580,7 +583,9 @@ class DownloadsWatchdog(BaseWatchdog):
filename_match = re.search(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)', content_disposition)
if filename_match:
- suggested_filename = filename_match.group(1).strip('\'"')
+ # Content-Disposition is attacker-controlled — strip path
+ # components before passing along. See _sanitize_download_filename.
+ suggested_filename = self._sanitize_download_filename(filename_match.group(1).strip('\'"'))
self.logger.info(f'[DownloadsWatchdog] 🔍 Detected downloadable content via network: {url[:80]}...')
self.logger.debug(
@@ -673,9 +678,10 @@ class DownloadsWatchdog(BaseWatchdog):
# Get or create CDP session for this target
temp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)
- # Determine filename
+ # Determine filename. `suggested_filename` is page-controlled
+ # (parsed from Content-Disposition) — sanitize before any path join.
if suggested_filename:
- filename = suggested_filename
+ filename = self._sanitize_download_filename(suggested_filename)
else:
# Extract from URL
filename = os.path.basename(url.split('?')[0]) # Remove query params
@@ -743,6 +749,11 @@ class DownloadsWatchdog(BaseWatchdog):
if download_result and download_result.get('data') and len(download_result['data']) > 0:
download_path = os.path.join(downloads_dir, final_filename)
+ # Defense in depth: refuse to write outside downloads_dir even
+ # if sanitization above missed something (e.g. symlinked dir).
+ if not self._is_path_contained(download_path, downloads_dir):
+ self.logger.error(f'[DownloadsWatchdog] Refusing to write download outside downloads_dir: {download_path}')
+ return None
# Save the file asynchronously
async with await anyio.open_file(download_path, 'wb') as f:
@@ -858,7 +869,8 @@ class DownloadsWatchdog(BaseWatchdog):
expected_path = None
download_result = None
download_url = event.get('url', '')
- suggested_filename = event.get('suggestedFilename', 'download')
+ # CDP suggestedFilename is page-controlled — sanitize before any path join.
+ suggested_filename = self._sanitize_download_filename(event.get('suggestedFilename', 'download'))
guid = event.get('guid', '')
try:
@@ -953,7 +965,9 @@ class DownloadsWatchdog(BaseWatchdog):
current_step = 'getting_download_info'
# Get download info immediately
url = download.url
- suggested_filename = download.suggested_filename
+ # `download.suggested_filename` originates from CDP/the page — sanitize
+ # before using it in any path join. See _sanitize_download_filename.
+ suggested_filename = self._sanitize_download_filename(download.suggested_filename)
current_step = 'determining_download_directory'
# Determine download directory from browser profile
@@ -965,6 +979,11 @@ class DownloadsWatchdog(BaseWatchdog):
# Check if Playwright already auto-downloaded the file (due to CDP setup)
original_path = Path(downloads_dir) / suggested_filename
+ # Defense in depth: even with a sanitized filename, refuse a path
+ # whose realpath escapes downloads_dir (e.g. symlinked downloads_dir).
+ if not self._is_path_contained(original_path, downloads_dir):
+ self.logger.error(f'[DownloadsWatchdog] Refusing to handle download outside downloads_dir: {original_path}')
+ return
if original_path.exists() and original_path.stat().st_size > 0:
self.logger.debug(
f'[DownloadsWatchdog] File already downloaded by Playwright: {original_path} ({original_path.stat().st_size} bytes)'
@@ -1310,6 +1329,13 @@ class DownloadsWatchdog(BaseWatchdog):
downloads_dir = str(self.browser_session.browser_profile.downloads_path)
os.makedirs(downloads_dir, exist_ok=True)
download_path = os.path.join(downloads_dir, final_filename)
+ # Defense in depth: ensure the resolved write target is inside
+ # downloads_dir. `final_filename` is derived from the URL path here
+ # (already basename'd), but a future change to the upstream
+ # derivation must not be able to silently re-introduce a traversal.
+ if not self._is_path_contained(download_path, downloads_dir):
+ self.logger.error(f'[DownloadsWatchdog] Refusing to write PDF outside downloads_dir: {download_path}')
+ return None
# Save the PDF asynchronously
async with await anyio.open_file(download_path, 'wb') as f:
@@ -1378,5 +1404,44 @@ class DownloadsWatchdog(BaseWatchdog):
counter += 1
return new_filename
+ @staticmethod
+ def _sanitize_download_filename(name: str | None) -> str:
+ """Reduce an attacker-controlled filename to a safe basename.
+
+ `suggested_filename` from CDP (`Page.downloadWillBegin.suggestedFilename`)
+ and `Content-Disposition` headers is page-controlled — any visited site
+ can supply `../../../etc/foo`, `/etc/shadow`, `\\\\server\\share\\x`, or
+ embedded null bytes. Joining such names into `downloads_path` writes
+ attacker-controlled bytes to an arbitrary location.
+
+ GHSA-rv9j-wqjp-2fv4, GHSA-66xh-g88g-2h8j, GHSA-hpr4-fqgr-xhj9.
+ """
+ if not name:
+ return 'download'
+ # Strip embedded null bytes — some platforms treat them as terminators.
+ name = name.replace('\x00', '')
+ # Normalize Windows-style separators served by Linux servers so we never
+ # fall through `os.path.basename` (which on POSIX does NOT split on '\\').
+ name = name.replace('\\', '/')
+ # Keep only the last path segment.
+ name = os.path.basename(name.rsplit('/', 1)[-1])
+ # Reject pure-traversal names that basename keeps verbatim.
+ if name in ('', '.', '..'):
+ return 'download'
+ return name
+
+ @staticmethod
+ def _is_path_contained(path: str | Path, directory: str | Path) -> bool:
+ """Return True iff `path`'s realpath is inside `directory`'s realpath.
+
+ Defense in depth: even after sanitization the on-disk write must verify
+ the resolved target stays inside `downloads_path`. Protects against
+ `directory` itself being a symlink whose target an attacker could change,
+ or sanitization bugs we haven't caught yet.
+ """
+ real_path = os.path.realpath(str(path))
+ real_dir = os.path.realpath(str(directory))
+ return real_path == real_dir or real_path.startswith(real_dir + os.sep)
+
# Fix Pydantic circular dependency - this will be called from session.py after BrowserSession is defined
diff --git a/tests/ci/security/test_download_filename_sanitization.py b/tests/ci/security/test_download_filename_sanitization.py
new file mode 100644
index 000000000..aa0c06619
--- /dev/null
+++ b/tests/ci/security/test_download_filename_sanitization.py
@@ -0,0 +1,116 @@
+"""Tests for download filename sanitization (GHSA-rv9j-wqjp-2fv4,
+GHSA-66xh-g88g-2h8j, GHSA-hpr4-fqgr-xhj9).
+
+`DownloadsWatchdog` historically joined attacker-controlled filenames from CDP
+(`Page.downloadWillBegin.suggestedFilename`) and `Content-Disposition` headers
+directly into the configured `downloads_path`. Strings like `../../escape.bin`
+or `/etc/shadow.bak` would `os.path.join` outside the downloads directory,
+writing the fetched bytes (also attacker-controlled — the response body is the
+exploit content) to an arbitrary location with the agent's process privileges.
+
+`download_file_from_url` triggers passively for any
+`Content-Disposition: attachment` response, so this is reachable from any
+visited site — `allowed_domains` does not mitigate it.
+
+The fix funnels every attacker-controlled filename through
+`DownloadsWatchdog._sanitize_download_filename`, which keeps only the basename
+and rejects pure-traversal names. Each on-disk sink additionally verifies
+containment via `os.path.realpath`.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from browser_use.browser.watchdogs.downloads_watchdog import DownloadsWatchdog
+
+
+class TestSanitizeDownloadFilename:
+ def test_strips_relative_traversal(self) -> None:
+ assert DownloadsWatchdog._sanitize_download_filename('../../etc/passwd') == 'passwd'
+
+ def test_strips_absolute_unix_path(self) -> None:
+ assert DownloadsWatchdog._sanitize_download_filename('/etc/shadow') == 'shadow'
+
+ def test_strips_windows_backslash_paths(self) -> None:
+ assert DownloadsWatchdog._sanitize_download_filename('..\\..\\Windows\\System32\\config.txt') == 'config.txt'
+
+ def test_strips_mixed_separators(self) -> None:
+ assert DownloadsWatchdog._sanitize_download_filename('a/b\\c/../d.pdf') == 'd.pdf'
+
+ def test_pure_traversal_falls_back_to_download(self) -> None:
+ for malicious in ('..', '.', '/', '\\', '../', '..\\', '/.', '\\.', '/..'):
+ assert DownloadsWatchdog._sanitize_download_filename(malicious) == 'download', (
+ f'{malicious!r} should fall back to default'
+ )
+
+ def test_null_byte_stripped(self) -> None:
+ # Null bytes can be used to confuse path handling on some platforms.
+ assert DownloadsWatchdog._sanitize_download_filename('file.txt\x00.exe') == 'file.txt.exe'
+
+ def test_empty_or_none_falls_back(self) -> None:
+ assert DownloadsWatchdog._sanitize_download_filename('') == 'download'
+ assert DownloadsWatchdog._sanitize_download_filename(None) == 'download'
+
+ def test_normal_filenames_preserved(self) -> None:
+ # Make sure we don't over-sanitize legitimate names.
+ assert DownloadsWatchdog._sanitize_download_filename('report.pdf') == 'report.pdf'
+ assert DownloadsWatchdog._sanitize_download_filename('file with spaces.pdf') == 'file with spaces.pdf'
+ assert DownloadsWatchdog._sanitize_download_filename('file-with_underscores.csv') == 'file-with_underscores.csv'
+ # Dotfiles are allowed as long as they're not just dots.
+ assert DownloadsWatchdog._sanitize_download_filename('.bashrc') == '.bashrc'
+
+ def test_unicode_preserved(self) -> None:
+ # Filenames with non-ASCII characters should survive (common for i18n filenames).
+ assert DownloadsWatchdog._sanitize_download_filename('résumé.pdf') == 'résumé.pdf'
+ assert DownloadsWatchdog._sanitize_download_filename('文档.pdf') == '文档.pdf'
+
+
+class TestIsPathContained:
+ def test_file_inside_dir_returns_true(self, tmp_path: Path) -> None:
+ f = tmp_path / 'a.txt'
+ f.write_text('x')
+ assert DownloadsWatchdog._is_path_contained(f, tmp_path) is True
+
+ def test_nested_file_inside_dir_returns_true(self, tmp_path: Path) -> None:
+ nested = tmp_path / 'sub' / 'a.txt'
+ nested.parent.mkdir()
+ nested.write_text('x')
+ assert DownloadsWatchdog._is_path_contained(nested, tmp_path) is True
+
+ def test_escaping_path_returns_false(self, tmp_path: Path) -> None:
+ escape = tmp_path / '..' / 'a.txt'
+ assert DownloadsWatchdog._is_path_contained(escape, tmp_path) is False
+
+ def test_dir_itself_returns_true(self, tmp_path: Path) -> None:
+ assert DownloadsWatchdog._is_path_contained(tmp_path, tmp_path) is True
+
+ def test_sibling_dir_returns_false(self, tmp_path: Path) -> None:
+ sibling = tmp_path.parent / (tmp_path.name + '_sibling')
+ sibling.mkdir(exist_ok=True)
+ try:
+ f = sibling / 'a.txt'
+ f.write_text('x')
+ assert DownloadsWatchdog._is_path_contained(f, tmp_path) is False
+ finally:
+ f.unlink(missing_ok=True)
+ sibling.rmdir()
+
+
+class TestUniqueFilenameOperatesOnSanitizedBasename:
+ """`_get_unique_filename` must only ever receive a sanitized basename; if a
+ traversal string slips through, the (1)/(2) collision-avoidance logic
+ silently writes outside the intended directory."""
+
+ async def test_unique_filename_on_basename_stays_inside_dir(self, tmp_path: Path) -> None:
+ # Pre-sanitized name — what the caller should always pass.
+ result = await DownloadsWatchdog._get_unique_filename(str(tmp_path), 'report.pdf')
+ assert result == 'report.pdf'
+ # The resolved path lives inside tmp_path.
+ assert DownloadsWatchdog._is_path_contained(tmp_path / result, tmp_path)
+
+ async def test_unique_filename_collision_handling_stays_inside_dir(self, tmp_path: Path) -> None:
+ (tmp_path / 'report.pdf').write_text('x')
+ result = await DownloadsWatchdog._get_unique_filename(str(tmp_path), 'report.pdf')
+ assert result == 'report (1).pdf'
+ assert DownloadsWatchdog._is_path_contained(tmp_path / result, tmp_path)