diff --git a/Lib/imaplib.py b/Lib/imaplib.py index d9ec48cbc21959..a366f43e821ba0 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -1408,8 +1408,11 @@ def _check_bye(self): def _command(self, name, *args): - if self.state not in Commands[name]: + literal = self.literal + if literal is not None: self.literal = None + + if self.state not in Commands[name]: raise self.error("command %s illegal in state %s, " "only allowed in states %s" % (name, self.state, @@ -1434,9 +1437,7 @@ def _command(self, name, *args): raise ValueError("NUL, CR and LF not allowed in commands") data = data + b' ' + arg - literal = self.literal if literal is not None: - self.literal = None if type(literal) is type(self._command): literator = literal else: diff --git a/Lib/test/test_imaplib.py b/Lib/test/test_imaplib.py index 906c78f07d9c33..0acd39bd89be3e 100644 --- a/Lib/test/test_imaplib.py +++ b/Lib/test/test_imaplib.py @@ -2326,6 +2326,28 @@ def test_control_characters(self): self.assertEqual(name.encode('ascii').decode('utf-7-imap'), f'a{c}b') + def test_control_characters_append_literal(self): + client, server = self._setup(SimpleIMAPHandler) + client.login('user', 'pass') + for bad_mailbox in (b'a\nb', b'a\rb', b'a\0b'): + with self.subTest(mailbox=bad_mailbox): + with self.assertRaises(ValueError): + client.append(bad_mailbox, None, None, b'message') + self.assertIsNone(client.literal) + typ, _ = client.select('INBOX') + self.assertEqual(typ, 'OK') + with self.subTest(case='flags'): + with self.assertRaises(ValueError): + client.append('INBOX', '(\\Flag\n)', None, b'message') + self.assertIsNone(client.literal) + typ, _ = client.select('INBOX') + self.assertEqual(typ, 'OK') + client.logout() + with self.subTest(case='illegal_state'): + with self.assertRaises(imaplib.IMAP4.error): + client.append('INBOX', None, None, b'message') + self.assertIsNone(client.literal) + def test_mutf7_mailbox_name(self): # Without UTF8=ACCEPT a non-ASCII mailbox name is sent as modified # UTF-7 (RFC 3501, 5.1.3). A name that is already modified UTF-7 (e.g. diff --git a/Misc/NEWS.d/next/Security/2026-11-15-01-20-00.gh-issue-162010.aBcDeF.rst b/Misc/NEWS.d/next/Security/2026-11-15-01-20-00.gh-issue-162010.aBcDeF.rst new file mode 100644 index 00000000000000..6e8e9605a7d739 --- /dev/null +++ b/Misc/NEWS.d/next/Security/2026-11-15-01-20-00.gh-issue-162010.aBcDeF.rst @@ -0,0 +1,3 @@ +Fix an issue in :mod:`imaplib` where a rejected :meth:`~imaplib.IMAP4.append` +command left its message literal pending, causing it to be sent with the +subsequent command.