Skip to content

gh-119511: Fix OOM vulnerability in imaplib #119514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
11 changes: 10 additions & 1 deletion Lib/imaplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
# search command can be quite large, so we now use 1M.
_MAXLINE = 1000000

# Data larger than this will be read in chunks, to prevent extreme
# overallocation.
_SAFE_BUF_SIZE = 1 << 20

# Commands

Expand Down Expand Up @@ -315,7 +318,13 @@ def open(self, host='', port=IMAP4_PORT, timeout=None):

def read(self, size):
"""Read 'size' bytes from remote."""
return self.file.read(size)
cursize = min(size, _SAFE_BUF_SIZE)
data = self.file.read(cursize)
while cursize < size and len(data) == cursize:
delta = min(cursize, size - cursize)
data += self.file.read(delta)
cursize += delta
return data


def readline(self):
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_imaplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,20 @@ def handle(self):
self.assertRaises(imaplib.IMAP4.error,
self.imap_class, *server.server_address)

def test_truncated_large_literal(self):
size = 0
class BadHandler(SimpleIMAPHandler):
def handle(self):
self._send_textline('* OK {%d}' % size)
self._send_textline('IMAP4rev1')

for exponent in range(15, 64):
size = 1 << exponent
with self.subTest(f"size=2e{size}"):
with self.reaped_server(BadHandler) as server:
with self.assertRaises(imaplib.IMAP4.abort):
self.imap_class(*server.server_address)

@threading_helper.reap_threads
def test_simple_with_statement(self):
# simplest call
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Fix a potential denial of service in the :mod:`imaplib` module. When connecting
to a malicious server, it could cause an arbitrary amount of memory to be
allocated. On many systems this is harmless as unused virtual memory is only a
mapping, but if this hit a virtual address size limit it could lead to a
:exc:`MemoryError` or other process crash. On unusual systems or builds where
all allocated memory is touched and backed by actual ram or storage it could've
consumed resources doing so until similarly crashing.
Loading