diff --git a/CHANGES/14585.feature.rst b/CHANGES/14585.feature.rst new file mode 100644 index 00000000000..7e8ba4165c1 --- /dev/null +++ b/CHANGES/14585.feature.rst @@ -0,0 +1,6 @@ +Added a ``max_nesting_depth`` parameter to :class:`~aiohttp.MultipartReader` +(default ``10``). A ``multipart/*`` part nested deeper than the limit now +raises ``BadHttpMessage`` instead of building +another reader, so a small, deeply nested body no longer drives +:meth:`~aiohttp.MultipartReader.release` into ``RecursionError`` +-- by :user:`Franco944796`. diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 44b0649a814..f193b6364d5 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -152,6 +152,7 @@ Felix Yan Fernanda Guimarães FichteFoll Florian Scheffler +Franco Insua Franek Magiera Frederik Gladhorn Frederik Peter Aalund diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 498afcb0733..8900f149b36 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -693,7 +693,7 @@ boundary at which user-supplied strings can become wire bytes. | :--- | :--- | :--- | :--- | | 4.1 | Boundary parameter | 70-char cap; missing-boundary raises; HTTP header layer ([§5.1](#51-http1-parser)) catches CR/LF/NUL. | None. | | 4.2 | Many small parts | `client_max_size` caps total bytes. `Request.post()` additionally caps the number of form fields at `client_max_fields` (default `1000`, `0` disables) since PR #13738: multipart parts are counted before each part is read, and urlencoded bodies are rejected by `yarl.query_to_pairs` before any pair is materialised. Both paths raise `HTTPRequestEntityTooLarge`. | The cap only covers `Request.post()`. Direct `MultipartReader` / `Request.multipart()` users still get an unbounded part count; a `max_parts` parameter on `MultipartReader` would close that path. **User**: operators sensitive to live-object count should reduce `client_max_fields` and `client_max_size`. | -| 4.3 | Nested-multipart recursion | `Request.post()` rejects any nested multipart with `ValueError` ("To decode nested multipart you need to use custom reader") (`web_request.py:BaseRequest.post`). | **Direct `MultipartReader` users get unlimited recursion. Add a `max_nesting_depth` parameter (default e.g. 10) to fail cleanly before `RecursionError`.** | +| 4.3 | Nested-multipart recursion | `Request.post()` rejects any nested multipart with `ValueError` ("To decode nested multipart you need to use custom reader") (`web_request.py:BaseRequest.post`). `MultipartReader` takes `max_nesting_depth` (default `10`) since PR #14585: each nested reader gets one level less, and a part nested deeper raises `BadHttpMessage` before another reader is built (`multipart.py:MultipartReader._get_part_reader`). | None. | | 4.4 | Per-part headers bounded | `max_field_size` / `max_headers` plumbed since 5fe9dfb64 (Mar 2026). | None. | | 4.5 | Per-part body bounded | Per-iteration size check since 9cc4b917c (Mar 2026). | None. | | 4.6 | Filename path traversal | None; verbatim return is the documented behaviour. | **User**: sanitise `BodyPartReader.filename` before opening / saving / reflecting (strip path components, control bytes, known-bad sequences). | @@ -733,6 +733,9 @@ boundary at which user-supplied strings can become wire bytes. multipart header-injection path through `MultipartWriter.append(headers=...)` and `Payload(headers=...)` that the main HTTP writer's `_safe_header` check did not cover (threat 4.13). +- **Hardening, no advisory** (PR #14585) — `MultipartReader` gained + `max_nesting_depth` (default `10`), so deeply nested `multipart/*` + input raises `BadHttpMessage` instead of `RecursionError` (threat 4.3). - **PR #12721** (3.14.0) — companion to GHSA-m6qw-4cw2-hm4m: `FormData.add_field` now rejects CR / LF / NUL in `name` and `filename` (in addition to the previous `content_type` check), so the diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py index 9b9d80efe8d..4c9647aae1f 100644 --- a/aiohttp/multipart.py +++ b/aiohttp/multipart.py @@ -787,6 +787,7 @@ def __init__( max_field_size: int = 8190, max_headers: int = 128, max_size_error_cls: type[Exception] = ValueError, + max_nesting_depth: int = 10, ) -> None: self._mimetype = parse_mimetype(headers[CONTENT_TYPE]) assert self._mimetype.type == "multipart", "multipart/* content type expected" @@ -804,6 +805,7 @@ def __init__( self._max_field_size = max_field_size self._max_headers = max_headers self._max_size_error_cls = max_size_error_cls + self._max_nesting_depth = max_nesting_depth self._at_eof = False self._at_bof = True self._unread: list[bytes] = [] @@ -902,6 +904,8 @@ def _get_part_reader( mimetype = parse_mimetype(ctype) if mimetype.type == "multipart": + if self._max_nesting_depth <= 0: + raise BadHttpMessage("Multipart body is nested too deeply") if self.multipart_reader_cls is None: return type(self)( headers, @@ -910,6 +914,7 @@ def _get_part_reader( max_field_size=self._max_field_size, max_headers=self._max_headers, max_size_error_cls=self._max_size_error_cls, + max_nesting_depth=self._max_nesting_depth - 1, ) return self.multipart_reader_cls( headers, @@ -918,6 +923,7 @@ def _get_part_reader( max_field_size=self._max_field_size, max_headers=self._max_headers, max_size_error_cls=self._max_size_error_cls, + max_nesting_depth=self._max_nesting_depth - 1, ) else: return self.part_reader_cls( diff --git a/docs/multipart_reference.rst b/docs/multipart_reference.rst index 78cfc7f3ea1..e9c44cfc366 100644 --- a/docs/multipart_reference.rst +++ b/docs/multipart_reference.rst @@ -169,11 +169,19 @@ Multipart reference Readonly :class:`str` property. -.. class:: MultipartReader(headers, content) +.. class:: MultipartReader(headers, content, *, max_nesting_depth=10) :canonical: aiohttp.multipart.MultipartReader Multipart body reader. + :param int max_nesting_depth: how many levels of nested ``multipart/*`` + parts the reader accepts below itself. Each nested reader gets one + level less; a part nested deeper raises + ``BadHttpMessage`` instead of building + another reader. ``0`` rejects any nested multipart part. + + .. versionadded:: 3.15 + .. classmethod:: from_response(cls, response) Constructs reader instance from HTTP response. diff --git a/tests/test_multipart.py b/tests/test_multipart.py index 773c0fc61c7..cfb0d7012c7 100644 --- a/tests/test_multipart.py +++ b/tests/test_multipart.py @@ -25,6 +25,7 @@ CONTENT_TYPE, ) from aiohttp.helpers import DEFAULT_CHUNK_SIZE, HeadersDictProxy, parse_mimetype +from aiohttp.http_exceptions import BadHttpMessage from aiohttp.multipart import ( _QP_BLOCK_SIZE, BodyPartReader, @@ -106,6 +107,17 @@ def __exit__( self.content.close() +def nested_multipart_body(depth: int) -> bytes: + """Build a multipart/mixed body with ``depth`` nested multipart parts.""" + head = "".join( + f"--b{i}\r\nContent-Type: multipart/mixed; boundary=b{i + 1}\r\n\r\n" + for i in range(depth) + ) + inner = f"--b{depth}\r\nContent-Type: text/plain\r\n\r\nx\r\n--b{depth}--\r\n" + tail = "".join(f"\r\n--b{i}--\r\n" for i in reversed(range(depth))) + return (head + inner + tail).encode() + + class Response: def __init__(self, headers: HeadersDictProxy, content: Stream) -> None: self.headers = headers @@ -1005,6 +1017,64 @@ async def test_release(self) -> None: await reader.release() assert reader.at_eof() + async def test_nesting_within_max_nesting_depth(self) -> None: + with Stream(nested_multipart_body(3)) as stream: + reader: MultipartReader | BodyPartReader | None + reader = aiohttp.MultipartReader( + {CONTENT_TYPE: "multipart/mixed; boundary=b0"}, + stream, + max_nesting_depth=3, + ) + for _ in range(3): + assert isinstance(reader, MultipartReader) + reader = await reader.next() + assert isinstance(reader, MultipartReader) + part = await reader.next() + assert isinstance(part, BodyPartReader) + assert await part.read() == b"x" + + async def test_nesting_beyond_max_nesting_depth(self) -> None: + with Stream(nested_multipart_body(4)) as stream: + reader: MultipartReader | BodyPartReader | None + reader = aiohttp.MultipartReader( + {CONTENT_TYPE: "multipart/mixed; boundary=b0"}, + stream, + max_nesting_depth=3, + ) + for _ in range(3): + assert isinstance(reader, MultipartReader) + reader = await reader.next() + assert isinstance(reader, MultipartReader) + with pytest.raises(BadHttpMessage, match="nested too deeply"): + await reader.next() + + async def test_nesting_depth_with_custom_reader_cls(self) -> None: + class CustomReader(aiohttp.MultipartReader): + pass + + CustomReader.multipart_reader_cls = CustomReader + with Stream(nested_multipart_body(2)) as stream: + reader = CustomReader( + {CONTENT_TYPE: "multipart/mixed; boundary=b0"}, + stream, + max_nesting_depth=1, + ) + nested = await reader.next() + assert isinstance(nested, CustomReader) + with pytest.raises(BadHttpMessage, match="nested too deeply"): + await nested.next() + + async def test_release_deeply_nested_body(self) -> None: + # Without a depth limit, release() recursed once per nesting level + # and a ~70 KB body raised RecursionError. + with Stream(nested_multipart_body(1000)) as stream: + reader = aiohttp.MultipartReader( + {CONTENT_TYPE: "multipart/mixed; boundary=b0"}, + stream, + ) + with pytest.raises(BadHttpMessage, match="nested too deeply"): + await reader.release() + async def test_release_release(self) -> None: with Stream(b"--:\r\n\r\necho\r\n--:--") as stream: reader = aiohttp.MultipartReader(