Python twisted.internet.ssl.CertificateOptions() Examples

The following are 18 code examples of twisted.internet.ssl.CertificateOptions(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.ssl , or try the search function .
Example #1
Source File: only_noticed_pypi_pem_after_i_wrote_this.py    From txsni with MIT License 6 votes vote down vote up
def certificateOptionsFromPileOfPEM(pemdata):
    objects = objectsFromPEM(pemdata)
    if len(objects.keys) != 1:
        raise ValueError("Expected 1 private key, found %d"
                         % tuple([len(objects.keys)]))

    privateKey = objects.keys[0]

    certificatesByFingerprint = dict(
        [(certificate.getPublicKey().keyHash(), certificate)
         for certificate in objects.certificates]
    )

    if privateKey.keyHash() not in certificatesByFingerprint:
        raise ValueError("No certificate matching %s found")

    openSSLCert = certificatesByFingerprint.pop(privateKey.keyHash()).original
    openSSLKey = privateKey.original
    openSSLChain = [c.original for c in certificatesByFingerprint.values()]

    return CertificateOptions(certificate=openSSLCert, privateKey=openSSLKey,
                              extraCertChain=openSSLChain) 
Example #2
Source File: test_jabberxmlstream.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_certificateVerifyContext(self):
        """
        A custom contextFactory is passed through to startTLS.
        """
        ctx = CertificateOptions()
        self.init = xmlstream.TLSInitiatingInitializer(
            self.xmlstream, configurationForTLS=ctx)

        self.init.contextFactory = ctx

        def fakeStartTLS(contextFactory):
            self.assertIs(ctx, contextFactory)
            self.done.append('TLS')

        self.xmlstream.transport = proto_helpers.StringTransport()
        self.xmlstream.transport.startTLS = fakeStartTLS
        self.xmlstream.reset = lambda: self.done.append('reset')
        self.xmlstream.sendHeader = lambda: self.done.append('header')

        d = self.init.start()
        self.xmlstream.dataReceived("<proceed xmlns='%s'/>" % NS_XMPP_TLS)
        self.assertEqual(['TLS', 'reset', 'header'], self.done)
        return d 
Example #3
Source File: amp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def options(self, *authorities):
        """
        Behaves like L{twisted.internet.ssl.PrivateCertificate.options}().
        """
        if not self.client:
            # do some crud with sslverify to generate a temporary self-signed
            # certificate.  This is SLOOOWWWWW so it is only in the absolute
            # worst, most naive case.

            # We have to do this because OpenSSL will not let both the server
            # and client be anonymous.
            sharedDN = DN(CN='TEMPORARY CERTIFICATE')
            key = KeyPair.generate()
            cr = key.certificateRequest(sharedDN)
            sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1)
            cert = key.newCertificate(sscrd)
            return cert.options(*authorities)
        options = dict()
        if authorities:
            options.update(dict(verify=True,
                                requireCertificate=True,
                                caCerts=[auth.original for auth in authorities]))
        occo = CertificateOptions(**options)
        return occo 
Example #4
Source File: context_factory.py    From sygnal with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # Use CA root certs provided by OpenSSL
        trust_root = platformTrust()

        # "insecurelyLowerMinimumTo" is the argument that will go lower than
        # Twisted's default, which is why it is marked as "insecure" (since
        # Twisted's defaults are reasonably secure). But, since Twisted is
        # moving to TLS 1.2 by default, we want to respect the config option if
        # it is set to 1.0 (which the alternate option, raiseMinimumTo, will not
        # let us do).
        minTLS = TLSVersion.TLSv1_2

        self._verify_ssl = CertificateOptions(
            trustRoot=trust_root, insecurelyLowerMinimumTo=minTLS
        )
        self._verify_ssl_context = self._verify_ssl.getContext()
        self._verify_ssl_context.set_info_callback(self._context_info_cb) 
Example #5
Source File: tls_tcp_proxy.py    From how-to-build-a-tcp-proxy with The Unlicense 5 votes vote down vote up
def connectionMade(self):
        """
        Called by twisted when a client connects to the
        proxy.  Makes an TLS connection from the proxy to
        the server to complete the chain.
        """
        print("Connection made from CLIENT => PROXY")
        proxy_to_server_factory = protocol.ClientFactory()
        proxy_to_server_factory.protocol = ProxyToServerProtocol
        proxy_to_server_factory.server = self
 
        reactor.connectSSL(DST_IP, DST_PORT,
                           proxy_to_server_factory,
                           twisted_ssl.CertificateOptions()) 
