From ccbe5db8754d15c358f13ea48256b927fe85410e Mon Sep 17 00:00:00 2001 From: Menno Smits Date: Tue, 7 Jul 2015 17:42:20 +1200 Subject: [PATCH] Rearrange STARTTLS support to be a little more sane The tls module is now just for TLS related helpers. All unit tests now (finally!) passing under all supported Python versions. --- imapclient/imapclient.py | 29 +++++++++++++++---- imapclient/tls.py | 60 +++++++++++++--------------------------- 2 files changed, 43 insertions(+), 46 deletions(-) diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index b45bc4d..be1b290 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -20,7 +20,7 @@ except ImportError: oauth_module = None from . import response_lexer -from .tls import IMAP4 +from . import tls from .imap_utf7 import encode as encode_utf7, decode as decode_utf7 from .fixed_offset import FixedOffset from .response_types import SearchIds @@ -43,6 +43,10 @@ if 'XLIST' not in imaplib.Commands: if 'IDLE' not in imaplib.Commands: imaplib.Commands['IDLE'] = imaplib.Commands['APPEND'] +# ..and STARTTLS +if 'STARTTLS' not in imaplib.Commands: + imaplib.Commands['STARTTLS'] = ('NONAUTH',) + # System flags DELETED = r'\Deleted' @@ -135,6 +139,7 @@ class IMAPClient(object): self.log_file = sys.stderr self.normalise_times = True + self._starttls_done = False self._cached_capabilities = None self._imap = self._create_IMAP4(**kwargs) self._imap._mesg = self._log # patch in custom debug log method @@ -144,7 +149,7 @@ class IMAPClient(object): # Create the IMAP instance in a separate method to make unit tests easier if self.stream: return imaplib.IMAP4_stream(self.host) - ImapClass = self.ssl and imaplib.IMAP4_SSL or IMAP4 + ImapClass = self.ssl and imaplib.IMAP4_SSL or imaplib.IMAP4 return ImapClass(self.host, self.port, **kwargs) def starttls(self, ssl_context=None): @@ -163,15 +168,29 @@ class IMAPClient(object): Raises :py:exc:`AbortError` if the server does not support STARTTLS or an SSL connection is already established. - """ - return self._imap.starttls(ssl_context) + if self.ssl or self._starttls_done: + raise self.abort('TLS session already established') + + typ, dat = self._imap._simple_command("STARTTLS") + if typ != 'OK': + raise self.Error("Couldn't establish TLS session") + + self._tls_established = True + self._imap.sock = tls.wrap_socket(self._imap.sock, self.host, ssl_context) + self._imap.file = self._imap.sock.makefile() + return self._imap._untagged_response(typ, dat, "STARTTLS") def login(self, username, password): """Login using *username* and *password*, returning the server response. """ - return self._command_and_check('login', username, password, unpack=True) + return self._command_and_check( + 'login', + to_bytes(username), + to_bytes(password), + unpack=True, + ) def oauth_login(self, url, oauth_token, oauth_token_secret, consumer_key='anonymous', consumer_secret='anonymous'): diff --git a/imapclient/tls.py b/imapclient/tls.py index 895ad20..e75b454 100644 --- a/imapclient/tls.py +++ b/imapclient/tls.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """STARTTLS support for imaplib for Python 2.6+ and 3.3+ built on pyOpenSSL.""" -__all__ = ('IMAP4', 'get_default_context') +__all__ = ('get_default_context', 'wrap_socket') import sys import imaplib @@ -17,17 +17,13 @@ if sys.platform == "win32": except ImportError: enum_certificates = lambda x: [] + # third-party dependencies from six import b, binary_type from OpenSSL import SSL from service_identity import VerificationError from service_identity.pyopenssl import verify_hostname - -# add STARTTLS command support in imaplib if necessary -if 'STARTTLS' not in imaplib.Commands: - imaplib.Commands['STARTTLS'] = ('NONAUTH',) - # taken from Python 3.4 ssl module _RESTRICTED_SERVER_CIPHERS = ( 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' @@ -95,44 +91,25 @@ def get_default_context(cafile=None, capath=None, check_hostname=True): return context -class IMAP4(imaplib.IMAP4): - - def starttls(self, ssl_context=None): - """Send a STARTTLS command and wrap the socket with TLS.""" - name = 'STARTTLS' - - if (isinstance(self, imaplib.IMAP4_SSL) or - getattr(self, '_tls_established', False)): - raise self.abort('TLS session already established') - - if name not in self.capabilities: - raise self.abort('STARTTLS not supported by server') - - if not ssl_context: - ssl_context = get_default_context() - - type_, dat = self._simple_command(name) - - if type_ == 'OK': - self.sock = _SSLConnection(ssl_context, self.sock) - self.sock.set_connect_state() - self.sock.do_handshake() +def wrap_socket(sock, host, ssl_context): + """XXX + """ + if not ssl_context: + ssl_context = get_default_context() - if getattr(ssl_context, 'check_hostname', True): - try: - verify_hostname(self.sock, self.host) - except VerificationError: - self.sock.shutdown() - self.sock.close() - raise self.abort( - "Server certificate not valid for %s" % self.host) + sock = _SSLConnection(ssl_context, sock) + sock.set_connect_state() + sock.do_handshake() - self.file = self.sock.makefile() - self._tls_established = True - else: - raise self.Error("Couldn't establish TLS session") + if getattr(ssl_context, 'check_hostname', True): + try: + verify_hostname(sock, host) + except VerificationError: + sock.shutdown() + sock.close() + raise imaplib.Error("Server certificate not valid for %s" % host) - return self._untagged_response(type_, dat, name) + return sock class _SSLConnection(SSL.Connection): @@ -149,6 +126,7 @@ class _SSLConnection(SSL.Connection): # lifted from backports.ssl +# XXX do we really have to copy this here? class _socketfileobj(object): """Custom file-like object to support socket.makefile for pyOpenSSL.""" -- 2.43.0