Scrapy, a fast high-level web crawling & scraping framework for Python.
Unbounded Content-Encoding decompression chain allows denial of service
Adrian Chaves06c866b557fa
diff --git a/docs/news.rst b/docs/news.rstindex a6dac942c..4e6358695 100644--- a/docs/news.rst+++ b/docs/news.rst@@ -40,6 +40,21 @@ Security bug fixes(:gh:`482`, :gh:`4583`, :gh:`6430`, :gh:`8417`, :gh:`8459`, :gh:`8460`)+- :class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`+ now decodes at most 1 content coding per response by default, and drops+ responses that apply more with :exc:`~scrapy.exceptions.IgnoreRequest`.++ In previous Scrapy versions, the number of content codings was unlimited,+ so a malicious server could send a response with a ``Content-Encoding``+ header that chains thousands of codings (e.g. ``gzip, gzip, gzip, …``) to+ make Scrapy run as many decompression passes, causing high CPU and memory+ usage. See the `j72p-v7rm-cwm3`_ security advisory for details.++ To allow more content codings per response, set the new+ :setting:`COMPRESSION_MAX_ENCODINGS` setting.++ .. _j72p-v7rm-cwm3: https://github.com/scrapy/scrapy/security/advisories/GHSA-j72p-v7rm-cwm3+Modified requirements~~~~~~~~~~~~~~~~~~~~~diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rstindex a7e0cb489..537cc9243 100644--- a/docs/topics/downloader-middleware.rst+++ b/docs/topics/downloader-middleware.rst@@ -809,6 +809,25 @@ Default: ``True``Whether the Compression middleware will be enabled.+.. setting:: COMPRESSION_MAX_ENCODINGS++COMPRESSION_MAX_ENCODINGS+^^^^^^^^^^^^^^^^^^^^^^^^^++.. versionadded:: 2.20.0++Default: ``1``++Maximum number of chained content codings that+:class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`+decodes from the ``Content-Encoding`` of a response. A response that chains+more codings than this is dropped with :exc:`~scrapy.exceptions.IgnoreRequest`.++Raise it only to scrape servers that legitimately apply multiple codings to a+response, keeping in mind that a high value lets a malicious server force many+decompression passes.++HttpProxyMiddleware-------------------diff --git a/scrapy/downloadermiddlewares/httpcompression.py b/scrapy/downloadermiddlewares/httpcompression.pyindex 3fa7db59e..4d35dbbb8 100644--- a/scrapy/downloadermiddlewares/httpcompression.py+++ b/scrapy/downloadermiddlewares/httpcompression.py@@ -44,6 +44,12 @@ ACCEPTED_ENCODINGS: list[bytes] = [b"gzip", b"deflate", b"br", b"zstd"]_THREAD_DECODE_MIN_SIZE = 8192+class _MaxEncodingCountExceeded(ValueError):+ def __init__(self, count: int, max_count: int) -> None:+ self.count = count+ self.max_count = max_count++class HttpCompressionMiddleware:"""This middleware allows compressed (gzip, deflate etc.) traffic to besent/received from websites"""@@ -64,10 +70,12 @@ class HttpCompressionMiddleware:self.stats = statsself._max_size = 1073741824self._warn_size = 33554432+ self._max_encodings = 1returnself.stats = crawler.statsself._max_size = crawler.settings.getint("DOWNLOAD_MAXSIZE")self._warn_size = crawler.settings.getint("DOWNLOAD_WARNSIZE")+ self._max_encodings = crawler.settings.getint("COMPRESSION_MAX_ENCODINGS")crawler.signals.connect(self.open_spider, signals.spider_opened)@classmethod@@ -119,6 +127,14 @@ class HttpCompressionMiddleware:)logger.warning(msg)raise IgnoreRequest(msg) from e+ except _MaxEncodingCountExceeded as e:+ msg = (+ f"Ignored response {response} because its Content-Encoding "+ f"header lists {e.count} supported encodings, which exceeds "+ f"COMPRESSION_MAX_ENCODINGS ({e.max_count})."+ )+ logger.warning(msg)+ raise IgnoreRequest(msg) from eexcept _DECOMPRESSION_ERRORS as e:encodings = b", ".join(content_encoding).decode()raise DecompressionError(@@ -156,6 +172,8 @@ class HttpCompressionMiddleware:self, body: bytes, content_encoding: list[bytes], max_size: int) -> tuple[bytes, list[bytes]]:to_decode, to_keep = self._split_encodings(content_encoding)+ if len(to_decode) > self._max_encodings:+ raise _MaxEncodingCountExceeded(len(to_decode), self._max_encodings)for encoding in to_decode:if len(body) >= _THREAD_DECODE_MIN_SIZE:body = await run_in_thread(self._decode, body, encoding, max_size)diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.pyindex 0a86215e5..d17fc8118 100644--- a/scrapy/settings/default_settings.py+++ b/scrapy/settings/default_settings.py@@ -43,6 +43,7 @@ __all__ = ["CLOSESPIDER_TIMEOUT_NO_ITEM","COMMANDS_MODULE","COMPRESSION_ENABLED",+ "COMPRESSION_MAX_ENCODINGS","CONCURRENT_CONNECTIONS_PER_HANDLER","CONCURRENT_ITEMS","CONCURRENT_REQUESTS",@@ -278,6 +279,7 @@ CLOSESPIDER_TIMEOUT_NO_ITEM = 0COMMANDS_MODULE = ""COMPRESSION_ENABLED = True+COMPRESSION_MAX_ENCODINGS = 1CONCURRENT_CONNECTIONS_PER_HANDLER = Nonediff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.pyindex 40b5fc3d3..c20c2c3b0 100644--- a/tests/test_downloadermiddleware_httpcompression.py+++ b/tests/test_downloadermiddleware_httpcompression.py@@ -66,6 +66,12 @@ class TestHttpCompression:self.mw = build_from_crawler(HttpCompressionMiddleware, self.crawler)self.crawler.stats.open_spider()+ def _mw(self, max_encodings: int) -> HttpCompressionMiddleware:+ crawler = get_crawler(+ Spider, settings_dict={"COMPRESSION_MAX_ENCODINGS": max_encodings}+ )+ return build_from_crawler(HttpCompressionMiddleware, crawler)+def _getresponse(self, coding: str) -> Response:if coding not in FORMAT:raise ValueError@@ -255,7 +261,7 @@ class TestHttpCompression:response = self._getresponse("gzip-deflate")assert response.requestrequest = response.request- newresponse = await self.mw.process_response(request, response)+ newresponse = await self._mw(2).process_response(request, response)assert newresponse is not responseassert "Content-Encoding" not in newresponse.headersassert newresponse.body.startswith(b"<!DOCTYPE")@@ -292,7 +298,7 @@ class TestHttpCompression:response.headers["Content-Encoding"] = ["gzip", "deflate"]assert response.requestrequest = response.request- newresponse = await self.mw.process_response(request, response)+ newresponse = await self._mw(2).process_response(request, response)assert newresponse is not responseassert "Content-Encoding" not in newresponse.headersassert newresponse.body.startswith(b"<!DOCTYPE")@@ -313,7 +319,7 @@ class TestHttpCompression:response.headers["Content-Encoding"] = ["gzip", "deflate, gzip"]assert response.requestrequest = response.request- newresponse = await self.mw.process_response(request, response)+ newresponse = await self._mw(3).process_response(request, response)assert newresponse is not responseassert "Content-Encoding" not in newresponse.headersassert newresponse.body.startswith(b"<!DOCTYPE")@@ -330,6 +336,31 @@ class TestHttpCompression:assert newresponse is not responseassert newresponse.headers.getlist("Content-Encoding") == [b"gzip", b"foo"]+ @coroutine_test+ async def test_max_encodings_default(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ response = self._getresponse("gzip-deflate")+ assert response.request+ request = response.request+ with (+ caplog.at_level(+ WARNING, logger="scrapy.downloadermiddlewares.httpcompression"+ ),+ pytest.raises(IgnoreRequest),+ ):+ await self.mw.process_response(request, response)+ assert "COMPRESSION_MAX_ENCODINGS (1)" in caplog.text++ @coroutine_test+ async def test_max_encodings_rejects_before_decompressing(self) -> None:+ response = self._getresponse("gzip")+ response.headers["Content-Encoding"] = [b", ".join([b"gzip"] * 5000)]+ assert response.request+ request = response.request+ with pytest.raises(IgnoreRequest, match="lists 5000 supported encodings"):+ await self.mw.process_response(request, response)+@coroutine_testasync def test_process_response_encoding_inside_body(self):headers = {