Skip to content

Commit 124254d

Browse files
committed
Validate and confine HTTP Content-Disposition filenames in fetch_http
1 parent cff07bc commit 124254d

2 files changed

Lines changed: 223 additions & 5 deletions

File tree

‎scanpipe/pipes/fetch.py‎

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,45 @@
7777
# urllib3-based HTTP client disagree on the host part of a URL, defeating the
7878
# ``is_safe_url`` check below.
7979
UNSAFE_URL_CHARS_RE = re.compile(r"[\x00-\x20\x7f\\]")
80+
UNSAFE_FILENAME_CHARS_RE = re.compile(r"[\x00-\x1f\x7f/\\]")
81+
82+
83+
def is_safe_filename(filename, download_directory):
84+
"""
85+
Return True if `filename` is a safe single file name that resolves
86+
strictly inside `download_directory` without traversing or escaping.
87+
"""
88+
if not filename or not isinstance(filename, str):
89+
return False
90+
91+
filename = filename.strip()
92+
if not filename or filename in (".", ".."):
93+
return False
94+
95+
# Reject null bytes, control characters, and POSIX / Windows path separators
96+
if UNSAFE_FILENAME_CHARS_RE.search(filename):
97+
return False
98+
99+
# Reject Windows drive prefixes or stream/colon syntax (e.g. C:, file:stream)
100+
if ":" in filename:
101+
return False
102+
103+
download_dir = Path(download_directory).resolve()
104+
candidate_path = (download_dir / filename).resolve()
105+
106+
# Must resolve strictly inside download_dir and not be download_dir itself
107+
if (
108+
not candidate_path.is_relative_to(download_dir)
109+
or candidate_path == download_dir
110+
):
111+
return False
112+
113+
# Account for existing symlinks pointing outside download_dir
114+
target = download_dir / filename
115+
if target.is_symlink() and not target.resolve().is_relative_to(download_dir):
116+
return False
117+
118+
return True
80119

81120

82121
def get_request_session(uri):
@@ -106,16 +145,27 @@ def fetch_http(uri, to=None):
106145
if response.status_code != 200:
107146
raise requests.RequestException
108147

148+
download_directory = to or tempfile.mkdtemp()
149+
download_directory_path = Path(download_directory).resolve()
150+
download_directory_path.mkdir(parents=True, exist_ok=True)
151+
109152
content_disposition = response.headers.get("content-disposition", "")
110153
_, params = parse_header_parameters(content_disposition)
111-
filename = params.get("filename")
112-
if not filename:
154+
raw_filename = params.get("filename")
155+
156+
if raw_filename is not None and raw_filename.strip():
157+
filename = raw_filename.strip()
158+
if not is_safe_filename(filename, download_directory_path):
159+
raise ValueError(f"Invalid or unsafe filename: {raw_filename!r}")
160+
else:
113161
# Using `response.url` in place of provided `Scan.uri` since the former
114162
# will be more accurate in case of HTTP redirect.
115-
filename = unquote(Path(urlparse(response.url).path).name)
163+
raw_url_filename = unquote(Path(urlparse(response.url).path).name)
164+
filename = raw_url_filename.strip() if raw_url_filename else ""
165+
if not is_safe_filename(filename, download_directory_path):
166+
raise ValueError(f"Invalid or unsafe filename: {raw_url_filename!r}")
116167

117-
download_directory = to or tempfile.mkdtemp()
118-
output_file = Path(download_directory, filename)
168+
output_file = download_directory_path / filename
119169

120170
file_content = response.content
121171
with open(output_file, "wb") as f:

‎scanpipe/tests/pipes/test_fetch.py‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020
# ScanCode.io is a free software code scanning tool from nexB Inc. and others.
2121
# Visit https://github.com/nexB/scancode.io for support and download.
2222

23+
import os
2324
import socket
25+
import tempfile
2426
from pathlib import Path
2527
from unittest import mock
2628

