]> khamidou — GitHub mirrors - imapclient.git/commitdiff
Use backports.ssl for all TLS/SSL connections
authorMenno Smits <menno@freshfoo.com>
Tue, 14 Jul 2015 06:05:43 +0000 (18:05 +1200)
committerMenno Smits <menno@freshfoo.com>
Tue, 14 Jul 2015 06:05:43 +0000 (18:05 +1200)
All unit tests and live tests passing.

NEWS.rst
imapclient/config.py
imapclient/imapclient.py
imapclient/test/test_init.py
imapclient/tls.py

index 4361bd51e0d2a4d6d8247fcfe1df339beebe42a1..534d579696391b13a1a6746034ce110fe422bcf1 100644 (file)
--- a/NEWS.rst
+++ b/NEWS.rst
@@ -1,3 +1,9 @@
+=======
+ 1.0.0
+=======
+
+XXX Removed kwargs support from constructor - replaced by ssl_context
+
 ======
  0.13
 ======
index 2281d1f6315d163d3dc1167fe8b98a7a5dd0a8a3..362873d3cff302019e1db94ccc91dc8946a58344 100644 (file)
@@ -9,9 +9,12 @@ try:
 except ImportError:
     from configparser import SafeConfigParser, NoOptionError
 
+from backports import ssl
+
 import imapclient
 from .six.moves.urllib.request import urlopen
 from .six.moves.urllib.parse import urlencode
+from .tls import create_default_context
 
 try:
     import json
@@ -93,8 +96,17 @@ def get_oauth2_token(client_id, client_secret, refresh_token):
     return token
 
 def create_client_from_config(conf):
+    # FIXME: temporary until the config files are expanded to support TLS options.
+    ssl_context = None
+    if conf.ssl:
+       ssl_context = create_default_context()
+       ssl_context.check_hostname = False
+       ssl_context.verify_mode = ssl.CERT_NONE
+
     client = imapclient.IMAPClient(conf.host, port=conf.port,
-                                   ssl=conf.ssl, stream=conf.stream)
+                                   ssl=conf.ssl,
+                                   ssl_context=ssl_context,
+                                   stream=conf.stream)
 
     if conf.starttls:
         client.starttls()
index 8c54521a7d8d8210f85564c6d85c5ae0f72f1c56..74e6c6feb2bc112bad0f51c16b95a8d59201bc79 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2014, Menno Smits
+# Copyright (c) 2015, Menno Smits
 # Released subject to the New BSD License
 # Please see http://en.wikipedia.org/wiki/BSD_licenses
 
@@ -84,25 +84,16 @@ class IMAPClient(object):
     If *ssl* is ``True`` an SSL connection will be made (defaults to
     ``False``).
 
+    If *ssl* is ``True`` the optional *ssl_context* argument can be
+    used to provide a ``backports.ssl.SSLContext`` instance used to
+    control SSL/TLS connection parameters. If this is not provided a
+    sensible default context will be used.
+
     If *stream* is ``True`` then *host* is used as the command to run
     to establish a connection to the IMAP server (defaults to
     ``False``). This is useful for exotic connection or authentication
     setups.
 
-    Additional keyword arguments are passed through to the constructor
-    of the :py:class:`imaplib.IMAP4` class, or
-    :py:class:`imaplib.IMAP4_SSL` when *ssl* is ``True`` (these are
-    used by ``IMAPClient`` internally). This allows passing SSL
-    related parameters such as *keyfile*, *certfile* and *ssl_context*
-    (Python version dependent). For details, see the :py:mod:`imaplib`
-    documentation in the standard library reference.
-
-    .. note::
-
-       Support for passthrough keyword arguments may be removed in
-       some future version of IMAPClient. Backwards compatibility is
-       not guaranteed for this feature.
-
     The *normalise_times* attribute specifies whether datetimes
     returned by ``fetch()`` are normalised to the local system time
     and include no timezone information (native), or are datetimes
