Skip to content

Commit c67d8f9

Browse files
vstinnertdwyer
andcommitted
gh-102988: email parseaddr() now rejects malformed address
Detect email address parsing errors and return empty tuple to indicate the parsing error (old API). Add an optional 'strict' parameter to getaddresses() and parseaddr() functions. Patch by Thomas Dwyer. Co-Authored-By: Thomas Dwyer <[email protected]>
1 parent ff4e53c commit c67d8f9

File tree

5 files changed

+209
-37
lines changed

5 files changed

+209
-37
lines changed

Doc/library/email.utils.rst

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ of the new API.
6565
*email address* parts. Returns a tuple of that information, unless the parse
6666
fails, in which case a 2-tuple of ``('', '')`` is returned.
6767

68+
If *strict* is true, use a strict parser which rejects malformed inputs.
69+
70+
.. versionchanged:: 3.13
71+
Add *strict* optional parameter and reject malformed inputs by default.
72+
6873

6974
.. function:: formataddr(pair, charset='utf-8')
7075

@@ -82,12 +87,15 @@ of the new API.
8287
Added the *charset* option.
8388

8489

85-
.. function:: getaddresses(fieldvalues)
90+
.. function:: getaddresses(fieldvalues, *, strict=True)
8691

8792
This method returns a list of 2-tuples of the form returned by ``parseaddr()``.
8893
*fieldvalues* is a sequence of header field values as might be returned by
89-
:meth:`Message.get_all <email.message.Message.get_all>`. Here's a simple
90-
example that gets all the recipients of a message::
94+
:meth:`Message.get_all <email.message.Message.get_all>`.
95+
96+
If *strict* is true, use a strict parser which rejects malformed inputs.
97+
98+
Here's a simple example that gets all the recipients of a message::
9199

92100
from email.utils import getaddresses
93101

@@ -97,6 +105,9 @@ of the new API.
97105
resent_ccs = msg.get_all('resent-cc', [])
98106
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
99107

108+
.. versionchanged:: 3.13
109+
Add *strict* optional parameter and reject malformed inputs by default.
110+
100111

101112
.. function:: parsedate(date)
102113

Doc/whatsnew/3.13.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,17 @@ doctest
157157
:attr:`doctest.TestResults.skipped` attributes.
158158
(Contributed by Victor Stinner in :gh:`108794`.)
159159

160+
email
161+
-----
162+
163+
* :func:`email.utils.getaddresses` and :func:`email.utils.parseaddr` now return
164+
``('', '')`` 2-tuples in more situations where invalid email addresses are
165+
encountered instead of potentially inaccurate values. Add optional *strict*
166+
parameter to these two functions: use ``strict=False`` to get the old
167+
behavior, accept malformed inputs.
168+
(Contributed by Thomas Dwyer for :gh:`102988` to ameliorate CVE-2023-27043
169+
fix.)
170+
160171
io
161172
--
162173

Lib/email/utils.py

Lines changed: 85 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,70 @@ def formataddr(pair, charset='utf-8'):
103103
return address
104104

105105

106+
def _pre_parse_validation(email_header_fields):
107+
accepted_values = []
108+
for v in email_header_fields:
109+
s = v.replace('\\(', '').replace('\\)', '')
110+
if s.count('(') != s.count(')'):
111+
v = "('', '')"
112+
accepted_values.append(v)
106113

107-
def getaddresses(fieldvalues):
108-
"""Return a list of (REALNAME, EMAIL) for each fieldvalue."""
109-
all = COMMASPACE.join(str(v) for v in fieldvalues)
110-
a = _AddressList(all)
111-
return a.addresslist
114+
return accepted_values
115+
116+
117+
def _post_parse_validation(parsed_email_header_tuples):
118+
accepted_values = []
119+
# The parser would have parsed a correctly formatted domain-literal
120+
# The existence of an [ after parsing indicates a parsing failure
121+
for v in parsed_email_header_tuples:
122+
if '[' in v[1]:
123+
v = ('', '')
124+
accepted_values.append(v)
125+
126+
return accepted_values
127+
128+
129+
realname_comma_re = re.compile(r'"[^"]*,[^"]*"')
130+
131+
def getaddresses(fieldvalues, *, strict=True):
132+
"""Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue.
133+
134+
When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in
135+
its place.
136+
137+
If the resulting list of parsed address is greater than number of
138+
fieldvalues in the input list a parsing error has occurred, so a list
139+
containing a single empty 2-tuple [('', '')] is returned in its place.
140+
This is done to avoid invalid output.
141+
142+
Malformed input: getaddresses(['[email protected] <[email protected]>'])
143+
Invalid output: [('', '[email protected]'), ('', '[email protected]')]
144+
Safe output: [('', '')]
145+
146+
If strict is true, use a strict parser which rejects malformed inputs.
147+
"""
148+
if strict:
149+
fieldvalues = [str(v) for v in fieldvalues]
150+
fieldvalues = _pre_parse_validation(fieldvalues)
151+
all = COMMASPACE.join(v for v in fieldvalues)
152+
a = _AddressList(all)
153+
result = _post_parse_validation(a.addresslist)
154+
155+
# When a comma is used in the Real Name part it is not a deliminator
156+
# So strip those out before counting the commas
157+
n = 0
158+
for v in fieldvalues:
159+
v = realname_comma_re.sub('', v)
160+
n += v.count(',') + 1
161+
162+
if len(result) != n:
163+
return [('', '')]
164+
165+
return result
166+
else:
167+
all = COMMASPACE.join(str(v) for v in fieldvalues)
168+
a = _AddressList(all)
169+
return a.addresslist
112170

