Python OpenSSL.SSL.Context() Examples
The following are 30
code examples of OpenSSL.SSL.Context().
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
OpenSSL.SSL
, or try the search function
.
Example #1
Source File: httpserver.py From mishkal with GNU General Public License v3.0 | 8 votes |
def _auto_ssl_context(): import OpenSSL, time, random pkey = OpenSSL.crypto.PKey() pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 768) cert = OpenSSL.crypto.X509() cert.set_serial_number(random.randint(0, sys.maxint)) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * 365) cert.get_subject().CN = '*' cert.get_subject().O = 'Dummy Certificate' cert.get_issuer().CN = 'Untrusted Authority' cert.get_issuer().O = 'Self-Signed' cert.set_pubkey(pkey) cert.sign(pkey, 'md5') ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey(pkey) ctx.use_certificate(cert) return ctx
Example #2
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_doesNotSwallowOtherSSLErrors(self): """ Only no cipher matches get swallowed, every other SSL error gets propagated. """ def raiser(_): # Unfortunately, there seems to be no way to trigger a real SSL # error artificially. raise SSL.Error([['', '', '']]) ctx = FakeContext(SSL.SSLv23_METHOD) ctx.set_cipher_list = raiser self.patch(sslverify.SSL, 'Context', lambda _: ctx) self.assertRaises( SSL.Error, sslverify._expandCipherString, u'ALL', SSL.SSLv23_METHOD, 0 )
Example #3
Source File: ssl.py From Exchange2domain with MIT License | 6 votes |
def wrapClientConnection(self, cert='/tmp/impacket.crt'): # Create a context, we don't really care about the SSL/TLS # versions used since it is only intended for local use and thus # doesn't have to be super-secure ctx = SSL.Context(SSL.SSLv23_METHOD) try: ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) except SSL.Error: LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') generateImpacketCert(cert) ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) sslSocket = SSL.Connection(ctx, self.socksSocket) sslSocket.set_accept_state() # Now set this property back to the SSL socket instead of the regular one self.socksSocket = sslSocket
Example #4
Source File: handlers.py From oss-ftp with MIT License | 6 votes |
def get_ssl_context(cls): if cls.ssl_context is None: if cls.certfile is None: raise ValueError("at least certfile must be specified") cls.ssl_context = SSL.Context(cls.ssl_protocol) if cls.ssl_protocol != SSL.SSLv2_METHOD: cls.ssl_context.set_options(SSL.OP_NO_SSLv2) else: warnings.warn("SSLv2 protocol is insecure", RuntimeWarning) cls.ssl_context.use_certificate_chain_file(cls.certfile) if not cls.keyfile: cls.keyfile = cls.certfile cls.ssl_context.use_privatekey_file(cls.keyfile) return cls.ssl_context # --- overridden methods
Example #5
Source File: crashpoc.py From CVE-2019-0708 with GNU General Public License v3.0 | 6 votes |
def send_init_packets(host): tpkt = TPKT() tpdu = TPDU() rdp_neg = RDP_NEG_REQ() rdp_neg['Type'] = 1 rdp_neg['requestedProtocols'] = 1 tpdu['VariablePart'] = rdp_neg.getData() tpdu['Code'] = 0xe0 tpkt['TPDU'] = tpdu.getData() s = socket.socket() s.connect((host, 3389)) s.sendall(tpkt.getData()) s.recv(8192) ctx = SSL.Context(SSL.TLSv1_METHOD) tls = SSL.Connection(ctx,s) tls.set_connect_state() tls.do_handshake() return tls # This can be fixed length now buttfuckit
Example #6
Source File: ssl.py From Slackor with GNU General Public License v3.0 | 6 votes |
def wrapClientConnection(self, cert='/tmp/impacket.crt'): # Create a context, we don't really care about the SSL/TLS # versions used since it is only intended for local use and thus # doesn't have to be super-secure ctx = SSL.Context(SSL.SSLv23_METHOD) try: ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) except SSL.Error: LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') generateImpacketCert(cert) ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) sslSocket = SSL.Connection(ctx, self.socksSocket) sslSocket.set_accept_state() # Now set this property back to the SSL socket instead of the regular one self.socksSocket = sslSocket
Example #7
Source File: _sslverify.py From learn_python3_spider with MIT License | 6 votes |
def __init__(self, hostname, ctx): """ Initialize L{ClientTLSOptions}. @param hostname: The hostname to verify as input by a human. @type hostname: L{unicode} @param ctx: an L{OpenSSL.SSL.Context} to use for new connections. @type ctx: L{OpenSSL.SSL.Context}. """ self._ctx = ctx self._hostname = hostname if isIPAddress(hostname) or isIPv6Address(hostname): self._hostnameBytes = hostname.encode('ascii') self._hostnameIsDnsName = False else: self._hostnameBytes = _idnaBytes(hostname) self._hostnameIsDnsName = True self._hostnameASCII = self._hostnameBytes.decode("ascii") ctx.set_info_callback( _tolerateErrors(self._identityVerifyingInfoCallback) )
Example #8
Source File: handlers.py From oss-ftp with MIT License | 6 votes |
def get_ssl_context(cls): if cls.ssl_context is None: if cls.certfile is None: raise ValueError("at least certfile must be specified") cls.ssl_context = SSL.Context(cls.ssl_protocol) if cls.ssl_protocol != SSL.SSLv2_METHOD: cls.ssl_context.set_options(SSL.OP_NO_SSLv2) else: warnings.warn("SSLv2 protocol is insecure", RuntimeWarning) cls.ssl_context.use_certificate_chain_file(cls.certfile) if not cls.keyfile: cls.keyfile = cls.certfile cls.ssl_context.use_privatekey_file(cls.keyfile) return cls.ssl_context # --- overridden methods
Example #9
Source File: ssl.py From learn_python3_spider with MIT License | 6 votes |
def __init__(self, privateKeyFileName, certificateFileName, sslmethod=SSL.SSLv23_METHOD, _contextFactory=SSL.Context): """ @param privateKeyFileName: Name of a file containing a private key @param certificateFileName: Name of a file containing a certificate @param sslmethod: The SSL method to use """ self.privateKeyFileName = privateKeyFileName self.certificateFileName = certificateFileName self.sslmethod = sslmethod self._contextFactory = _contextFactory # Create a context object right now. This is to force validation of # the given parameters so that errors are detected earlier rather # than later. self.cacheContext()
Example #10
Source File: _sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _identityVerifyingInfoCallback(self, connection, where, ret): """ U{info_callback <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback> } for pyOpenSSL that verifies the hostname in the presented certificate matches the one passed to this L{ClientTLSOptions}. @param connection: the connection which is handshaking. @type connection: L{OpenSSL.SSL.Connection} @param where: flags indicating progress through a TLS handshake. @type where: L{int} @param ret: ignored @type ret: ignored """ if where & SSL.SSL_CB_HANDSHAKE_START: connection.set_tlsext_host_name(self._hostnameBytes) elif where & SSL.SSL_CB_HANDSHAKE_DONE: try: verifyHostname(connection, self._hostnameASCII) except VerificationError: f = Failure() transport = connection.get_app_data() transport.failVerification(f)
Example #11
Source File: ssl.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def __init__(self, privateKeyFileName, certificateFileName, sslmethod=SSL.SSLv23_METHOD, _contextFactory=SSL.Context): """ @param privateKeyFileName: Name of a file containing a private key @param certificateFileName: Name of a file containing a certificate @param sslmethod: The SSL method to use """ self.privateKeyFileName = privateKeyFileName self.certificateFileName = certificateFileName self.sslmethod = sslmethod self._contextFactory = _contextFactory # Create a context object right now. This is to force validation of # the given parameters so that errors are detected earlier rather # than later. self.cacheContext()
Example #12
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_extraChainFilesAreAddedIfSupplied(self): """ If C{extraCertChain} is set and all prerequisites are met, the specified chain certificates are added to C{Context}s that get created. """ opts = sslverify.OpenSSLCertificateOptions( privateKey=self.sKey, certificate=self.sCert, extraCertChain=self.extraCertChain, ) opts._contextFactory = FakeContext ctx = opts.getContext() self.assertEqual(self.sKey, ctx._privateKey) self.assertEqual(self.sCert, ctx._certificate) self.assertEqual(self.extraCertChain, ctx._extraCertChain)
Example #13
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_openSSL101SetECDHRaises(self): """ An exception raised by L{OpenSSL.SSL.Context.set_tmp_ecdh} under OpenSSL 1.0.1 is suppressed because ECHDE is best-effort. """ def set_tmp_ecdh(ctx): raise BaseException self.context.set_tmp_ecdh = set_tmp_ecdh chooser = sslverify._ChooseDiffieHellmanEllipticCurve( self.OPENSSL_101, openSSLlib=self.lib, openSSLcrypto=self.crypto, ) chooser.configureECDHCurve(self.context) self.assertFalse(self.libState.ecdhContexts) self.assertFalse(self.libState.ecdhValues) self.assertEqual( self.cryptoState.getEllipticCurveCalls, [sslverify._defaultCurveName], )
Example #14
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_openSSL102SetECDHAutoRaises(self): """ An exception raised by C{SSL_CTX_set_ecdh_auto} under OpenSSL 1.0.2 is suppressed because ECDH is best-effort. """ self.libState.setECDHAutoRaises = BaseException context = SSL.Context(SSL.SSLv23_METHOD) chooser = sslverify._ChooseDiffieHellmanEllipticCurve( self.OPENSSL_102, openSSLlib=self.lib, openSSLcrypto=self.crypto, ) chooser.configureECDHCurve(context) self.assertEqual(self.libState.ecdhContexts, [context._context]) self.assertEqual(self.libState.ecdhValues, [True]) self.assertFalse(self.cryptoState.getEllipticCurveCalls)
Example #15
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_doesNotSwallowOtherSSLErrors(self): """ Only no cipher matches get swallowed, every other SSL error gets propagated. """ def raiser(_): # Unfortunately, there seems to be no way to trigger a real SSL # error artificially. raise SSL.Error([['', '', '']]) ctx = FakeContext(SSL.SSLv23_METHOD) ctx.set_cipher_list = raiser self.patch(sslverify.SSL, 'Context', lambda _: ctx) self.assertRaises( SSL.Error, sslverify._expandCipherString, u'ALL', SSL.SSLv23_METHOD, 0 )
Example #16
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_openSSL102(self): """ OpenSSL 1.0.2 does not set ECDH curves by default, but C{SSL_CTX_set_ecdh_auto} requests that a context choose a secure set curves automatically. """ context = SSL.Context(SSL.SSLv23_METHOD) chooser = sslverify._ChooseDiffieHellmanEllipticCurve( self.OPENSSL_102, openSSLlib=self.lib, openSSLcrypto=self.crypto, ) chooser.configureECDHCurve(context) self.assertEqual(self.libState.ecdhContexts, [context._context]) self.assertEqual(self.libState.ecdhValues, [True]) self.assertFalse(self.cryptoState.getEllipticCurveCalls) self.assertIsNone(self.context._ecCurve)
Example #17
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def SSL_CTX_set_ecdh_auto(self, ctx, value): """ Record the context and value under in the C{_state} instance variable. @see: L{FakeLibState} @param ctx: An SSL context. @type ctx: L{OpenSSL.SSL.Context} @param value: A boolean value @type value: L{bool} """ self._state.ecdhContexts.append(ctx) self._state.ecdhValues.append(value) if self._state.setECDHAutoRaises is not None: raise self._state.setECDHAutoRaises
Example #18
Source File: _sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def __init__(self, hostname, ctx): """ Initialize L{ClientTLSOptions}. @param hostname: The hostname to verify as input by a human. @type hostname: L{unicode} @param ctx: an L{OpenSSL.SSL.Context} to use for new connections. @type ctx: L{OpenSSL.SSL.Context}. """ self._ctx = ctx self._hostname = hostname self._hostnameBytes = _idnaBytes(hostname) self._hostnameASCII = self._hostnameBytes.decode("ascii") ctx.set_info_callback( _tolerateErrors(self._identityVerifyingInfoCallback) )
Example #19
Source File: test_validation.py From flocker with Apache License 2.0 | 6 votes |
def start_tls_server(test, port, context_factory): """ Start a TLS server on the given port. :param test: The test this is being run in. :param int port: Port to listen on. :param context_factory: Context factory to use. :return: ``Deferred`` that fires when port is open to connections. """ server_endpoint = SSL4ServerEndpoint(reactor, port, context_factory, interface='127.0.0.1') server_factory = WaitForDisconnectsFactory.forProtocol(SendingProtocol) test.addCleanup(lambda: server_factory.wait_for_disconnects()) d = server_endpoint.listen(server_factory) d.addCallback(lambda port: test.addCleanup(port.stopListening)) return d
Example #20
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def loopbackTLSConnection(trustRoot, privateKeyFile, chainedCertFile=None): """ Create a loopback TLS connection with the given trust and keys. @param trustRoot: the C{trustRoot} argument for the client connection's context. @type trustRoot: L{sslverify.IOpenSSLTrustRoot} @param privateKeyFile: The name of the file containing the private key. @type privateKeyFile: L{str} (native string; file name) @param chainedCertFile: The name of the chained certificate file. @type chainedCertFile: L{str} (native string; file name) @return: 3-tuple of server-protocol, client-protocol, and L{IOPump} @rtype: L{tuple} """ class ContextFactory(object): def getContext(self): """ Create a context for the server side of the connection. @return: an SSL context using a certificate and key. @rtype: C{OpenSSL.SSL.Context} """ ctx = SSL.Context(SSL.TLSv1_METHOD) if chainedCertFile is not None: ctx.use_certificate_chain_file(chainedCertFile) ctx.use_privatekey_file(privateKeyFile) # Let the test author know if they screwed something up. ctx.check_privatekey() return ctx serverOpts = ContextFactory() clientOpts = sslverify.OpenSSLCertificateOptions(trustRoot=trustRoot) return _loopbackTLSConnection(serverOpts, clientOpts)
Example #21
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def set_mode(self, mode): """ Set the mode. See L{SSL.Context.set_mode}. @param mode: See L{SSL.Context.set_mode}. """ self._mode = mode
Example #22
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _configureOpenSSL101NoCurves(self, ctx): """ No elliptic curves are available on OpenSSL 1.0.1. We can't set anything, so do nothing. @param ctx: The context on which to set the ECDH curve. @type ctx: L{OpenSSL.SSL.Context} """
Example #23
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def set_tmp_ecdh(self, curve): """ Set an ECDH curve. Should only be called by OpenSSL 1.0.1 code. @param curve: See L{OpenSSL.SSL.Context.set_tmp_ecdh} """ self._ecCurve = curve
Example #24
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def configureECDHCurve(self, ctx): """ A null configuration. @param ctx: An L{OpenSSL.SSL.Context} that would be configured. """
Example #25
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def getContext(self): """ Return an L{OpenSSL.SSL.Context} object. """ if self._context is None: self._context = self._makeContext() return self._context
Example #26
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _configureOpenSSL102(self, ctx): """ Have the context automatically choose elliptic curves for ECDH. Run on OpenSSL 1.0.2 and OpenSSL 1.1.0+, but only has an effect on OpenSSL 1.0.2. @param ctx: The context which . @type ctx: L{OpenSSL.SSL.Context} """ ctxPtr = ctx._context try: self._openSSLlib.SSL_CTX_set_ecdh_auto(ctxPtr, True) except: pass
Example #27
Source File: ssl_helpers.py From learn_python3_spider with MIT License | 5 votes |
def getContext(self): return SSL.Context(SSL.TLSv1_METHOD)
Example #28
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _identityVerifyingInfoCallback(self, connection, where, ret): """ U{info_callback <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback> } for pyOpenSSL that verifies the hostname in the presented certificate matches the one passed to this L{ClientTLSOptions}. @param connection: the connection which is handshaking. @type connection: L{OpenSSL.SSL.Connection} @param where: flags indicating progress through a TLS handshake. @type where: L{int} @param ret: ignored @type ret: ignored """ # Literal IPv4 and IPv6 addresses are not permitted # as host names according to the RFCs if where & SSL.SSL_CB_HANDSHAKE_START and self._hostnameIsDnsName: connection.set_tlsext_host_name(self._hostnameBytes) elif where & SSL.SSL_CB_HANDSHAKE_DONE: try: if self._hostnameIsDnsName: verifyHostname(connection, self._hostnameASCII) else: verifyIPAddress(connection, self._hostnameASCII) except VerificationError: f = Failure() transport = connection.get_app_data() transport.failVerification(f)
Example #29
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _configureOpenSSL101(self, ctx): """ Set the default elliptic curve for ECDH on the context. Only run on OpenSSL 1.0.1. @param ctx: The context on which to set the ECDH curve. @type ctx: L{OpenSSL.SSL.Context} """ try: ctx.set_tmp_ecdh(self._ecCurve) except: pass
Example #30
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _configureOpenSSL110(self, ctx): """ OpenSSL 1.1.0 Contexts are preconfigured with an optimal set of ECDH curves. This method does nothing. @param ctx: L{OpenSSL.SSL.Context} """