[Python-Dev] Simplify and unify SSL verification

Christian Heimes christian at python.org
Fri Nov 8 00:50:57 CET 2013


Am 08.11.2013 00:09, schrieb Barry Warsaw:
> I'm sure you're considering this, but I want to explicitly preserve the
> ability to register self-signed certificates.  It's often necessary in
> practice, but very useful for testing purposes.
> 
> ssl.SSLContext.load_cert_chain() is the way to do this, but will this be
> exposed in your proposed factory function?  If not, then I think it's
> critically important that whatever API is exposed in the client code not hide
> the SSLContext object, such that clients of the client code can load up those
> self-signed certificates after the context has been created.

If you want full control over the context then you can still create your
own context object. Nobody is going to stop you from that. The factory
function removes code duplication. Right now 6 modules have the same
code for PROTOCOL_SSLv23 with OP_NO_SSLv2.


Old code
--------

class HTTPSConnection:
    def __init__(self, hostname, port, key_file=None,
                 cert_file=None, context=None):
       if context is None:
            # Some reasonable defaults
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.options |= ssl.OP_NO_SSLv2
       if key_file or cert_file:
                context.load_cert_chain(cert_file, key_file)


New code
--------

def create_default_context(protocol=None):
    if protocol is None:
        context = SSLContext(PROTOCOL_SSLv23)
        context.options |= OP_NO_SSLv2
    else:
        context = SSLContext(protocol)
    return context


class HTTPSConnection:
    def __init__(self, hostname, port, context=None):
        if context is None:
            context = ssl.create_default_context()
        self.context = context


If you want full control
------------------------

barrys_special_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
barrys_special_context.load_cert_chain(cert_file, key_file)

con =  HTTPSConnection(host, port, barrys_special_context)


With my proposed new option for SSLContext() you also gain full control
over hostname matching and extra cert checks. Super Barry power! :)

Christian



More information about the Python-Dev mailing list