113171

114172
def _format_timetuple_and_zone(timetuple, zone):
@@ -207,17 +265,34 @@ def parsedate_to_datetime(data):
207265
tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
208266

209267

210-
def parseaddr(addr):
268+
def parseaddr(addr, *, strict=True):
211269
"""
212270
Parse addr into its constituent realname and email address parts.
213271
214272
Return a tuple of realname and email address, unless the parse fails, in
215273
which case return a 2-tuple of ('', '').
274+
275+
If strict is true, use a strict parser which rejects malformed inputs.
216276
"""
217-
addrs = _AddressList(addr).addresslist
218-
if not addrs:
219-
return '', ''
220-
return addrs[0]
277+
if strict:
278+
if isinstance(addr, list):
279+
addr = addr[0]
280+
281+
if not isinstance(addr, str):
282+
return ('', '')
283+
284+
addr = _pre_parse_validation([addr])[0]
285+
addrs = _post_parse_validation(_AddressList(addr).addresslist)
286+
287+
if not addrs or len(addrs) > 1:
288+
return ('', '')
289+
290+
return addrs[0]
291+
else:
292+
addrs = _AddressList(addr).addresslist
293+
if not addrs:
294+
return '', ''
295+
return addrs[0]
221296

222297

223298
# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.

Lib/test/test_email/test_email.py

Lines changed: 93 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3320,32 +3320,101 @@ def test_getaddresses(self):
33203320
[('Al Person', '[email protected]'),
33213321
('Bud Person', '[email protected]')])
33223322

3323-
def test_getaddresses_comma_in_name(self):
3324-
"""GH-106669 regression test."""
3325-
self.assertEqual(
3326-
utils.getaddresses(
3327-
[
3328-
'"Bud, Person" <[email protected]>',
3329-
'[email protected] (Al Person)',
3330-
'"Mariusz Felisiak" <[email protected]>',
3331-
]
3332-
),
3333-
[
3334-
('Bud, Person', '[email protected]'),
3335-
('Al Person', '[email protected]'),
3336-
('Mariusz Felisiak', '[email protected]'),
3337-
],
3338-
)
3323+
def test_parsing_errors(self):
3324+
"""Test for parsing errors from CVE-2023-27043 and CVE-2019-16056"""
3325+
3326+
3327+
empty = ('', '')
3328+
3329+
# Test utils.getaddresses() and utils.parseaddr() on malformed email
3330+
# addresses: default behavior (strict=True) rejects malformed address,
3331+
# and strict=True which tolerates malformed address.
3332+
for invalid_separator, expected_non_strict in (
3333+
('(', [(f'<{bob}>', alice)]),
3334+
(')', [('', alice), empty, ('', bob)]),
3335+
('<', [('', alice), empty, ('', bob), empty]),
3336+
('>', [('', alice), empty, ('', bob)]),
3337+
('[', [('', f'{alice}[<{bob}>]')]),
3338+
(']', [('', alice), empty, ('', bob)]),
3339+
('@', [empty, empty, ('', bob)]),
3340+
(';', [('', alice), empty, ('', bob)]),
3341+
(':', [('', alice), ('', bob)]),
3342+
('.', [('', alice + '.'), ('', bob)]),
3343+
('"', [('', alice), ('', f'<{bob}>')]),
3344+
):
3345+
address = f'{alice}{invalid_separator}<{bob}>'
3346+
with self.subTest(address=address):
3347+
self.assertEqual(utils.getaddresses([address]),
3348+
[empty])
3349+
self.assertEqual(utils.getaddresses([address], strict=False),
3350+
expected_non_strict)
3351+
3352+
self.assertEqual(utils.parseaddr([address]),
3353+
empty)
3354+
self.assertEqual(utils.parseaddr([address], strict=False),
3355+
('', address))
3356+
3357+
# Comma (',') is treated differently depending on strict parameter.
3358+
# Comma without quotes.
3359+
address = f'{alice},<{bob}>'
3360+
self.assertEqual(utils.getaddresses([address]),
3361+
[('', alice), ('', bob)])
3362+
self.assertEqual(utils.parseaddr([address]),
3363+
empty)
3364+
self.assertEqual(utils.parseaddr([address], strict=False),
3365+
('', address))
3366+
3367+
# Comma with quotes.
3368+
address = '"Alice, [email protected]" <[email protected]>'
3369+
expected_strict = ('Alice, [email protected]', '[email protected]')
3370+
self.assertEqual(utils.getaddresses([address]), [expected_strict])
3371+
self.assertEqual(utils.parseaddr([address]), expected_strict)
3372+
self.assertEqual(utils.parseaddr([address], strict=False),
3373+
('', address))
33393374

