f63228
f63228
# HG changeset patch
f63228
# User R David Murray <rdmurray@bitdance.com>
f63228
# Date 1388775562 18000
f63228
# Node ID dd906f4ab9237020a7a275c2d361fa288e553481
f63228
# Parent  69b5f692455306c98aa27ecea17e6290787ebd3f
f63228
closes 16039: CVE-2013-1752: limit line length in imaplib readline calls.
f63228
f63228
diff --git a/Lib/imaplib.py b/Lib/imaplib.py
f63228
--- a/Lib/imaplib.py
f63228
+++ b/Lib/imaplib.py
f63228
@@ -35,6 +35,15 @@ IMAP4_PORT = 143
f63228
 IMAP4_SSL_PORT = 993
f63228
 AllowedVersions = ('IMAP4REV1', 'IMAP4')        # Most recent first
f63228
 
f63228
+# Maximal line length when calling readline(). This is to prevent
f63228
+# reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
f63228
+# don't specify a line length. RFC 2683 however suggests limiting client
f63228
+# command lines to 1000 octets and server command lines to 8000 octets.
f63228
+# We have selected 10000 for some extra margin and since that is supposedly
f63228
+# also what UW and Panda IMAP does.
f63228
+_MAXLINE = 10000
f63228
+
f63228
+
f63228
 #       Commands
f63228
 
f63228
 Commands = {
f63228
@@ -237,7 +246,10 @@ class IMAP4:
f63228
 
f63228
     def readline(self):
f63228
         """Read line from remote."""
f63228
-        return self.file.readline()
f63228
+        line = self.file.readline(_MAXLINE + 1)
f63228
+        if len(line) > _MAXLINE:
f63228
+            raise self.error("got more than %d bytes" % _MAXLINE)
f63228
+        return line
f63228
 
f63228
 
f63228
     def send(self, data):
f63228
diff --git a/Lib/test/test_imaplib.py b/Lib/test/test_imaplib.py
f63228
--- a/Lib/test/test_imaplib.py
f63228
+++ b/Lib/test/test_imaplib.py
f63228
@@ -165,6 +165,16 @@ class BaseThreadedNetworkedTests(unittes
f63228
                               self.imap_class, *server.server_address)
f63228
 
f63228
 
f63228
+    def test_linetoolong(self):
f63228
+        class TooLongHandler(SimpleIMAPHandler):
f63228
+            def handle(self):
f63228
+                # Send a very long response line
f63228
+                self.wfile.write('* OK ' + imaplib._MAXLINE*'x' + '\r\n')
f63228
+
f63228
+        with self.reaped_server(TooLongHandler) as server:
f63228
+            self.assertRaises(imaplib.IMAP4.error,
f63228
+                              self.imap_class, *server.server_address)
f63228
+
f63228
 class ThreadedNetworkedTests(BaseThreadedNetworkedTests):
f63228
 
f63228
     server_class = SocketServer.TCPServer