@@ -128,7 +119,7 @@ class IMAPClient(object):
     ReadOnlyError = imaplib.IMAP4.readonly
 
     def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False,
-                 **kwargs):
+                 ssl_context=None):
         if stream:
             if port is not None:
                 raise ValueError("can't set 'port' when 'stream' True")
@@ -140,6 +131,7 @@ class IMAPClient(object):
         self.host = host
         self.port = port
         self.ssl = ssl
+        self.ssl_context = ssl_context
         self.stream = stream
         self.use_uid = use_uid
         self.folder_encode = True
@@ -148,16 +140,18 @@ class IMAPClient(object):
 
         self._starttls_done = False
         self._cached_capabilities = None
-        self._imap = self._create_IMAP4(**kwargs)
+        self._imap = self._create_IMAP4()
         self._imap._mesg = self._log    # patch in custom debug log method
         self._idle_tag = None
 
-    def _create_IMAP4(self, **kwargs):
-        # Create the IMAP instance in a separate method to make unit tests easier
+    def _create_IMAP4(self):
         if self.stream:
             return imaplib.IMAP4_stream(self.host)
-        ImapClass = self.ssl and imaplib.IMAP4_SSL or imaplib.IMAP4
-        return ImapClass(self.host, self.port, **kwargs)
+
+        if self.ssl:
+            return tls.IMAP4_TLS(self.host, self.port, self.ssl_context)
+
+        return imaplib.IMAP4(self.host, self.port)
 
     def starttls(self, ssl_context=None):
         """Switch to an SSL encrypted connection by sending a STARTTLS command.
index 695fb96f0a2464a7fced5bd22622c03c89975e1b..fb0d07d43fc762cad58501e239976dba63e76f94 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2014, Menno Smits
+# Copyright (c) 2015, Menno Smits
 # Released subject to the New BSD License
 # Please see http://en.wikipedia.org/wiki/BSD_licenses
 
@@ -7,14 +7,17 @@ from mock import patch, sentinel
 from imapclient.imapclient import IMAPClient
 from imapclient.test.util import unittest
 
+
 class TestInit(unittest.TestCase):
 
     def setUp(self):
-        self.patcher = patch('imapclient.imapclient.imaplib')
-        self.imaplib = self.patcher.start()
+        patcher = patch('imapclient.imapclient.imaplib')
+        self.imaplib = patcher.start()
+        self.addCleanup(patcher.stop)
 
-    def tearDown(self):
-        self.patcher.stop()
+        patcher = patch('imapclient.imapclient.tls')
+        self.tls = patcher.start()
+        self.addCleanup(patcher.stop)
 
     def test_plain(self):
         self.imaplib.IMAP4.return_value = sentinel.IMAP4
@@ -26,39 +29,22 @@ class TestInit(unittest.TestCase):
         self.assertEqual(imap.host, '1.2.3.4')
         self.assertEqual(imap.port, 143)
         self.assertEqual(imap.ssl, False)
+        self.assertEqual(imap.ssl_context, None)
         self.assertEqual(imap.stream, False)
 
     def test_SSL(self):
-        self.imaplib.IMAP4_SSL.return_value = sentinel.IMAP4_SSL
+        self.tls.IMAP4_TLS.return_value = sentinel.IMAP4_TLS
 
-        imap = IMAPClient('1.2.3.4', ssl=True)
+        imap = IMAPClient('1.2.3.4', ssl=True, ssl_context=sentinel.context)
 
-        self.assertEqual(imap._imap, sentinel.IMAP4_SSL)
-        self.imaplib.IMAP4_SSL.assert_called_with('1.2.3.4', 993)
+        self.assertEqual(imap._imap, sentinel.IMAP4_TLS)
+        self.tls.IMAP4_TLS.assert_called_with('1.2.3.4', 993, sentinel.context)
         self.assertEqual(imap.host, '1.2.3.4')
         self.assertEqual(imap.port, 993)
         self.assertEqual(imap.ssl, True)
+        self.assertEqual(imap.ssl_context, sentinel.context)
         self.assertEqual(imap.stream, False)
 
-    def test_SSL_kwargs(self):
-        self.imaplib.IMAP4_SSL.return_value = sentinel.IMAP4_SSL
-
-        imap = IMAPClient('1.2.3.4', ssl=True, keyfile='key.pem',
-                          certfile='cert.pem')
-
-        self.assertEqual(imap._imap, sentinel.IMAP4_SSL)
-        self.imaplib.IMAP4_SSL.assert_called_with('1.2.3.4', 993,
-            keyfile='key.pem', certfile='cert.pem')
-        self.assertEqual(imap.ssl, True)
-        self.assertEqual(imap.stream, False)
-
-        imap = IMAPClient('1.2.3.4', ssl=True, ssl_context=sentinel.context)
-        self.imaplib.IMAP4_SSL.assert_called_with('1.2.3.4', 993,
-            ssl_context=sentinel.context)
-        self.assertEqual(imap.ssl, True)
-        self.assertEqual(imap.stream, False)
-
-
     def test_stream(self):
         self.imaplib.IMAP4_stream.return_value = sentinel.IMAP4_stream
 
index be0e72b49ab97c79540f15e3a23c37341862c798..ca98d7955c31b3ea4dddafcc94be6e4c51275da5 100644 (file)
@@ -1,18 +1,24 @@
-# -*- coding: utf-8 -*-
+# Copyright (c) 2015, Menno Smits
+# Released subject to the New BSD License
+# Please see http://en.wikipedia.org/wiki/BSD_licenses
 
 """
