Skip to content

Commit 2712a3c

Browse files
Fix multipart injection (#12104) (#12109)
(cherry picked from commit dab9e87) Co-authored-by: mingi jung <[email protected]>
1 parent b4f67b1 commit 2712a3c

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

aiohttp/formdata.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ def add_field(
7979
raise TypeError(
8080
"content_type must be an instance of str. Got: %s" % content_type
8181
)
82+
if "\r" in content_type or "\n" in content_type:
83+
raise ValueError(
84+
"Newline or carriage return detected in headers. "
85+
"Potential header injection attack."
86+
)
8287
headers[hdrs.CONTENT_TYPE] = content_type
8388
self._is_multipart = True
8489
if content_transfer_encoding is not None:

tests/test_formdata.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,18 @@ async def test_formdata_textio_charset(buf: bytearray, writer) -> None:
6767
assert b"\x93\xfa\x96{" in buf
6868

6969

70-
def test_invalid_formdata_content_type() -> None:
70+
@pytest.mark.parametrize("val", (0, 0.1, {}, [], b"foo"))
71+
def test_invalid_type_formdata_content_type(val: object) -> None:
7172
form = FormData()
72-
invalid_vals = [0, 0.1, {}, [], b"foo"]
73-
for invalid_val in invalid_vals:
74-
with pytest.raises(TypeError):
75-
form.add_field("foo", "bar", content_type=invalid_val)
73+
with pytest.raises(TypeError):
74+
form.add_field("foo", "bar", content_type=val) # type: ignore[arg-type]
75+
76+
77+
@pytest.mark.parametrize("val", ("\r", "\n", "a\ra\n", "a\na\r"))
78+
def test_invalid_value_formdata_content_type(val: str) -> None:
79+
form = FormData()
80+
with pytest.raises(ValueError):
81+
form.add_field("foo", "bar", content_type=val)
7682

7783

7884
def test_invalid_formdata_filename() -> None:

0 commit comments

Comments
 (0)