本文整理汇总了Python中OpenSSL.SSL.Connection.get_peer_certificate方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.get_peer_certificate方法的具体用法?Python Connection.get_peer_certificate怎么用?Python Connection.get_peer_certificate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OpenSSL.SSL.Connection
的用法示例。
在下文中一共展示了Connection.get_peer_certificate方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: OpenSSLSNI
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [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())
示例2: _load_verify_locations_test
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [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')
示例3: netflix_openssl_test_retry
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [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
示例4: _validate_certificate_hostname_pyopenssl
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [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)
示例5: main
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [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()
示例6: TLSMemoryBIOProtocol
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [as 别名]
#.........这里部分代码省略.........
def write(self, bytes):
"""
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
If C{loseConnection} was called, subsequent calls to C{write} will
drop the bytes on the floor.
"""
if isinstance(bytes, unicode):
raise TypeError("Must write bytes to a TLS transport, not unicode.")
# Writes after loseConnection are not supported, unless a producer has
# been registered, in which case writes can happen until the producer
# is unregistered:
if self.disconnecting and self._producer is None:
return
self._write(bytes)
def _write(self, bytes):
"""
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
This may be called by C{dataReceived} with bytes that were buffered
before C{loseConnection} was called, which is why this function
doesn't check for disconnection but accepts the bytes regardless.
"""
if self._lostTLSConnection:
return
leftToSend = bytes
while leftToSend:
try:
sent = self._tlsConnection.send(leftToSend)
except WantReadError:
self._writeBlockedOnRead = True
self._appSendBuffer.append(leftToSend)
if self._producer is not None:
self._producer.pauseProducing()
break
except Error:
# Pretend TLS connection disconnected, which will trigger
# disconnect of underlying transport. The error will be passed
# to the application protocol's connectionLost method. The
# other SSL implementation doesn't, but losing helpful
# debugging information is a bad idea.
self._tlsShutdownFinished(Failure())
break
else:
# If we sent some bytes, the handshake must be done. Keep
# track of this to control error reporting behavior.
self._handshakeDone = True
self._flushSendBIO()
leftToSend = leftToSend[sent:]
def writeSequence(self, iovec):
"""
Write a sequence of application bytes by joining them into one string
and passing them to L{write}.
"""
self.write(b"".join(iovec))
def getPeerCertificate(self):
return self._tlsConnection.get_peer_certificate()
def registerProducer(self, producer, streaming):
# If we've already disconnected, nothing to do here:
if self._lostTLSConnection:
producer.stopProducing()
return
# If we received a non-streaming producer, wrap it so it becomes a
# streaming producer:
if not streaming:
producer = streamingProducer = _PullToPush(producer, self)
producer = _ProducerMembrane(producer)
# This will raise an exception if a producer is already registered:
self.transport.registerProducer(producer, True)
self._producer = producer
# If we received a non-streaming producer, we need to start the
# streaming wrapper:
if not streaming:
streamingProducer.startStreaming()
def unregisterProducer(self):
# If we received a non-streaming producer, we need to stop the
# streaming wrapper:
if isinstance(self._producer._producer, _PullToPush):
self._producer._producer.stopStreaming()
self._producer = None
self._producerPaused = False
self.transport.unregisterProducer()
if self.disconnecting and not self._writeBlockedOnRead:
self._shutdownTLS()
示例7: Context
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [as 别名]
from OpenSSL.SSL import Connection, Context, SSLv3_METHOD, TLSv1_2_METHOD
host = 'www.baidu.com'
try:
ssl_connection_setting = Context(SSLv3_METHOD)
except ValueError:
ssl_connection_setting = Context(TLSv1_2_METHOD)
ssl_connection_setting.set_timeout(30)
s = socket()
s.connect((host, 443))
c = Connection(ssl_connection_setting, s)
c.set_connect_state()
c.do_handshake()
cert = c.get_peer_certificate()
print "Issuer: ", cert.get_issuer()
print "Subject: ", cert.get_subject().get_components()
subject_list = cert.get_subject().get_components()
print "Common Name:", dict(subject_list).get("CN")
print "notAfter(UTC time): ", cert.get_notAfter()
UTC_FORMAT = "%Y%m%d%H%M%SZ"
utc_to_local_offset = datetime.datetime.fromtimestamp(time.time()) - datetime.datetime.utcfromtimestamp(time.time())
utc_time = time.mktime(time.strptime(cert.get_notAfter(), UTC_FORMAT))
local_time = utc_time + utc_to_local_offset.seconds
print "notAfter(Local Time): ", datetime.datetime.fromtimestamp(local_time)
print "is_expired:", cert.has_expired()
c.shutdown()
s.close()
示例8: exit
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [as 别名]
try:
proxy.connect((host, port))
except socket_error:
proxy.close()
exit("[-] problem connecting to " + str(host) + ":" + str(port))
ssl = SSL_Connection(ctx, proxy)
ssl.setblocking(True)
try:
ssl.set_connect_state()
ssl.do_handshake()
except:
exit(1)
digest = ssl.get_peer_certificate().digest("sha1")
proxy.close()
checkcert = digest.replace(":", "").lower() + ".certs.googlednstest.com"
try:
response = query(checkcert, "TXT")
except:
exit(0)
if not response:
print "No response from the DNS for this cert"
exit(0)
ans = str(response[0]).replace('"', "").split(" ")
print asctime(localtime(int(ans[0]) * 24 * 3600))
print asctime(localtime(int(ans[1]) * 24 * 3600))
示例9: exit
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import get_peer_certificate [as 别名]
print " \n\n Unable to complet the SSL Handshake %s" % msg
exit(1)
pass
#--- Get the remote host name
rhost = soc.getpeername()
log(("\nRemote Host name :" + host), sink)
log(("\nRemote Host IPv4 :" + rhost[0]), sink)
log(("\nRemote Host Port :" + str(rhost[1])), sink)
#--- Get and Analyse Server Certificate
cert = soc_ssl.get_peer_certificate()
cipher = soc_ssl.get_cipher_name()
log(("\nCipher Suite used : " + cipher), sink)
#--- Get Subject Info
subject_comps = cert.get_subject().get_components()
subject_name = cert.get_subject().commonName
if (not subject_name):
subject_name = get_x509_val(subject_comps, "O")
log("\nSubject Name = " + subject_name, sink)