本文整理汇总了Python中OpenSSL.SSL.Connection.set_connect_state方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.set_connect_state方法的具体用法?Python Connection.set_connect_state怎么用?Python Connection.set_connect_state使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OpenSSL.SSL.Connection
的用法示例。
在下文中一共展示了Connection.set_connect_state方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _ssl_handshake
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def _ssl_handshake(self):
"""
Perform an SSL handshake w/ the server.
Precondition: a successful STARTTLS exchange has
taken place with Riak
returns True upon success, otherwise an exception is raised
"""
if self._client._credentials:
ssl_ctx = \
Context(self._client._credentials.ssl_version)
try:
configure_context(ssl_ctx, self._client._credentials)
# attempt to upgrade the socket to SSL
ssl_socket = Connection(ssl_ctx, self._socket)
ssl_socket.set_connect_state()
ssl_socket.do_handshake()
# ssl handshake successful
self._socket = ssl_socket
if self._client._credentials.has_credential('crl'):
self._client._credentials.check_revoked_cert(ssl_socket)
return True
except Exception as e:
# fail if *any* exceptions are thrown during SSL handshake
raise RiakError(e.message)
示例2: test_set_default_verify_paths
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def test_set_default_verify_paths(self):
"""
L{Context.set_default_verify_paths} causes the platform-specific CA
certificate locations to be used for verification purposes.
"""
# Testing this requires a server with a certificate signed by one of
# the CAs in the platform CA location. Getting one of those costs
# money. Fortunately (or unfortunately, depending on your
# perspective), it's easy to think of a public server on the
# internet which has such a certificate. Connecting to the network
# in a unit test is bad, but it's the only way I can think of to
# really test this. -exarkun
# Arg, verisign.com doesn't speak TLSv1
context = Context(SSLv3_METHOD)
context.set_default_verify_paths()
context.set_verify(
VERIFY_PEER,
lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
client = socket()
client.connect(('verisign.com', 443))
clientSSL = Connection(context, client)
clientSSL.set_connect_state()
clientSSL.do_handshake()
clientSSL.send('GET / HTTP/1.0\r\n\r\n')
self.assertTrue(clientSSL.recv(1024))
示例3: test_set_info_callback
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def test_set_info_callback(self):
"""
L{Context.set_info_callback} accepts a callable which will be invoked
when certain information about an SSL connection is available.
"""
(server, client) = socket_pair()
clientSSL = Connection(Context(TLSv1_METHOD), client)
clientSSL.set_connect_state()
called = []
def info(conn, where, ret):
called.append((conn, where, ret))
context = Context(TLSv1_METHOD)
context.set_info_callback(info)
context.use_certificate(
load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
context.use_privatekey(
load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
serverSSL = Connection(context, server)
serverSSL.set_accept_state()
while not called:
for ssl in clientSSL, serverSSL:
try:
ssl.do_handshake()
except WantReadError:
pass
# Kind of lame. Just make sure it got called somehow.
self.assertTrue(called)
示例4: server_ok
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def server_ok(serverarg, capath, timeout):
"Check if the server is active and responsive"
server_ctx = Context(TLSv1_METHOD)
server_ctx.load_verify_locations(None, capath)
def verify_cb(conn, cert, errnum, depth, ok):
return ok
server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
serverarg = re.split("/*", serverarg)[1]
if ':' in serverarg:
serverarg = serverarg.split(':')
server = serverarg[0]
port = int(serverarg[1] if not '?' in serverarg[1] else serverarg[1].split('?')[0])
else:
server = serverarg
port = DEFAULT_PORT
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((server, port))
server_conn = Connection(server_ctx, sock)
server_conn.set_connect_state()
try:
def handler(signum, frame):
raise socket.error([('Timeout', 'after', str(timeout) + 's')])
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
server_conn.do_handshake()
signal.alarm(0)
except socket.timeout as e:
nagios_out('Critical',
'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)),2)
server_conn.shutdown()
server_conn.close()
except (SSLError, socket.error) as e:
if 'sslv3 alert handshake failure' in errmsg_from_excp(e):
pass
else:
nagios_out('Critical',
'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)), 2)
return True
示例5: verify_cert
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def verify_cert(host, ca, timeout):
server_ctx = Context(TLSv1_METHOD)
server_cert_chain = []
if os.path.isdir(ca):
server_ctx.load_verify_locations(None, ca)
else:
server_ctx.load_verify_locations(ca, None)
def verify_cb(conn, cert, errnum, depth, ok):
server_cert_chain.append(cert)
return ok
server_ctx.set_verify(VERIFY_PEER, verify_cb)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(1)
sock.settimeout(timeout)
sock.connect((host, 443))
server_conn = Connection(server_ctx, sock)
server_conn.set_connect_state()
def iosock_try():
ok = True
try:
server_conn.do_handshake()
sleep(0.5)
except SSLWantReadError as e:
ok = False
pass
except Exception as e:
raise e
return ok
try:
while True:
if iosock_try():
break
server_subject = server_cert_chain[-1].get_subject()
if host != server_subject.CN:
raise SSLError('Server certificate CN does not match %s' % host)
except SSLError as e:
raise e
finally:
server_conn.shutdown()
server_conn.close()
return True
示例6: _load_verify_locations_test
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def _load_verify_locations_test(self, *args):
port = socket()
port.bind(('', 0))
port.listen(1)
client = socket()
client.setblocking(False)
client.connect_ex(port.getsockname())
clientContext = Context(TLSv1_METHOD)
clientContext.load_verify_locations(*args)
# Require that the server certificate verify properly or the
# connection will fail.
clientContext.set_verify(
VERIFY_PEER,
lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
clientSSL = Connection(clientContext, client)
clientSSL.set_connect_state()
server, _ = port.accept()
server.setblocking(False)
serverContext = Context(TLSv1_METHOD)
serverContext.use_certificate(
load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
serverContext.use_privatekey(
load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
serverSSL = Connection(serverContext, server)
serverSSL.set_accept_state()
for i in range(3):
for ssl in clientSSL, serverSSL:
try:
# Without load_verify_locations above, the handshake
# will fail:
# Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
# 'certificate verify failed')]
ssl.do_handshake()
except WantReadError:
pass
cert = clientSSL.get_peer_certificate()
self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
示例7: verify_servercert
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def verify_servercert(host, timeout, capath):
server_ctx = Context(TLSv1_METHOD)
server_ctx.load_verify_locations(None, capath)
server_cert_chain = []
def verify_cb(conn, cert, errnum, depth, ok):
server_cert_chain.append(cert)
return ok
server_ctx.set_verify(VERIFY_PEER, verify_cb)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(1)
sock.settimeout(timeout)
sock.connect((host, 443))
server_conn = Connection(server_ctx, sock)
server_conn.set_connect_state()
def iosock_try():
ok = True
try:
server_conn.do_handshake()
sleep(0.5)
except SSLWantReadError as e:
ok = False
pass
except Exception as e:
raise e
return ok
try:
while True:
if iosock_try():
break
global server_expire
server_expire = server_cert_chain[-1].get_notAfter()
except PyOpenSSLError as e:
raise e
finally:
server_conn.shutdown()
server_conn.close()
return True
示例8: _client
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def _client(self, sock):
"""
Create a new client-side SSL L{Connection} object wrapped around
C{sock}.
"""
# Now create the client side Connection. Similar boilerplate to the
# above.
client_ctx = Context(TLSv1_METHOD)
client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
client_store = client_ctx.get_cert_store()
client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
client_ctx.check_privatekey()
client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
client_conn = Connection(client_ctx, sock)
client_conn.set_connect_state()
return client_conn
示例9: OpenSSLSNI
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
class OpenSSLSNI(object):
"""This class implements the functionality of obtaining certificates secure connection using
apache TLS Extension Server Name Indication (SNI)
"""
def connection(func):
def wrapped(self):
self._connect()
try:
return func(self)
finally:
self._close()
return wrapped
def __init__(self, host, port):
#Set host name
self._host = str(host).split('//')[-1].split(':')[0]
#Set port
self._port = int(port) if str(port).isdigit() else 443
def _connect(self):
"""This method implements the functionality of establishing a secure connection using TLS Extension"""
self._socket_client = socket()
self._socket_client.connect((self._host, self._port))
self._ssl_client = Connection(Context(TLSv1_METHOD), self._socket_client)
self._ssl_client.set_connect_state()
self._ssl_client.set_tlsext_host_name(self._host)
self._ssl_client.do_handshake()
def _close(self):
"""This method implements the functional termination created connection"""
self._ssl_client.close()
del self._socket_client
@property
@connection
def serial_number(self):
"""Returns certificates serial number"""
return self._ssl_client.get_peer_certificate().get_serial_number()
@property
@connection
def certificate(self):
"""Returns certificate"""
return OpenSSL.crypto.dump_certificate(FILETYPE_PEM, self._ssl_client.get_peer_certificate())
示例10: netflix_openssl_test_retry
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def netflix_openssl_test_retry(ip):
client = socket()
print 'Connecting...',
stdout.flush()
client.connect((ip, port))
print 'connected', client.getpeername()
client_ssl = Connection(Context(TLSv1_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(hostname)
client_ssl.do_handshake()
cert = client_ssl.get_peer_certificate().get_subject()
cn = [comp for comp in cert.get_components() if comp[0] in ['CN']]
client_ssl.close()
print cn
if hostname in cn[0][1]:
return True
else:
return False
示例11: _validate_certificate_hostname_pyopenssl
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def _validate_certificate_hostname_pyopenssl(self):
""" Use pyOpenSSL check if the host's certifcate matches the hostname.
Python < 2.7.9 is not able to provide a server hostname for SNI, so this
is a fallback that opens an additional connection if the initial
validation failed.
Returns:
bool: Whether or not the hostname is valid on the certificate.
"""
client = socket.socket()
client.connect((self.host, self.port))
client_ssl = Connection(Context(TLSv1_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(self.host)
client_ssl.do_handshake()
cert = client_ssl.get_peer_certificate()
client_ssl.close()
common_name = cert.get_subject().commonName
return self._cert_host_matches_hostname(common_name, self.host)
示例12: SSLSock
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
class SSLSock(TcpSock):
def __init__(self,*args,**kwargs):
TcpSock.__init__(self,*args,**kwargs)
self.raw_sock=self.sock
self.sock=Connection(Context(TLSv1_METHOD),self.raw_sock)
self.sock.set_connect_state()
self.sock.do_handshake()
def sock_recv(self,size,nodata_delay):
if size is None: size=self.recv_size
try: return self.sock.read(size)
except WantReadError:
tmout=self.timeout
if tmout is None: raise
if not select.select([self.sock],[],[],tmout)[0]:
raise socket.timeout,"No data in %s seconds"%(tmout,)
try: return self.sock.read(size)
except ZeroReturnError: return ""
except ZeroReturnError: return ""
except SysCallError,e:
if e[0]==-1: return ""
raise
示例13: main
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def main():
"""
Connect to an SNI-enabled server and request a specific hostname, specified
by argv[1], of it.
"""
if len(argv) < 2:
print 'Usage: %s <hostname>' % (argv[0],)
return 1
client = socket()
print 'Connecting...',
stdout.flush()
client.connect(('127.0.0.1', 8443))
print 'connected', client.getpeername()
client_ssl = Connection(Context(TLSv1_METHOD), client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(argv[1])
client_ssl.do_handshake()
print 'Server subject is', client_ssl.get_peer_certificate().get_subject()
client_ssl.close()
示例14: main
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def main():
port = socket()
port.bind(('', 0))
port.listen(5)
client = socket()
client.setblocking(False)
client.connect_ex(port.getsockname())
client.setblocking(True)
server = port.accept()[0]
clientCtx = Context(TLSv1_METHOD)
clientCtx.set_cipher_list('ALL:ADH')
clientCtx.load_tmp_dh('dhparam.pem')
sslClient = Connection(clientCtx, client)
sslClient.set_connect_state()
serverCtx = Context(TLSv1_METHOD)
serverCtx.set_cipher_list('ALL:ADH')
serverCtx.load_tmp_dh('dhparam.pem')
sslServer = Connection(serverCtx, server)
sslServer.set_accept_state()
t1 = Thread(target=send, args=(sslClient,))
t2 = Thread(target=send, args=(sslServer,))
t3 = Thread(target=recv, args=(sslClient,))
t4 = Thread(target=recv, args=(sslServer,))
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
示例15: go
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import set_connect_state [as 别名]
def go():
port = socket()
port.bind(('', 0))
port.listen(1)
called = []
def info(*args):
print count.next()
called.append(None)
return 1
context = Context(TLSv1_METHOD)
context.set_verify(VERIFY_PEER, info)
context.use_certificate(
load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
context.use_privatekey(
load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
while 1:
client = socket()
client.setblocking(False)
client.connect_ex(port.getsockname())
clientSSL = Connection(context, client)
clientSSL.set_connect_state()
server, ignored = port.accept()
server.setblocking(False)
serverSSL = Connection(context, server)
serverSSL.set_accept_state()
del called[:]
while not called:
for ssl in clientSSL, serverSSL:
try:
ssl.send('foo')
except WantReadError, e:
pass