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


Python SSL.Connection类代码示例

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


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

示例1: _ssl_handshake

    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,代码行数:26,代码来源:connection.py

示例2: will_use_tls_1_3

def will_use_tls_1_3():
    """
    Will OpenSSL negotiate TLS 1.3?
    """
    ctx = Context(SSLv23_METHOD)
    connection = Connection(ctx, None)
    return connection.get_protocol_version_name() == u'TLSv1.3'
开发者ID:glyph,项目名称:txsni,代码行数:7,代码来源:test_txsni.py

示例3: connect

 def connect(self, *args, **kwargs):
     while True:
         try:
             _Connection.connect(self, *args, **kwargs)
             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,代码行数:11,代码来源:gevent_openssl.py

示例4: do_handshake

 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,代码行数:11,代码来源:gevent_openssl.py

示例5: __init__

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,代码行数:51,代码来源:HTTPSConnectionHandler.py

示例6: test_set_default_verify_paths

    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,代码行数:27,代码来源:test_ssl.py

示例7: recv

 def recv(self, bufsiz, flags=0):
     pending = _Connection.pending(self)
     if pending:
         return _Connection.recv(min(pending, bufsiz))
     while True:
         try:
             return _Connection.recv(self, buflen, flags)
         except WantReadError:
             exc_clear()
             wait_read(self._sock.fileno(), timeout=self._timeout)
         except WantWriteError:
             exc_clear()
             wait_write(self._sock.fileno(), timeout=self._timeout)
         except ZeroReturnError:
             return ''
开发者ID:ayanamist,项目名称:gevent_openssl,代码行数:15,代码来源:gevent_openssl.py

示例8: verify_callback

    def verify_callback(
            conn: SSL.Connection,
            x509: SSL.X509,
            errno: int,
            depth: int,
            is_cert_verified: bool
    ) -> bool:
        if is_cert_verified and depth == 0:
            # Verify hostname of leaf certificate.
            cert = certs.Cert(x509)
            try:
                crt: typing.Dict[str, typing.Any] = dict(
                    subjectAltName=[("DNS", x.decode("ascii", "strict")) for x in cert.altnames]
                )
                if cert.cn:
                    crt["subject"] = [[["commonName", cert.cn.decode("ascii", "strict")]]]
                if sni:
                    # SNI hostnames allow support of IDN by using ASCII-Compatible Encoding
                    # Conversion algorithm is in RFC 3490 which is implemented by idna codec
                    # https://docs.python.org/3/library/codecs.html#text-encodings
                    # https://tools.ietf.org/html/rfc6066#section-3
                    # https://tools.ietf.org/html/rfc4985#section-3
                    hostname = sni.encode("idna").decode("ascii")
                else:
                    hostname = "no-hostname"
                match_hostname(crt, hostname)
            except (ValueError, CertificateError) as e:
                conn.cert_error = exceptions.InvalidCertificateException(
                    "Certificate verification error for {}: {}".format(
                        sni or repr(address),
                        str(e)
                    )
                )
                is_cert_verified = False
        elif is_cert_verified:
            pass
        else:
            conn.cert_error = exceptions.InvalidCertificateException(
                "Certificate verification error for {}: {} (errno: {}, depth: {})".format(
                    sni,
                    SSL._ffi.string(SSL._lib.X509_verify_cert_error_string(errno)).decode(),
                    errno,
                    depth
                )
            )

        # SSL_VERIFY_NONE: The handshake will be continued regardless of the verification result.
        return is_cert_verified
开发者ID:jbremer,项目名称:mitmproxy,代码行数:48,代码来源:tls.py

示例9: 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()
开发者ID:tylerwowen,项目名称:mitm_proxy,代码行数:7,代码来源:HTTPSConnectionHandler.py

示例10: makeConnection

    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()
开发者ID:BillAndersan,项目名称:twisted,代码行数:34,代码来源:tls.py

示例11: send

 def send(self, data, flags=0):
     while True:
         try:
             _Connection.send(self, data, flags)
             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)
         except SysCallError as e:
             if e[0] == -1 and not data:
                 # errors when writing empty strings are expected and can be ignored
                 return 0
             raise
开发者ID:ayanamist,项目名称:gevent_openssl,代码行数:16,代码来源:gevent_openssl.py

示例12: _connect

 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()
开发者ID:pombredanne,项目名称:revizor-tests,代码行数:8,代码来源:web_common.py

示例13: server_ok

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,代码行数:50,代码来源:nagios-plugins-openstack-swift_v2.py

示例14: _client

 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
开发者ID:Februar0218,项目名称:openwrt-mt7620-1,代码行数:18,代码来源:test_ssl.py

示例15: OpenSSLSNI

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,代码行数:44,代码来源:web_common.py


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