Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions Lib/email/_header_value_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3080,14 +3080,25 @@ def _fold_mime_parameters(part, lines, maxlen, encoding):
# have that, we'd be stuck, so in that case fall back to
# the RFC standard width.
maxlen = 78
splitpoint = maxchars = maxlen - chrome_len - 2
while True:
maxchars = maxlen - chrome_len - 2
# Ensure maxchars is at least 1 to prevent negative values
if maxchars <= 0:
maxchars = 1
splitpoint = maxchars
splitpoint = max(1, splitpoint) # Ensure splitpoint is always at least 1
while splitpoint > 1:
partial = value[:splitpoint]
encoded_value = urllib.parse.quote(
partial, safe='', errors=error_handler)
if len(encoded_value) <= maxchars:
break
splitpoint -= 1
# If we still can't fit, force a minimal split
if splitpoint <= 1:
splitpoint = 1
partial = value[:splitpoint]
encoded_value = urllib.parse.quote(
partial, safe='', errors=error_handler)
lines.append(" {}*{}*={}{}".format(
name, section, extra_chrome, encoded_value))
extra_chrome = ''
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_email/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,24 @@ def test_string_payload_with_multipart_content_type(self):
attachments = msg.iter_attachments()
self.assertEqual(list(attachments), [])

def test_mime_parameter_folding_no_infinite_loop(self):
msg = self._make_message()
msg.add_attachment(
b"test content",
maintype="text",
subtype="plain",
filename="test.txt"
)
maxlen = 78 # Standard RFC line length
extra_chrome = "utf-8''" # charset + encoding info
section = 0
min_name_len = maxlen - 3 - len(str(section)) - 3 - len(extra_chrome)
long_param_name = "a" * min_name_len
long_param_value = "b" * 100
msg.set_param(long_param_name, long_param_value)
result = msg.as_string()
self.assertIsInstance(result, str)
self.assertIn(long_param_name, result)

if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix infinite loop in email.message.EmailMessage.as_string() when
add_attachment() is called with very long parameter keys. This could cause
denial of service by hanging the application indefinitely during MIME
parameter folding and RFC 2231 encoding.
Loading