当前位置: 首页>>代码示例>>Python>>正文


Python Connection.do_handshake方法代码示例

本文整理汇总了Python中OpenSSL.SSL.Connection.do_handshake方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.do_handshake方法的具体用法?Python Connection.do_handshake怎么用?Python Connection.do_handshake使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OpenSSL.SSL.Connection的用法示例。


在下文中一共展示了Connection.do_handshake方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_set_default_verify_paths

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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))
开发者ID:dreamwave,项目名称:rad,代码行数:29,代码来源:test_ssl.py

示例2: _ssl_handshake

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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)
开发者ID:serenabiodec,项目名称:riak-python-client,代码行数:28,代码来源:connection.py

示例3: do_handshake

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]
 def do_handshake(self):
     while True:
         try:
             _Connection.do_handshake(self)
             break
         except WantReadError:
             exc_clear()
             wait_read(self._sock.fileno(), timeout=self._timeout)
         except WantWriteError:
             exc_clear()
             wait_write(self._sock.fileno(), timeout=self._timeout)
开发者ID:ayanamist,项目名称:gevent_openssl,代码行数:13,代码来源:gevent_openssl.py

示例4: __init__

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]
class ManInTheMiddle:

    def __init__(self, client_socket, host, port):
        self.client_socket = client_socket
        self.host = host
        self.port = port
        self.sni = None
        self.client_ssl_sock = None
        self.server_ssl_sock = None

    def start_hacking(self):
        self.client_socket.sendall(('HTTP/1.1 %d %s\r\n\r\n' % (200, 'OK')).encode('latin-1', 'strict'))
        self.accept_client_conn()

    def accept_client_conn(self):
        context = Context(SSLv23_METHOD)
        context.set_tlsext_servername_callback(self.prepare_handshake)

        self.client_ssl_sock = Connection(context, self.client_socket)
        self.client_ssl_sock.set_accept_state()
        self.client_ssl_sock.do_handshake()

    def prepare_handshake(self, connection):
        raw_sni = connection.get_servername()
        if raw_sni is not None:
            self.sni = str(raw_sni, 'ascii')

        self.build_server_conn()
        cert_dict = self.server_ssl_sock.getpeercert()
        crt_dir = generate_fake_cert(cert_dict)
        try:
            key, cert = load(crt_dir)
        except crypto.Error:
            raise CertificateRaceCondition
        new_context = Context(SSLv23_METHOD)
        new_context.use_privatekey(key)
        new_context.use_certificate(cert)
        connection.set_context(new_context)

    def build_server_conn(self):
        server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        server_context.verify_mode = ssl.CERT_OPTIONAL
        # context.load_verify_locations('/etc/ssl/certs/ca-bundle.crt')
        server_context.set_default_verify_paths()
        ssl_sock = server_context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=self.sni)
        try:
            ssl_sock.connect((self.host, self.port))
        except socket.gaierror:
            print(self.host, self.port)
            raise ServerConnectionError
        self.server_ssl_sock = ssl_sock
开发者ID:tylerwowen,项目名称:mitm_proxy,代码行数:53,代码来源:HTTPSConnectionHandler.py

示例5: server_ok

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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
开发者ID:osct,项目名称:swift-nagios-probe,代码行数:52,代码来源:nagios-plugins-openstack-swift_v2.py

示例6: OpenSSLSNI

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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())
开发者ID:pombredanne,项目名称:revizor-tests,代码行数:46,代码来源:web_common.py

示例7: netflix_openssl_test_retry

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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
开发者ID:cjrowson,项目名称:netflix-proxy,代码行数:22,代码来源:__testbuild.py

示例8: SSLSock

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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
开发者ID:korc,项目名称:krutils,代码行数:23,代码来源:net.py

示例9: _validate_certificate_hostname_pyopenssl

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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)
开发者ID:AppScale,项目名称:appscale,代码行数:23,代码来源:__init__.py

示例10: main

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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()
开发者ID:15580056814,项目名称:hue,代码行数:24,代码来源:client.py