-Solid TLS support for Python 2.6+ and 3.3+ built on backports.ssl/pyOpenSSL.
+Good TLS support for IMAPClient built on backports.ssl/pyOpenSSL.
+
+Works with Python 2.6+ and 3.3+.
 """
 
 __all__ = ('create_default_context', 'wrap_socket')
 
 
-import sys
 import imaplib
+import socket
+import sys
 
 from backports import ssl
 _ossl = ssl.ossl
 
+
 if sys.platform == "win32":
     try:
         from ssl import enum_certificates, Purpose
@@ -35,7 +41,8 @@ def create_default_context(cafile=None, capath=None, cadata=None):
 
     context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
 
-    # do certificate hostname checks.
+    # require certificate that matches the host name.
+    context.verify_mode = ssl.CERT_REQUIRED
     context.check_hostname = True
 
     # SSLv2 considered harmful.
@@ -96,8 +103,41 @@ def wrap_socket(sock, ssl_context, hostname):
         ssl_context = create_default_context()
 
     try:
-        return ssl_context.wrap_socket(sock, server_hostname=hostname)
+        newsock = ssl_context.wrap_socket(sock, server_hostname=hostname)
     except ssl.CertificateError:
         sock.shutdown()
         sock.close()
         raise imaplib.Error("server certificate not valid for %s" % hostname)
+
+    return _SSLSocketWithShutdown(newsock)
+
+
+class IMAP4_TLS(imaplib.IMAP4):
+    """IMAP4 client class for TLS/SSL connections.
+
+    Adapted from imaplib.IMAP4_SSL.
+    """
+
+    def __init__(self, host, port, ssl_context):
+        self.ssl_context = ssl_context
+        imaplib.IMAP4.__init__(self, host, port)
+
+    def open(self, host, port):
+        self.host = host
+        self.port = port
+        sock = socket.create_connection((host, port))
+        self.sock = wrap_socket(sock, self.ssl_context, host)
+        self.file = self.sock.makefile('rb')
+
+
+# TODO: get shutdown added in backports.ssl.SSLSocket
+class _SSLSocketWithShutdown(object):
+
+    def __init__(self, sslsock):
+        self.sslsock = sslsock
+
+    def shutdown(self, _):
+        return self.sslsock._conn.shutdown()
+
+    def __getattr__(self, name):
+        return getattr(self.sslsock, name)