fix(email): require the sender identity to re-parse as exactly one mailbox

Check the final address on both parse paths, not only the bracketed fallback:
an unterminated quote made parseaddr return 'victim@x, attacker@evil' verbatim
(reply RCPT TO both, authenticated by the attacker's domain), and
'victim"@evil' re-parsed as the bare recipient 'victim'. Authentication now
folds domains A-Z only, like the identity, so U+212A cannot pass as 'k'.

Fixes #136770
This commit is contained in:
Maciej Lisiewski
2026-11-14 03:40:59 +01:00
parent 3bc7c82169
commit 4731510ada
2 changed files with 60 additions and 8 deletions

View File

@@ -18,7 +18,7 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.parser import BytesHeaderParser
from email.utils import formatdate, parseaddr
from email.utils import formatdate, getaddresses, parseaddr
from email import encoders
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
@@ -297,7 +297,8 @@ def _extract_email_address(raw: str) -> str:
``Name <addr>`` values parseaddr rejects (``Doe, John <j@x>``) fall back to their single bracketed addr-spec,
but only when the display part (``(comments)`` removed) cannot hold another mailbox or group: no quotes, ``;``,
``:`` or stray parens, and no ``@`` unless it is exactly the bracketed address (``a@x <a@x>``). Values over
``_MAX_FROM_LEN`` (or with more than 64 ``(``) and results without ``@`` return ``""`` so the caller drops the message."""
``_MAX_FROM_LEN`` (or with more than 64 ``(``) and results that are not exactly one round-tripping ``local@domain``
mailbox return ``""`` so the caller drops the message."""
value = re.sub(r"\r?\n[ \t]+", " ", str(raw or ""))
if len(value) > _MAX_FROM_LEN or value.count("(") > 64:
return "" # hostile size/nesting: take the empty-sender drop (parseaddr recurses per nested comment)
@@ -308,7 +309,12 @@ def _extract_email_address(raw: str) -> str:
and ("@" not in display or display.lower() == bracketed.lower())):
addr = bracketed
addr = addr.strip().translate(_ASCII_LOWER)
return addr if "@" in addr else "" # a bare word (``John``) is not a sender identity
# Both paths: the identity is the reply To:, so it must re-parse as exactly this one mailbox. An unterminated
# quote makes parseaddr return ``a@x, b@evil`` verbatim, and ``victim"@evil`` re-parses as RCPT TO ``victim``.
local, at, domain = addr.partition("@")
if not (local and at and domain and "@" not in domain and getaddresses([addr]) == [("", addr)]):
return "" # also drops a bare word (``John``), which is not a sender identity
return addr
def _strip_comments(text: str) -> str:
@@ -360,13 +366,13 @@ def _auth_props(text: str) -> list[tuple[str, str]]:
def _domain_of(address: str) -> str:
"""Lowercased domain part of an email address, or ''."""
return address.rpartition("@")[2].strip().lower()
return address.rpartition("@")[2].strip().translate(_ASCII_LOWER) # A-Z only, like the identity (U+212A stays)
def _domains_aligned(a: str, b: str) -> bool:
"""Relaxed DMARC alignment: equal, or one is a dot-suffix of the other."""
a = (a or "").strip().lower().rstrip(".")
b = (b or "").strip().lower().rstrip(".")
a = (a or "").strip().translate(_ASCII_LOWER).rstrip(".")
b = (b or "").strip().translate(_ASCII_LOWER).rstrip(".")
return bool(a and b) and (a == b or a.endswith("." + b) or b.endswith("." + a))

View File

@@ -4,12 +4,14 @@ The identity parsed from From: becomes the session's chat_id, the allowlist key
authentication only proves the domain.
"""
import email
import os
import unittest
from unittest.mock import patch
from email.utils import getaddresses
from unittest.mock import MagicMock, patch
from gateway.config import PlatformConfig
from plugins.platforms.email.adapter import EmailAdapter, _extract_email_address
from plugins.platforms.email.adapter import EmailAdapter, _extract_email_address, _verify_sender_authentication
class TestSenderIdentityParsing(unittest.TestCase):
@@ -40,5 +42,49 @@ class TestSenderIdentityParsing(unittest.TestCase):
self.assertTrue(adapter._sender_accepted(sender, authenticated))
_OPEN_ACCESS_ENV = {"EMAIL_ADDRESS": "hermes@bot.test", "EMAIL_PASSWORD": "pw", "EMAIL_IMAP_HOST": "imap.bot.test",
"EMAIL_SMTP_HOST": "smtp.bot.test", "EMAIL_AUTHSERV_ID": "mx.bot.test",
"EMAIL_ALLOW_ALL_USERS": "true", "EMAIL_ALLOWED_USERS": "", "GATEWAY_ALLOWED_USERS": ""}
class TestSenderIdentityEndToEnd(unittest.TestCase):
"""parse -> authentication -> sender gate -> reply recipients, with the attacker's own domain passing DMARC."""
def _reply_recipients(self, from_value: str, auth_domain: str):
"""SMTP recipients of the reply to a From: the adapter accepted, or None when it refuses the message."""
with patch.dict(os.environ, _OPEN_ACCESS_ENV, clear=False):
adapter = EmailAdapter(PlatformConfig(enabled=True))
raw = (f"From: {from_value}\r\nAuthentication-Results: mx.bot.test; dmarc=pass header.from={auth_domain}\r\n"
"Subject: hi\r\nMessage-ID: <m1@evil.com>\r\n\r\nbody").encode()
msg_data = adapter._parse_fetched_message(b"1", raw)
if msg_data is None or not adapter._sender_accepted(msg_data["sender_addr"], msg_data):
return None
smtp = MagicMock()
with patch.object(adapter, "_connect_smtp", return_value=smtp):
adapter._send_email(msg_data["sender_addr"], "reply")
sent = smtp.send_message.call_args[0][0]
return [a for _, a in getaddresses(sent.get_all("To", []))]
def test_unterminated_quote_cannot_make_a_two_recipient_identity(self):
# parseaddr hands the unterminated quoted text back verbatim as the "address".
for from_value in ('"victim@x.test, attacker@evil.com', 'x:"victim@x.test, attacker@evil.com'):
self.assertIsNone(self._reply_recipients(from_value, "evil.com"), from_value)
def test_stray_quote_in_bracketed_address_cannot_become_a_bare_local_part(self):
# ``victim"@evil.com`` re-parses as the domain-less recipient ``victim``.
self.assertIsNone(self._reply_recipients('Doe, J <victim"@evil.com>', "evil.com"))
def test_non_ascii_domain_does_not_authenticate_as_its_ascii_fold(self):
# U+212A KELVIN SIGN: the identity keeps it, so authentication must not fold it to ``kx.com`` either.
msg = email.message_from_string("From: Doe <a@\u212ax.com>\r\n"
"Authentication-Results: mx.bot.test; dmarc=pass header.from=kx.com\r\n\r\nb")
sender = _extract_email_address(msg["From"])
self.assertEqual(sender, "a@\u212ax.com")
self.assertFalse(_verify_sender_authentication(msg, sender, authserv_id="mx.bot.test")[0])
def test_ordinary_sender_still_gets_one_reply_to_itself(self):
self.assertEqual(self._reply_recipients("Doe, John <John@Evil.com>", "evil.com"), ["john@evil.com"])
if __name__ == "__main__":
unittest.main()