示例11: main

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]
def main():
    """
    Run an SNI-enabled server which selects between a few certificates in a
    C{dict} based on the handshake request it receives from a client.
    """
    port = socket()
    port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    port.bind(('', 8443))
    port.listen(3)

    print 'Accepting...',
    stdout.flush()
    server, addr = port.accept()
    print 'accepted', addr

    server_context = Context(TLSv1_METHOD)
    server_context.set_tlsext_servername_callback(pick_certificate)

    server_ssl = Connection(server_context, server)
    server_ssl.set_accept_state()
    server_ssl.do_handshake()
    server.close()
开发者ID:SpiderOak,项目名称:pyopenssl,代码行数:24,代码来源:server.py

示例12: TLSMemoryBIOProtocol

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]

#.........这里部分代码省略.........
        return self._tlsConnection


    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        tlsContext = self.factory._contextFactory.getContext()
        self._tlsConnection = Connection(tlsContext, None)
        if self.factory._isClient:
            self._tlsConnection.set_connect_state()
        else:
            self._tlsConnection.set_accept_state()
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            # This is the expected case - there's no data in the connection's
            # input buffer yet, so it won't be able to complete the whole
            # handshake now.  If this is the speak-first side of the
            # connection, then some bytes will be in the send buffer now; flush
            # them.
            self._flushSendBIO()


    def _flushSendBIO(self):
        """
        Read any bytes out of the send BIO and write them to the underlying
        transport.
        """
        try:
            bytes = self._tlsConnection.bio_read(2 ** 15)
        except WantReadError:
            # There may be nothing in the send BIO right now.
            pass
        else:
            self.transport.write(bytes)


    def _flushReceiveBIO(self):
        """
        Try to receive any application-level bytes which are now available
        because of a previous write into the receive BIO.  This will take
        care of delivering any application-level bytes which are received to
        the protocol, as well as handling of the various exceptions which
        can come from trying to get such bytes.
        """
        # Keep trying this until an error indicates we should stop or we
开发者ID:AmirKhooj,项目名称:VTK,代码行数:70,代码来源:tls.py

示例13: Context

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [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()
开发者ID:DingGuodong,项目名称:LinuxBashShellScriptForOps,代码行数:32,代码来源:pyGetCertsInfo.py

示例14: TLSMemoryBIOProtocol

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]

#.........这里部分代码省略.........
        C{peerFromTransport} and C{hostFromTransport} methods only.  A
        different system handle may be returned by future versions of this
        method.
        """
        return self._tlsConnection


    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        tlsContext = self.factory._contextFactory.getContext()
        self._tlsConnection = Connection(tlsContext, None)
        if self.factory._isClient:
            self._tlsConnection.set_connect_state()
        else:
            self._tlsConnection.set_accept_state()
        self._appSendBuffer = []

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            # This is the expected case - there's no data in the connection's
            # input buffer yet, so it won't be able to complete the whole
            # handshake now.  If this is the speak-first side of the
            # connection, then some bytes will be in the send buffer now; flush
            # them.
            self._flushSendBIO()


    def _flushSendBIO(self):
        """
        Read any bytes out of the send BIO and write them to the underlying
        transport.
        """
        try:
            bytes = self._tlsConnection.bio_read(2 ** 15)
        except WantReadError:
            # There may be nothing in the send BIO right now.
            pass
        else:
            self.transport.write(bytes)


    def _flushReceiveBIO(self):
        """
        Try to receive any application-level bytes which are now available
        because of a previous write into the receive BIO.  This will take
        care of delivering any application-level bytes which are received to
        the protocol, as well as handling of the various exceptions which
        can come from trying to get such bytes.
        """
        # Keep trying this until an error indicates we should stop or we
开发者ID:BillAndersan,项目名称:twisted,代码行数:70,代码来源:tls.py

示例15: socket

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import do_handshake [as 别名]
        if (":" in host and has_ipv6 == True) or (len(argv) >= 4 and ":" in phost and has_ipv6 == True):
            proxy = socket(AF_INET6, SOCK_STREAM)
        else:
            proxy = socket(AF_INET, SOCK_STREAM)

        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)
开发者ID:pwns4cash,项目名称:crap,代码行数:33,代码来源:gglcertcheck.py


注:本文中的OpenSSL.SSL.Connection.do_handshake方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。