Example #6
Source File: xmlstream.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def onProceed(self, obj):
        """
        Proceed with TLS negotiation and reset the XML stream.
        """

        self.xmlstream.removeObserver('/failure', self.onFailure)
        ctx = ssl.CertificateOptions()
        self.xmlstream.transport.startTLS(ctx)
        self.xmlstream.reset()
        self.xmlstream.sendHeader()
        self._deferred.callback(Reset) 
Example #7
Source File: snimap.py    From txsni with MIT License 5 votes vote down vote up
def __init__(self, mapping):
        self.mapping = mapping
        self._negotiationDataForContext = collections.defaultdict(
            _NegotiationData
        )
        try:
            self.context = self.mapping['DEFAULT'].getContext()
        except KeyError:
            self.context = CertificateOptions().getContext()
        self.context.set_tlsext_servername_callback(
            self.selectContext
        ) 
Example #8
Source File: application.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def _ssl_options(sslkey, sslcert):
    with open(sslkey) as keyfile:
        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, keyfile.read())
    with open(sslcert) as certfile:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, certfile.read())

    acceptable = ssl.AcceptableCiphers.fromOpenSSLCipherString(
        u'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:!RC4:HIGH:!MD5:!aNULL:!EDH')
    options = ssl.CertificateOptions(privateKey=pkey,
                                     certificate=cert,
                                     method=SSL.TLSv1_2_METHOD,
                                     acceptableCiphers=acceptable)
    return options 
Example #9
Source File: test_ssl.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectClient(self, address, portNumber, clientCreator):
        """
        Create an SSL client using L{IReactorSSL.connectSSL}.
        """
        contextFactory = ssl.CertificateOptions()
        return clientCreator.connectSSL(address, portNumber, contextFactory) 
Example #10
Source File: xmlstream.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def onProceed(self, obj):
        """
        Proceed with TLS negotiation and reset the XML stream.
        """

        self.xmlstream.removeObserver('/failure', self.onFailure)
        ctx = ssl.CertificateOptions()
        self.xmlstream.transport.startTLS(ctx)
        self.xmlstream.reset()
        self.xmlstream.sendHeader()
        self._deferred.callback(Reset) 
Example #11
Source File: federation_tls_options.py    From sydent with Apache License 2.0 5 votes vote down vote up
def __init__(self, config):
        verify_requests = config.getboolean("http", "federation.verifycerts")
        if verify_requests:
            self._options = ssl.CertificateOptions(trustRoot=ssl.platformTrust())
        else:
            self._options = ssl.CertificateOptions() 
Example #12
Source File: test_ssl.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def connectClient(self, address, portNumber, clientCreator):
        """
        Create an SSL client using L{IReactorSSL.connectSSL}.
        """
        contextFactory = ssl.CertificateOptions()
        return clientCreator.connectSSL(address, portNumber, contextFactory) 
Example #13
Source File: endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _parseClientSSLOptions(kwargs):
    """
    Parse common arguments for SSL endpoints, creating an L{CertificateOptions}
    instance.

    @param kwargs: A dict of keyword arguments to be parsed, potentially
        containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and
        C{hostname}.  See L{_parseClientSSL}.
    @type kwargs: L{dict}

    @return: The remaining arguments, including a new key C{sslContextFactory}.
    """
    hostname = kwargs.pop('hostname', None)
    clientCertificate = _privateCertFromPaths(kwargs.pop('certKey', None),
                                              kwargs.pop('privateKey', None))
    trustRoot = _parseTrustRootPath(kwargs.pop('caCertsDir', None))
    if hostname is not None:
        configuration = optionsForClientTLS(
            _idnaText(hostname), trustRoot=trustRoot,
            clientCertificate=clientCertificate
        )
    else:
        # _really_ though, you should specify a hostname.
        if clientCertificate is not None:
            privateKeyOpenSSL = clientCertificate.privateKey.original
            certificateOpenSSL = clientCertificate.original
        else:
            privateKeyOpenSSL = None
            certificateOpenSSL = None
        configuration = CertificateOptions(
            trustRoot=trustRoot,
            privateKey=privateKeyOpenSSL,
            certificate=certificateOpenSSL,
        )
    kwargs['sslContextFactory'] = configuration
    return kwargs 
Example #14
Source File: test_jabberclient.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_tlsConfiguration(self):
        """
        A TLS configuration is passed to the TLS initializer.
        """
        configs = []

        def init(self, xs, required=True, configurationForTLS=None):
            configs.append(configurationForTLS)

        self.client_jid = jid.JID('user@example.com/resource')

        # Get an XmlStream instance. Note that it gets initialized with the
        # XMPPAuthenticator (that has its associateWithXmlStream called) that
        # is in turn initialized with the arguments to the factory.
        configurationForTLS = ssl.CertificateOptions()
        factory = client.XMPPClientFactory(
            self.client_jid, 'secret',
            configurationForTLS=configurationForTLS)
        self.patch(xmlstream.TLSInitiatingInitializer, "__init__", init)
        xs = factory.buildProtocol(None)

        # test list of initializers
        version, tls, sasl, bind, session = xs.initializers

        self.assertIsInstance(tls, xmlstream.TLSInitiatingInitializer)
        self.assertIs(configurationForTLS, configs[0]) 
