diff --git a/Lib/email/header.py b/Lib/email/header.py index ea1f84ea964ca6..20b9d78397d861 100644 --- a/Lib/email/header.py +++ b/Lib/email/header.py @@ -87,29 +87,34 @@ def decode_header(header): # (encoded_string, encoding, charset). For unencoded strings, the last # two parts will be None. words = [] + # Whether the word that originally preceded words[-1] was encoded. + # Whitespace between two encoded words is dropped (see below); the + # check must use the original neighbours, not those left after a drop. + prev_encoded = False for line in header.splitlines(): - parts = ecre.split(line) - first = True - while parts: - unencoded = parts.pop(0) - if first: - unencoded = unencoded.lstrip() - first = False + # ecre has three groups, so split() returns an unencoded chunk + # followed by zero or more (charset, encoding, encoded, unencoded) + # groups. Iterate rather than popping from the front of the list, + # which is quadratic in the number of encoded words. + parts = iter(ecre.split(line)) + unencoded = next(parts).lstrip() + while True: if unencoded: + prev_encoded = bool(words) and bool(words[-1][1]) words.append((unencoded, None, None)) - if parts: - charset = parts.pop(0).lower() - encoding = parts.pop(0).lower() - encoded = parts.pop(0) - words.append((encoded, encoding, charset)) - # Now loop over words and remove words that consist of whitespace - # between two encoded strings. - droplist = [] - for n, w in enumerate(words): - if n>1 and w[1] and words[n-2][1] and words[n-1][0].isspace(): - droplist.append(n-1) - for d in reversed(droplist): - del words[d] + charset = next(parts, None) + if charset is None: + break + encoding = next(parts).lower() + encoded = next(parts) + last_encoded = bool(words) and bool(words[-1][1]) + # Remove a word that consists of whitespace between two + # encoded strings. + if prev_encoded and words[-1][0].isspace(): + words.pop() + prev_encoded = last_encoded + words.append((encoded, encoding, charset.lower())) + unencoded = next(parts) # The next step is to decode each encoded word by applying the reverse # base64 or quopri transformation. decoded_words is now a list of the @@ -135,27 +140,34 @@ def decode_header(header): else: raise AssertionError('Unexpected encoding: ' + encoding) # Now convert all words to bytes and collapse consecutive runs of - # similarly encoded words. + # similarly encoded words. Collect each run in a list and join once, + # since repeated bytes concatenation is quadratic. collapsed = [] - last_word = last_charset = None + run = None + last_charset = None for word, charset in decoded_words: if isinstance(word, str): word = bytes(word, 'raw-unicode-escape') - if last_word is None: - last_word = word + if run is None: + run = [word] last_charset = charset elif charset != last_charset: - collapsed.append((last_word, last_charset)) - last_word = word + collapsed.append((_join_run(run, last_charset), last_charset)) + run = [word] last_charset = charset - elif last_charset is None: - last_word += BSPACE + word else: - last_word += word - collapsed.append((last_word, last_charset)) + run.append(word) + collapsed.append((_join_run(run, last_charset) if run else None, + last_charset)) return collapsed +def _join_run(run, charset): + if len(run) == 1: + return run[0] + return (BSPACE if charset is None else b'').join(run) + + def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '): """Create a Header from a sequence of pairs as returned by decode_header() diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index 2a5794a5b66fc5..f3ca49b7fda504 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -2425,6 +2425,33 @@ def test_rfc2047_with_whitespace(self): (b' rg ', None), (b'\xe5', 'iso-8859-1'), (b' sbord', None)]) + def test_rfc2047_whitespace_between_encoded_words(self): + # Whitespace between two encoded words is dropped, judged by the + # words' original neighbours, even if a neighbour is itself an + # encoded word that decodes to whitespace. + eq = self.assertEqual + eq(decode_header('=?utf-8?q?a?= =?utf-8?q? ?==?utf-8?q?b?= ' + '=?utf-8?q?c?='), + [(b'a bc', 'utf-8')]) + eq(decode_header('=?utf-8?q?a?= =?utf-8?q? ?= =?utf-8?q?b?='), + [(b'a b', 'utf-8')]) + eq(decode_header('x =?utf-8?q?a?= =?iso-8859-1?q?b?= ' + '=?utf-8?q?c?= y'), + [(b'x ', None), (b'a', 'utf-8'), (b'b', 'iso-8859-1'), + (b'c', 'utf-8'), (b' y', None)]) + + def test_rfc2047_many_encoded_words(self): + # gh-136063: decoding used to take quadratic time in the number + # of encoded words. + n = 100_000 + s = ' '.join(['=?utf-8?q?ab?='] * n) + self.assertEqual(decode_header(s), [(b'ab' * n, 'utf-8')]) + s = ' '.join(['=?utf-8?q?ab?=', 'x'] * n) + dh = decode_header(s) + self.assertEqual(len(dh), 2 * n) + self.assertEqual(dh[:3], [(b'ab', 'utf-8'), (b' x ', None), + (b'ab', 'utf-8')]) + def test_rfc2047_B_bad_padding(self): s = '=?iso-8859-1?B?%s?=' data = [ # only test complete bytes diff --git a/Misc/NEWS.d/next/Security/2026-11-25-09-10-00.gh-issue-136063.dHq7Lw.rst b/Misc/NEWS.d/next/Security/2026-11-25-09-10-00.gh-issue-136063.dHq7Lw.rst new file mode 100644 index 00000000000000..d2fae44a7548c0 --- /dev/null +++ b/Misc/NEWS.d/next/Security/2026-11-25-09-10-00.gh-issue-136063.dHq7Lw.rst @@ -0,0 +1,2 @@ +:mod:`email.header`: ensure linear complexity for :func:`~email.header.decode_header` +when decoding headers containing many :rfc:`2047` encoded words.