33403375
def test_getaddresses_nasty(self):
3341-
eq = self.assertEqual
3342-
eq(utils.getaddresses(['foo: ;']), [('', '')])
3343-
eq(utils.getaddresses(
3344-
['[]*-- =~$']),
3345-
[('', ''), ('', ''), ('', '*--')])
3346-
eq(utils.getaddresses(
3347-
['foo: ;', '"Jason R. Mastaler" <[email protected]>']),
3348-
[('', ''), ('Jason R. Mastaler', '[email protected]')])
3376+
for addresses, expected in (
3377+
(['"Sürname, Firstname" <[email protected]>'],
3378+
[('Sürname, Firstname', '[email protected]')]),
3379+
3380+
(['foo: ;'],
3381+
[('', '')]),
3382+
3383+
(['foo: ;', '"Jason R. Mastaler" <[email protected]>'],
3384+
[('', ''), ('Jason R. Mastaler', '[email protected]')]),
3385+
3386+
([r'Pete(A nice \) chap) <pete(his account)@silly.test(his host)>'],
3387+
[('Pete (A nice ) chap his account his host)', '[email protected]')]),
3388+
3389+
(['(Empty list)(start)Undisclosed recipients :(nobody(I know))'],
3390+
[('', '')]),
3391+
3392+
(['Mary <@machine.tld:[email protected]>, , jdoe@test . example'],
3393+
[('Mary', '[email protected]'), ('', ''), ('', '[email protected]')]),
3394+
3395+
(['John Doe <jdoe@machine(comment). example>'],
3396+
[('John Doe (comment)', '[email protected]')]),
3397+
3398+
(['"Mary Smith: Personal Account" <[email protected]>'],
3399+
[('Mary Smith: Personal Account', '[email protected]')]),
3400+
3401+
(['Undisclosed recipients:;'],
3402+
[('', '')]),
3403+
3404+
([r'<[email protected]>, "Giant; \"Big\" Box" <[email protected]>'],
3405+
[('', '[email protected]'), ('Giant; "Big" Box', '[email protected]')]),
3406+
):
3407+
with self.subTest(addresses=addresses):
3408+
self.assertEqual(utils.getaddresses(addresses),
3409+
expected)
3410+
self.assertEqual(utils.getaddresses(addresses, strict=False),
3411+
expected)
3412+
3413+
addresses = ['[]*-- =~$']
3414+
self.assertEqual(utils.getaddresses(addresses),
3415+
[('', '')])
3416+
self.assertEqual(utils.getaddresses(addresses, strict=False),
3417+
[('', ''), ('', ''), ('', '*--')])
33493418

33503419
def test_getaddresses_embedded_comment(self):
33513420
"""Test proper handling of a nested comment"""
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
:func:`email.utils.getaddresses` and :func:`email.utils.parseaddr` now
2+
return ``('', '')`` 2-tuples in more situations where invalid email
3+
addresses are encountered instead of potentially inaccurate values. Add
4+
optional *strict* parameter to these two functions: use ``strict=False`` to
5+
get the old behavior, accept malformed inputs. Patch by Thomas Dwyer to
6+
ameliorate CVE-2023-27043 fix.

0 commit comments

Comments
 (0)