Example #15
Source File: _tls.py    From txacme with MIT License 5 votes vote down vote up
def start_responding(self, server_name, challenge, response):
        """
        Put a context into the mapping.
        """
        server_name = response.z_domain.decode('ascii')
        cert, pkey = generate_tls_sni_01_cert(
            server_name, _generate_private_key=self._generate_private_key)
        server_name = server_name.encode('utf-8')
        self._challenge_options[server_name] = CertificateOptions(
            certificate=crypto.X509.from_cryptography(cert),
            privateKey=crypto.PKey.from_cryptography_key(pkey)) 
Example #16
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def connectClient(self, address, portNumber, clientCreator):
        """
        Create an SSL client using L{IReactorSSL.connectSSL}.
        """
        contextFactory = ssl.CertificateOptions()
        return clientCreator.connectSSL(address, portNumber, contextFactory) 
Example #17
Source File: endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _parseClientSSLOptions(kwargs):
    """
    Parse common arguments for SSL endpoints, creating an L{CertificateOptions}
    instance.

    @param kwargs: A dict of keyword arguments to be parsed, potentially
        containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and
        C{hostname}.  See L{_parseClientSSL}.
    @type kwargs: L{dict}

    @return: The remaining arguments, including a new key C{sslContextFactory}.
    """
    hostname = kwargs.pop('hostname', None)
    clientCertificate = _privateCertFromPaths(kwargs.pop('certKey', None),
                                              kwargs.pop('privateKey', None))
    trustRoot = _parseTrustRootPath(kwargs.pop('caCertsDir', None))
    if hostname is not None:
        configuration = optionsForClientTLS(
            _idnaText(hostname), trustRoot=trustRoot,
            clientCertificate=clientCertificate
        )
    else:
        # _really_ though, you should specify a hostname.
        if clientCertificate is not None:
            privateKeyOpenSSL = clientCertificate.privateKey.original
            certificateOpenSSL = clientCertificate.original
        else:
            privateKeyOpenSSL = None
            certificateOpenSSL = None
        configuration = CertificateOptions(
            trustRoot=trustRoot,
            privateKey=privateKeyOpenSSL,
            certificate=certificateOpenSSL,
        )
    kwargs['sslContextFactory'] = configuration
    return kwargs 
Example #18
Source File: endpoints.py    From python-for-android with Apache License 2.0 4 votes vote down vote up
def _parseClientSSL(**kwargs):
    """
    Perform any argument value coercion necessary for SSL client parameters.

    Valid keyword arguments to this function are all L{IReactorSSL.connectSSL}
    arguments except for C{contextFactory}.  Instead, C{certKey} (the path name
    of the certificate file) C{privateKey} (the path name of the private key
    associated with the certificate) are accepted and used to construct a
    context factory.
    
    @param caCertsDir: The one parameter which is not part of
        L{IReactorSSL.connectSSL}'s signature, this is a path name used to
        construct a list of certificate authority certificates.  The directory
        will be scanned for files ending in C{.pem}, all of which will be
        considered valid certificate authorities for this connection.

    @type caCertsDir: C{str}

    @return: The coerced values as a C{dict}.
    """
    from twisted.internet import ssl
    kwargs = _parseClientTCP(**kwargs)
    certKey = kwargs.pop('certKey', None)
    privateKey = kwargs.pop('privateKey', None)
    caCertsDir = kwargs.pop('caCertsDir', None)
    if certKey is not None:
        certx509 = ssl.Certificate.loadPEM(
            FilePath(certKey).getContent()).original
    else:
        certx509 = None
    if privateKey is not None:
        privateKey = ssl.PrivateCertificate.loadPEM(
            FilePath(privateKey).getContent()).privateKey.original
    else:
        privateKey = None
    if caCertsDir is not None:
        verify = True
        caCerts = _loadCAsFromDir(FilePath(caCertsDir))
    else:
        verify = False
        caCerts = None
    kwargs['sslContextFactory'] = ssl.CertificateOptions(
        method=ssl.SSL.SSLv23_METHOD,
        certificate=certx509,
        privateKey=privateKey,
        verify=verify,
        caCerts=caCerts
    )
    return kwargs