@@ -94,6 +96,172 @@ def test_scanpipe_pipes_fetch_http(self, mock_get, mock_is_safe_url):
9496
downloaded_file = fetch.fetch_http(url)
9597
self.assertTrue(Path(downloaded_file.directory, "another_name.zip").exists())
9698

99+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
100+
@mock.patch("requests.sessions.Session.get")
101+
def test_scanpipe_pipes_fetch_http_content_disposition_traversal_attempts(
102+
self, mock_get, mock_is_safe_url
103+
):
104+
url = "https://example.com/filename.zip"
105+
invalid_filenames = [
106+
"../../evil.zip",
107+
"../evil.zip",
108+
"sub/dir/evil.zip",
109+
"..",
110+
".",
111+
]
112+
for invalid_name in invalid_filenames:
113+
headers = {"content-disposition": f'attachment; filename="{invalid_name}"'}
114+
mock_get.return_value = make_mock_response(url=url, headers=headers)
115+
with self.assertRaises(ValueError) as cm:
116+
fetch.fetch_http(url)
117+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
118+
119+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
120+
@mock.patch("requests.sessions.Session.get")
121+
def test_scanpipe_pipes_fetch_http_content_disposition_absolute_paths(
122+
self, mock_get, mock_is_safe_url
123+
):
124+
url = "https://example.com/filename.zip"
125+
invalid_filenames = [
126+
"/etc/passwd",
127+
"/evil.zip",
128+
"/var/test.zip",
129+
]
130+
for invalid_name in invalid_filenames:
131+
headers = {"content-disposition": f'attachment; filename="{invalid_name}"'}
132+
mock_get.return_value = make_mock_response(url=url, headers=headers)
133+
with self.assertRaises(ValueError) as cm:
134+
fetch.fetch_http(url)
135+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
136+
137+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
138+
@mock.patch("requests.sessions.Session.get")
139+
def test_scanpipe_pipes_fetch_http_content_disposition_windows_syntax(
140+
self, mock_get, mock_is_safe_url
141+
):
142+
url = "https://example.com/filename.zip"
143+
invalid_filenames = [
144+
r"..\..\evil.zip",
145+
r"C:\evil.zip",
146+
r"C:evil.zip",
147+
r"D:/evil.zip",
148+
r"\\server\share\evil.zip",
149+
]
150+
for invalid_name in invalid_filenames:
151+
headers = {"content-disposition": f'attachment; filename="{invalid_name}"'}
152+
mock_get.return_value = make_mock_response(url=url, headers=headers)
153+
with self.assertRaises(ValueError) as cm:
154+
fetch.fetch_http(url)
155+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
156+
157+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
158+
@mock.patch("requests.sessions.Session.get")
159+
def test_scanpipe_pipes_fetch_http_content_disposition_control_chars(
160+
self, mock_get, mock_is_safe_url
161+
):
162+
url = "https://example.com/filename.zip"
163+
invalid_filenames = [
164+
"evil\x00.zip",
165+
"evil\n.zip",
166+
"evil\r\ntest.zip",
167+
"evil\x1f.zip",
168+
"evil\x7f.zip",
169+
]
170+
for invalid_name in invalid_filenames:
171+
headers = {"content-disposition": f'attachment; filename="{invalid_name}"'}
172+
mock_get.return_value = make_mock_response(url=url, headers=headers)
173+
with self.assertRaises(ValueError) as cm:
174+
fetch.fetch_http(url)
175+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
176+
177+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
178+
@mock.patch("requests.sessions.Session.get")
179+
def test_scanpipe_pipes_fetch_http_content_disposition_empty_and_fallback(
180+
self, mock_get, mock_is_safe_url
181+
):
182+
url = "https://example.com/safe_fallback.zip"
183+
184+
# Empty filename parameter falls back to URL filename
185+
headers = {"content-disposition": 'attachment; filename=""'}
186+
mock_get.return_value = make_mock_response(url=url, headers=headers)
187+
downloaded = fetch.fetch_http(url)
188+
self.assertEqual("safe_fallback.zip", downloaded.filename)
189+
self.assertTrue(Path(downloaded.directory, "safe_fallback.zip").exists())
190+
191+
# Whitespace-only filename parameter falls back to URL filename
192+
headers = {"content-disposition": 'attachment; filename=" "'}
193+
mock_get.return_value = make_mock_response(url=url, headers=headers)
194+
downloaded = fetch.fetch_http(url)
195+
self.assertEqual("safe_fallback.zip", downloaded.filename)
196+
self.assertTrue(Path(downloaded.directory, "safe_fallback.zip").exists())
197+
198+
# Empty header filename and empty URL filename raises ValueError
199+
empty_path_url = "https://example.com/"
200+
headers = {"content-disposition": 'attachment; filename=""'}
201+
mock_get.return_value = make_mock_response(url=empty_path_url, headers=headers)
202+
with self.assertRaises(ValueError) as cm:
203+
fetch.fetch_http(empty_path_url)
204+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
205+
206+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
207+
@mock.patch("requests.sessions.Session.get")
208+
def test_scanpipe_pipes_fetch_http_content_disposition_safe_names(
209+
self, mock_get, mock_is_safe_url
210+
):
211+
url = "https://example.com/default.zip"
212+
safe_names = [
213+
"safe-release_v1.0.tar.gz",
214+
"report (final).pdf",
215+
"archive.bundle.zip",
216+
]
217+
for safe_name in safe_names:
218+
headers = {"content-disposition": f'attachment; filename="{safe_name}"'}
219+
mock_get.return_value = make_mock_response(url=url, headers=headers)
220+
downloaded = fetch.fetch_http(url)
221+
self.assertEqual(safe_name, downloaded.filename)
222+
self.assertEqual(downloaded.path, Path(downloaded.directory) / safe_name)
223+
self.assertTrue(downloaded.path.exists())
224+
self.assertGreater(downloaded.size, 0)
225+
self.assertTrue(downloaded.sha1)
226+
self.assertTrue(downloaded.md5)
227+
228+
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
229+
@mock.patch("requests.sessions.Session.get")
230+
def test_scanpipe_pipes_fetch_http_content_disposition_symlink(
231+
self, mock_get, mock_is_safe_url
232+
):
233+
url = "https://example.com/file.zip"
234+
headers = {"content-disposition": 'attachment; filename="link.zip"'}
235+
mock_get.return_value = make_mock_response(url=url, headers=headers)
236+
237+
with (
238+
tempfile.TemporaryDirectory() as temp_dir,
239+
tempfile.TemporaryDirectory() as outside_dir,
240+
):
241+
download_dir = Path(temp_dir)
242+
outside_target = Path(outside_dir) / "target.txt"
243+
symlink_path = download_dir / "link.zip"
244+
245+
can_symlink = True
246+
try:
247+
os.symlink(outside_target, symlink_path)
248+
except (OSError, NotImplementedError):
249+
can_symlink = False
250+
251+
if can_symlink:
252+
with self.assertRaises(ValueError) as cm:
253+
fetch.fetch_http(url, to=str(download_dir))
254+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
255+
self.assertFalse(outside_target.exists())
256+
else:
257+
with mock.patch.object(Path, "is_symlink", return_value=True):
258+
with mock.patch.object(
259+
Path, "resolve", return_value=outside_target.resolve()
260+
):
261+
with self.assertRaises(ValueError) as cm:
262+
fetch.fetch_http(url, to=str(download_dir))
263+
self.assertIn("Invalid or unsafe filename", str(cm.exception))
264+
97265
@mock.patch("scanpipe.pipes.fetch.is_safe_url", return_value=True)
98266
@mock.patch("requests.sessions.Session.get")
99267
def test_scanpipe_pipes_fetch_package_url(self, mock_get, mock_is_safe_url):

0 commit comments

Comments
 (0)