Python OpenSSL.SSL 模块,SSLv23_METHOD() 实例源码
我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用OpenSSL.SSL.SSLv23_METHOD()。
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()
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
)
def test_methodIsDeprecated(self):
"""
Passing C{method} to L{sslverify.OpenSSLCertificateOptions} is
deprecated.
"""
sslverify.OpenSSLCertificateOptions(
privateKey=self.sKey,
certificate=self.sCert,
method=SSL.SSLv23_METHOD,
)
message = ("Passing method to twisted.internet.ssl.CertificateOptions "
"was deprecated in Twisted 17.1.0. Please use a "
"combination of insecurelyLowerMinimumTo, raiseMinimumTo, "
"and lowerMaximumSecurityTo instead, as Twisted will "
"correctly configure the method.")
warnings = self.flushWarnings([self.test_methodIsDeprecated])
self.assertEqual(1, len(warnings))
self.assertEqual(DeprecationWarning, warnings[0]['category'])
self.assertEqual(message, warnings[0]['message'])
def test_tlsProtocolsNoMethodWithAtLeast(self):
"""
Passing C{raiseMinimumTo} along with C{method} to
L{sslverify.OpenSSLCertificateOptions} will cause it to raise an
exception.
"""
with self.assertRaises(TypeError) as e:
sslverify.OpenSSLCertificateOptions(
privateKey=self.sKey,
certificate=self.sCert,
method=SSL.SSLv23_METHOD,
raiseMinimumTo=sslverify.TLSVersion.TLSv1_2,
)
# Best error message
self.assertEqual(e.exception.args, ("nope",))
def test_tlsProtocolsNoMethodWithMinimum(self):
"""
Passing C{insecurelyLowerMinimumTo} along with C{method} to
L{sslverify.OpenSSLCertificateOptions} will cause it to raise an
exception.
"""
with self.assertRaises(TypeError) as e:
sslverify.OpenSSLCertificateOptions(
privateKey=self.sKey,
certificate=self.sCert,
method=SSL.SSLv23_METHOD,
insecurelyLowerMinimumTo=sslverify.TLSVersion.TLSv1_2,
)
# Best error message
self.assertEqual(e.exception.args, ("nope",))
def test_tlsProtocolsNoMethodWithMaximum(self):
"""
Passing C{lowerMaximumSecurityTo} along with C{method} to
L{sslverify.OpenSSLCertificateOptions} will cause it to raise an
exception.
"""
with self.assertRaises(TypeError) as e:
sslverify.OpenSSLCertificateOptions(
privateKey=self.sKey,
certificate=self.sCert,
method=SSL.SSLv23_METHOD,
lowerMaximumSecurityTo=sslverify.TLSVersion.TLSv1_2,
)
# Best error message
self.assertEqual(e.exception.args, ("nope",))
def test_method(self):
"""
L{Context} can be instantiated with one of L{SSLv2_METHOD},
L{SSLv3_METHOD}, L{SSLv23_METHOD}, or L{TLSv1_METHOD}.
"""
for meth in [SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]:
Context(meth)
try:
Context(SSLv2_METHOD)
except ValueError:
# Some versions of OpenSSL have SSLv2, some don't.
# Difficult to say in advance.
pass
self.assertRaises(TypeError, Context, "")
self.assertRaises(ValueError, Context, 10)
def connect (self, host, port):
if self.state == 1:
print "Already has an active connection"
elif self.type == 0: # TCP
if self.ssl == 1:
ctx = SSL.Context (SSL.SSLv23_METHOD)
s = SSL.Connection (ctx, socket(AF_INET, SOCK_STREAM))
try:
err = s.connect_ex ((host, port))
except:
print "Couldn't connect SSL socket"
return
if err == 0:
self.skt = s
self.state = 1
else:
s = socket (AF_INET, SOCK_STREAM)
try:
err = s.connect_ex ((host, port))
except:
print "Couldn't connect TCP socket"
return
if err == 0:
self.skt = s
self.state = 1
elif self.type == 1: # UDP
s = socket (AF_INET, SOCK_DGRAM)
try:
err = s.connect_ex ((host, port))
except:
print "Couldn't create UDP socket"
return
if err == 0:
self.skt = s
self.state = 1
else:
print "RAW sockets not implemented yet"
if self.state == 1:
return "OK"
def test_method(self):
"""
L{Context} can be instantiated with one of L{SSLv2_METHOD},
L{SSLv3_METHOD}, L{SSLv23_METHOD}, or L{TLSv1_METHOD}.
"""
for meth in [SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]:
Context(meth)
self.assertRaises(TypeError, Context, "")
self.assertRaises(ValueError, Context, 10)
def __init__(self, privateKeyFileName, certificateFileName,
sslmethod=SSL.SSLv23_METHOD):
"""
@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.cacheContext()
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def test_method(self):
"""
L{Context} can be instantiated with one of L{SSLv2_METHOD},
L{SSLv3_METHOD}, L{SSLv23_METHOD}, or L{TLSv1_METHOD}.
"""
for meth in [SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]:
Context(meth)
self.assertRaises(TypeError, Context, "")
self.assertRaises(ValueError, Context, 10)
def __init__(self, privateKeyFileName, certificateFileName,
sslmethod=SSL.SSLv23_METHOD):
"""
@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.cacheContext()
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def test_ssl_options(self):
from OpenSSL import SSL
from OpenSSL._util import lib
from pyftpdlib.handlers import TLS_FTPHandler
try:
TLS_FTPHandler.ssl_context = None
ctx = TLS_FTPHandler.get_ssl_context()
# Verify default opts.
with contextlib.closing(socket.socket()) as s:
s = SSL.Connection(ctx, s)
opts = lib.SSL_CTX_get_options(ctx._context)
self.assertTrue(opts & SSL.OP_NO_SSLv2)
self.assertTrue(opts & SSL.OP_NO_SSLv3)
self.assertTrue(opts & SSL.OP_NO_COMPRESSION)
TLS_FTPHandler.ssl_context = None # reset
# Make sure that if ssl_options is None no options are set
# (except OP_NO_SSLv2 whch is enabled by default unless
# ssl_proto is set to SSL.SSLv23_METHOD).
TLS_FTPHandler.ssl_context = None
TLS_FTPHandler.ssl_options = None
ctx = TLS_FTPHandler.get_ssl_context()
with contextlib.closing(socket.socket()) as s:
s = SSL.Connection(ctx, s)
opts = lib.SSL_CTX_get_options(ctx._context)
self.assertTrue(opts & SSL.OP_NO_SSLv2)
# self.assertFalse(opts & SSL.OP_NO_SSLv3)
self.assertFalse(opts & SSL.OP_NO_COMPRESSION)
finally:
TLS_FTPHandler.ssl_context = None
def _openssl_connect(hostname):
client = socket()
client.connect((hostname, 443))
client_ssl = Connection(Context(SSLv23_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(hostname.encode('utf-8'))
client_ssl.do_handshake()
return client_ssl
def _openssl_connect(hostname):
client = socket()
client.connect((hostname, 443))
client_ssl = Connection(Context(SSLv23_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(hostname.encode('utf-8'))
client_ssl.do_handshake()
return client_ssl
def _openssl_connect(hostname):
client = socket()
client.connect((hostname, 443))
client_ssl = Connection(Context(SSLv23_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(hostname.encode('utf-8'))
client_ssl.do_handshake()
return client_ssl
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c
def _getCertificateOptions(self, hostname, port):
"""
Return a L{CertificateOptions}.
@param hostname: ignored
@param port: ignored
@return: A new CertificateOptions instance.
@rtype: L{CertificateOptions}
"""
return CertificateOptions(
method=SSL.SSLv23_METHOD,
trustRoot=platformTrust()
)
def protocolNegotiationMechanisms():
"""
Checks whether your versions of PyOpenSSL and OpenSSL are recent enough to
support protocol negotiation, and if they are, what kind of protocol
negotiation is supported.
@return: A combination of flags from L{ProtocolNegotiationSupport} that
indicate which mechanisms for protocol negotiation are supported.
@rtype: L{constantly.FlagConstant}
"""
support = ProtocolNegotiationSupport.NOSUPPORT
ctx = SSL.Context(SSL.SSLv23_METHOD)
try:
ctx.set_npn_advertise_callback(lambda c: None)
except (AttributeError, NotImplementedError):
pass
else:
support |= ProtocolNegotiationSupport.NPN
try:
ctx.set_alpn_select_callback(lambda c: None)
except (AttributeError, NotImplementedError):
pass
else:
support |= ProtocolNegotiationSupport.ALPN
return support
def fromOpenSSLCipherString(cls, cipherString):
"""
Create a new instance using an OpenSSL cipher string.
@param cipherString: An OpenSSL cipher string that describes what
cipher suites are acceptable.
See the documentation of U{OpenSSL
<http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS>} or
U{Apache
<http://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslciphersuite>}
for details.
@type cipherString: L{unicode}
@return: Instance representing C{cipherString}.
@rtype: L{twisted.internet.ssl.AcceptableCiphers}
"""
return cls(_expandCipherString(
nativeString(cipherString),
SSL.SSLv23_METHOD, SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
)
# A secure default.
# Sources for more information on TLS ciphers:
#
# - https://wiki.mozilla.org/Security/Server_Side_TLS
# - https://www.ssllabs.com/projects/best-practices/index.html
# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
#
# The general intent is:
# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
# - prefer ECDHE over DHE for better performance,
# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
# security,
# - prefer AES-GCM to ChaCha20 because AES hardware support is common,
# - disable NULL authentication, MD5 MACs and DSS for security reasons.
#
def test_method(self):
"""
L{ssl.DefaultOpenSSLContextFactory.getContext} returns an SSL context
which can use SSLv3 or TLSv1 but not SSLv2.
"""
# SSLv23_METHOD allows SSLv2, SSLv3, or TLSv1
self.assertEqual(self.context._method, SSL.SSLv23_METHOD)
# And OP_NO_SSLv2 disables the SSLv2 support.
self.assertTrue(self.context._options & SSL.OP_NO_SSLv2)
# Make sure SSLv3 and TLSv1 aren't disabled though.
self.assertFalse(self.context._options & SSL.OP_NO_SSLv3)
self.assertFalse(self.context._options & SSL.OP_NO_TLSv1)
def test_certificateOptionsSerialization(self):
"""
Test that __setstate__(__getstate__()) round-trips properly.
"""
firstOpts = sslverify.OpenSSLCertificateOptions(
privateKey=self.sKey,
certificate=self.sCert,
method=SSL.SSLv23_METHOD,
verify=True,
caCerts=[self.sCert],
verifyDepth=2,
requireCertificate=False,
verifyOnce=False,
enableSingleUseKeys=False,
enableSessions=False,
fixBrokenPeers=True,
enableSessionTickets=True)
context = firstOpts.getContext()
self.assertIs(context, firstOpts._context)
self.assertIsNotNone(context)
state = firstOpts.__getstate__()
self.assertNotIn("_context", state)
opts = sslverify.OpenSSLCertificateOptions()
opts.__setstate__(state)
self.assertEqual(opts.privateKey, self.sKey)
self.assertEqual(opts.certificate, self.sCert)
self.assertEqual(opts.method, SSL.SSLv23_METHOD)
self.assertTrue(opts.verify)
self.assertEqual(opts.caCerts, [self.sCert])
self.assertEqual(opts.verifyDepth, 2)
self.assertFalse(opts.requireCertificate)
self.assertFalse(opts.verifyOnce)
self.assertFalse(opts.enableSingleUseKeys)
self.assertFalse(opts.enableSessions)
self.assertTrue(opts.fixBrokenPeers)
self.assertTrue(opts.enableSessionTickets)
def test_returnsListOfICiphers(self):
"""
L{sslverify._expandCipherString} always returns a L{list} of
L{interfaces.ICipher}.
"""
ciphers = sslverify._expandCipherString(u'ALL', SSL.SSLv23_METHOD, 0)
self.assertIsInstance(ciphers, list)
bogus = []
for c in ciphers:
if not interfaces.ICipher.providedBy(c):
bogus.append(c)
self.assertEqual([], bogus)
def test_set_context(self):
"""
L{Connection.set_context} specifies a new L{Context} instance to be used
for the connection.
"""
original = Context(SSLv23_METHOD)
replacement = Context(TLSv1_METHOD)
connection = Connection(original, None)
connection.set_context(replacement)
self.assertIdentical(replacement, connection.get_context())
# Lose our references to the contexts, just in case the Connection isn't
# properly managing its own contributions to their reference counts.
del original, replacement
collect()
def get_context(self):
"""Return an SSL.Context from self attributes."""
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
c = SSL.Context(SSL.SSLv23_METHOD)
c.use_privatekey_file(self.private_key)
if self.certificate_chain:
c.load_verify_locations(self.certificate_chain)
c.use_certificate_file(self.certificate)
return c