Python ssl.SSLError() Examples

The following are 30 code examples of ssl.SSLError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: __init__.py    From tikapy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _connect(self):
        """
        Connects a ssl socket.
        """
        self._connect_socket()
        try:
            ctx = ssl.create_default_context()
            if not self.verify_cert:
                ctx.verify_mode = ssl.CERT_OPTIONAL
            if not self.verify_addr:
                ctx.check_hostname = False
            self._sock = ctx.wrap_socket(self._base_sock,
                                         server_hostname=self.address)
        except ssl.SSLError:
            LOG.error('could not establish SSL connection')
            raise ClientError('could not establish SSL connection') 
Example #2
Source File: Requests.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def scan(self, url):
        url = verify(url)
        try:
            r = self.session.get(url,
                                 timeout=self.timeout,
                                 headers=self.headers,
                                 verify=False,
                                 stream=True,
                                 allow_redirects=False)
            return r

        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example #3
Source File: Requests.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def post(self, url, data):
        url = verify(url)
        try:
            r = self.session.post(url,
                                  data=data,
                                  timeout=self.timeout,
                                  headers=self.headers,
                                  verify=False,
                                  allow_redirects=False)
            return r
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example #4
Source File: Requests.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def request(self, url, method, data=None, headers=None):
        url = verify(url)
        try:
            if method == 'get':
                r = self.session.get(url, timeout=self.timeout, headers=headers, verify=False, allow_redirects=True)
                return r
            else:
                r = self.session.post(url,
                                      data=data,
                                      timeout=self.timeout,
                                      headers=headers,
                                      verify=False,
                                      allow_redirects=False)
                return r
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example #5
Source File: unicorn_binance_websocket_api_connection.py    From unicorn-binance-websocket-api with MIT License 6 votes vote down vote up
def receive(self):
        self.handler_binance_websocket_api_manager.set_heartbeat(self.stream_id)
        try:
            received_data_json = await self.handler_binance_websocket_api_manager.websocket_list[self.stream_id].recv()
            try:
                if self.handler_binance_websocket_api_manager.restart_requests[self.stream_id]['status'] == "restarted":
                    self.handler_binance_websocket_api_manager.increase_reconnect_counter(self.stream_id)
                    del self.handler_binance_websocket_api_manager.restart_requests[self.stream_id]
            except KeyError:
                pass
            if received_data_json is not None:
                size = sys.getsizeof(received_data_json)
                self.handler_binance_websocket_api_manager.increase_processed_receives_statistic(self.stream_id)
                self.handler_binance_websocket_api_manager.add_total_received_bytes(size)
                self.handler_binance_websocket_api_manager.increase_received_bytes_per_second(self.stream_id,
                                                                                              size)
            return received_data_json
        except RuntimeError as error_msg:
            logging.debug("binance_websocket_api_connection->receive(" +
                          str(self.stream_id) + ") - RuntimeError - error_msg: " + str(error_msg))
            sys.exit(1)
        except ssl.SSLError as error_msg:
            logging.debug("binance_websocket_api_connection->receive(" +
                          str(self.stream_id) + ") - ssl.SSLError - error_msg: " + str(error_msg))
        except KeyError as error_msg:
            logging.debug("binance_websocket_api_connection->receive(" +
                          str(self.stream_id) + ") - KeyError - error_msg: " + str(error_msg))
            self.handler_binance_websocket_api_manager.stream_is_stopping(self.stream_id)
            if self.handler_binance_websocket_api_manager.is_stop_request(self.stream_id) is False:
                self.handler_binance_websocket_api_manager.set_restart_request(self.stream_id)
            sys.exit(1)
        except asyncio.base_futures.InvalidStateError as error_msg:
            logging.critical("binance_websocket_api_connection->receive(" +
                             str(self.stream_id) + ") - asyncio.base_futures.InvalidStateError - error_msg: " +
                             str(error_msg) + " - Extra info: https://github.com/oliver-zehentleitner/unicorn-binance-"
                                              "websocket-api/issues/18 - open an own issue if needed!")
            self.handler_binance_websocket_api_manager.stream_is_stopping(self.stream_id)
            if self.handler_binance_websocket_api_manager.is_stop_request(self.stream_id) is False:
                self.handler_binance_websocket_api_manager.set_restart_request(self.stream_id)
            sys.exit(1) 
Example #6
Source File: low_level.py    From gist-alfred with MIT License 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u'':
        output = u'OSStatus %s' % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #7
Source File: reqman.py    From reqman with GNU General Public License v2.0 6 votes vote down vote up
def request(method,url,body:bytes,headers, timeout=None):
    try:
        async with aiohttp.ClientSession(trust_env=True) as session:

            r=await session.request(method,url,data=body,headers=headers,ssl=False,timeout=timeout,allow_redirects=False)
            try:
                obj=await r.json()
                content=jdumps(obj).encode("utf-8") # ensure json chars are not escaped, and are in utf8
            except:
                content=await r.read()
                if not isBytes(content):
                    txt=await r.text()
                    content=txt.encode("utf-8") # force bytes to be in utf8
                    
            info = "HTTP/%s.%s %s %s" % (r.version.major,r.version.minor, int(r.status), r.reason)
            return r.status,  dict(r.headers), Content(content), info
    except aiohttp.client_exceptions.ClientConnectorError as e:
        return None, {}, "Unreachable", ""        
    except concurrent.futures._base.TimeoutError as e:
        return None, {}, "Timeout", ""
    except aiohttp.client_exceptions.InvalidURL as e:
        return None, {}, "Invalid", ""
    except ssl.SSLError:
        pass 
Example #8
Source File: pyopenssl.py    From gist-alfred with MIT License 6 votes vote down vote up
def wrap_socket(self, sock, server_side=False,
                    do_handshake_on_connect=True, suppress_ragged_eofs=True,
                    server_hostname=None):
        cnx = OpenSSL.SSL.Connection(self._ctx, sock)

        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3
            server_hostname = server_hostname.encode('utf-8')

        if server_hostname is not None:
            cnx.set_tlsext_host_name(server_hostname)

        cnx.set_connect_state()

        while True:
            try:
                cnx.do_handshake()
            except OpenSSL.SSL.WantReadError:
                if not util.wait_for_read(sock, sock.gettimeout()):
                    raise timeout('select timed out')
                continue
            except OpenSSL.SSL.Error as e:
                raise ssl.SSLError('bad handshake: %r' % e)
            break

        return WrappedSocket(cnx, sock) 
Example #9
Source File: low_level.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u"":
        output = u"OSStatus %s" % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #10
Source File: pool.py    From recruit with Apache License 2.0 6 votes vote down vote up
def connect(self):
        """Connect to Mongo and return a new (connected) socket. Note that the
           pool does not keep a reference to the socket -- you must call
           return_socket() when you're done with it.
        """
        sock = self.create_connection()
        hostname = self.pair[0]

        if self.use_ssl:
            try:
                sock = ssl.wrap_socket(sock,
                                       certfile=self.ssl_certfile,
                                       keyfile=self.ssl_keyfile,
                                       ca_certs=self.ssl_ca_certs,
                                       cert_reqs=self.ssl_cert_reqs)
                if self.ssl_cert_reqs:
                    match_hostname(sock.getpeercert(), hostname)

            except ssl.SSLError:
                sock.close()
                raise ConnectionFailure("SSL handshake failed. MongoDB may "
                                        "not be configured with SSL support.")

        sock.settimeout(self.net_timeout)
        return SocketInfo(sock, self.pool_id, hostname) 
Example #11
Source File: XAsyncSockets.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def _doSSLHandshake(self) :
        count = 0
        while count < 10 :
            try :
                self._socket.do_handshake()
                break
            except ssl.SSLError as sslErr :
                count += 1
                if sslErr.args[0] == ssl.SSL_ERROR_WANT_READ :
                    select([self._socket], [], [], 1)
                elif sslErr.args[0] == ssl.SSL_ERROR_WANT_WRITE :
                    select([], [self._socket], [], 1)
                else :
                    raise XAsyncTCPClientException('SSL : Bad handshake : %s' % sslErr)
            except Exception as ex :
                raise XAsyncTCPClientException('SSL : Handshake error : %s' % ex)

    # ------------------------------------------------------------------------ 
Example #12
Source File: pyopenssl.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
                return b""
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b""
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            if not util.wait_for_read(self.socket, self.socket.gettimeout()):
                raise timeout("The read operation timed out")
            else:
                return self.recv(*args, **kwargs)

        # TLS 1.3 post-handshake authentication
        except OpenSSL.SSL.Error as e:
            raise ssl.SSLError("read error: %r" % e)
        else:
            return data 
Example #13
Source File: securetransport.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def version(self):
        protocol = Security.SSLProtocol()
        result = Security.SSLGetNegotiatedProtocolVersion(
            self.context, ctypes.byref(protocol)
        )
        _assert_no_error(result)
        if protocol.value == SecurityConst.kTLSProtocol13:
            raise ssl.SSLError("SecureTransport does not support TLS 1.3")
        elif protocol.value == SecurityConst.kTLSProtocol12:
            return "TLSv1.2"
        elif protocol.value == SecurityConst.kTLSProtocol11:
            return "TLSv1.1"
        elif protocol.value == SecurityConst.kTLSProtocol1:
            return "TLSv1"
        elif protocol.value == SecurityConst.kSSLProtocol3:
            return "SSLv3"
        elif protocol.value == SecurityConst.kSSLProtocol2:
            return "SSLv2"
        else:
            raise ssl.SSLError("Unknown TLS version: %r" % protocol) 
Example #14
Source File: httputil.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_ssl_certificate(self, binary_form=False):
        """Returns the client's SSL certificate, if any.

        To use client certificates, the HTTPServer's
        `ssl.SSLContext.verify_mode` field must be set, e.g.::

            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain("foo.crt", "foo.key")
            ssl_ctx.load_verify_locations("cacerts.pem")
            ssl_ctx.verify_mode = ssl.CERT_REQUIRED
            server = HTTPServer(app, ssl_options=ssl_ctx)

        By default, the return value is a dictionary (or None, if no
        client certificate is present).  If ``binary_form`` is true, a
        DER-encoded form of the certificate is returned instead.  See
        SSLSocket.getpeercert() in the standard library for more
        details.
        http://docs.python.org/library/ssl.html#sslsocket-objects
        """
        try:
            return self.connection.stream.socket.getpeercert(
                binary_form=binary_form)
        except SSLError:
            return None 
Example #15
Source File: http.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _send_internal(self, uri, method, headers=None, body=None, proxy_info=None):
        """Do send request to target URL and validate SSL cert by default.
        If validation failed, disable it and try again."""
        try:
            return self._connection.request(
                uri, body=body, method=method, headers=headers
            )
        except SSLHandshakeError:
            _logger.warning(
                "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verification failed. "
                "The certificate of the https server [%s] is not trusted, "
                "this add-on will proceed to connect with this certificate. "
                "You may need to check the certificate and "
                "refer to the documentation and add it to the trust list. %s",
                uri,
                traceback.format_exc()
            )

            self._connection = self._build_http_connection(
                proxy_info=proxy_info,
                disable_ssl_cert_validation=True
            )
            return self._connection.request(
                uri, body=body, method=method, headers=headers
            ) 
Example #16
Source File: low_level.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u"":
        output = u"OSStatus %s" % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #17
Source File: ProxyTool.py    From ProxHTTPSProxyMII with MIT License 6 votes vote down vote up
def handle_one_request(self):
        """Catch more exceptions than default

        Intend to catch exceptions on local side
        Exceptions on remote side should be handled in do_*()
        """
        try:
            BaseHTTPRequestHandler.handle_one_request(self)
            return
        except (ConnectionError, FileNotFoundError) as e:
            logger.warning("%03d " % self.reqNum + Fore.RED + "%s %s", self.server_version, e)
        except (ssl.SSLEOFError, ssl.SSLError) as e:
            if hasattr(self, 'url'):
                # Happens after the tunnel is established
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while operating on established local SSL tunnel for [%s]' % (e, self.url))
            else:
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while trying to establish local SSL tunnel for [%s]' % (e, self.path))
        self.close_connection = 1 
Example #18
Source File: securetransport.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def version(self):
        protocol = Security.SSLProtocol()
        result = Security.SSLGetNegotiatedProtocolVersion(
            self.context, ctypes.byref(protocol)
        )
        _assert_no_error(result)
        if protocol.value == SecurityConst.kTLSProtocol13:
            raise ssl.SSLError("SecureTransport does not support TLS 1.3")
        elif protocol.value == SecurityConst.kTLSProtocol12:
            return "TLSv1.2"
        elif protocol.value == SecurityConst.kTLSProtocol11:
            return "TLSv1.1"
        elif protocol.value == SecurityConst.kTLSProtocol1:
            return "TLSv1"
        elif protocol.value == SecurityConst.kSSLProtocol3:
            return "SSLv3"
        elif protocol.value == SecurityConst.kSSLProtocol2:
            return "SSLv2"
        else:
            raise ssl.SSLError("Unknown TLS version: %r" % protocol) 
Example #19
Source File: pyopenssl.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
                return b""
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b""
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            if not util.wait_for_read(self.socket, self.socket.gettimeout()):
                raise timeout("The read operation timed out")
            else:
                return self.recv(*args, **kwargs)

        # TLS 1.3 post-handshake authentication
        except OpenSSL.SSL.Error as e:
            raise ssl.SSLError("read error: %r" % e)
        else:
            return data 
Example #20
Source File: pyopenssl.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            if not util.wait_for_read(self.socket, self.socket.gettimeout()):
                raise timeout("The read operation timed out")
            else:
                return self.recv_into(*args, **kwargs)

        # TLS 1.3 post-handshake authentication
        except OpenSSL.SSL.Error as e:
            raise ssl.SSLError("read error: %r" % e) 
Example #21
Source File: low_level.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u'':
        output = u'OSStatus %s' % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #22
Source File: httputil.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_ssl_certificate(self, binary_form=False):
        """Returns the client's SSL certificate, if any.

        To use client certificates, the HTTPServer's
        `ssl.SSLContext.verify_mode` field must be set, e.g.::

            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain("foo.crt", "foo.key")
            ssl_ctx.load_verify_locations("cacerts.pem")
            ssl_ctx.verify_mode = ssl.CERT_REQUIRED
            server = HTTPServer(app, ssl_options=ssl_ctx)

        By default, the return value is a dictionary (or None, if no
        client certificate is present).  If ``binary_form`` is true, a
        DER-encoded form of the certificate is returned instead.  See
        SSLSocket.getpeercert() in the standard library for more
        details.
        http://docs.python.org/library/ssl.html#sslsocket-objects
        """
        try:
            return self.connection.stream.socket.getpeercert(
                binary_form=binary_form)
        except SSLError:
            return None 
Example #23
Source File: low_level.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u'':
        output = u'OSStatus %s' % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #24
Source File: low_level.py    From core with MIT License 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u'':
        output = u'OSStatus %s' % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #25
Source File: low_level.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def _assert_no_error(error, exception_class=None):
    """
    Checks the return code and throws an exception if there is an error to
    report
    """
    if error == 0:
        return

    cf_error_string = Security.SecCopyErrorMessageString(error, None)
    output = _cf_string_to_unicode(cf_error_string)
    CoreFoundation.CFRelease(cf_error_string)

    if output is None or output == u'':
        output = u'OSStatus %s' % error

    if exception_class is None:
        exception_class = ssl.SSLError

    raise exception_class(output) 
Example #26
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_ssl_context_handshake_fail(self):
        with ExpectLog(gen_log, "SSL Error|Uncaught exception"):
            ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            ctx.verify_mode = ssl.CERT_REQUIRED
            resp = self.fetch("/hello", ssl_options=ctx)
        self.assertRaises(ssl.SSLError, resp.rethrow) 
Example #27
Source File: iostream_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_check_hostname(self):
        # Test that server_hostname parameter to start_tls is being used.
        # The check_hostname functionality is only available in python 2.7 and
        # up and in python 3.4 and up.
        server_future = self.server_start_tls(_server_ssl_options())
        client_future = self.client_start_tls(
            ssl.create_default_context(),
            server_hostname=b'127.0.0.1')
        with ExpectLog(gen_log, "SSL Error"):
            with self.assertRaises(ssl.SSLError):
                # The client fails to connect with an SSL error.
                yield client_future
        with self.assertRaises(Exception):
            # The server fails to connect, but the exact error is unspecified.
            yield server_future 
Example #28
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_error_logging(self):
        # No stack traces are logged for SSL errors (in this case,
        # failure to validate the testing self-signed cert).
        # The SSLError is exposed through ssl.SSLError.
        with ExpectLog(gen_log, '.*') as expect_log:
            response = self.fetch("/", validate_cert=True)
            self.assertEqual(response.code, 599)
            self.assertIsInstance(response.error, ssl.SSLError)
        self.assertFalse(expect_log.logged_stack) 
Example #29
Source File: low_level.py    From core with MIT License 5 votes vote down vote up
def _cert_array_from_pem(pem_bundle):
    """
    Given a bundle of certs in PEM format, turns them into a CFArray of certs
    that can be used to validate a cert chain.
    """
    der_certs = [
        base64.b64decode(match.group(1))
        for match in _PEM_CERTS_RE.finditer(pem_bundle)
    ]
    if not der_certs:
        raise ssl.SSLError("No root certificates specified")

    cert_array = CoreFoundation.CFArrayCreateMutable(
        CoreFoundation.kCFAllocatorDefault,
        0,
        ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)
    )
    if not cert_array:
        raise ssl.SSLError("Unable to allocate memory!")

    try:
        for der_bytes in der_certs:
            certdata = _cf_data_from_bytes(der_bytes)
            if not certdata:
                raise ssl.SSLError("Unable to allocate memory!")
            cert = Security.SecCertificateCreateWithData(
                CoreFoundation.kCFAllocatorDefault, certdata
            )
            CoreFoundation.CFRelease(certdata)
            if not cert:
                raise ssl.SSLError("Unable to build cert object!")

            CoreFoundation.CFArrayAppendValue(cert_array, cert)
            CoreFoundation.CFRelease(cert)
    except Exception:
        # We need to free the array before the exception bubbles further.
        # We only want to do that if an error occurs: otherwise, the caller
        # should free.
        CoreFoundation.CFRelease(cert_array)

    return cert_array 
Example #30
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_ssl_options_handshake_fail(self):
        with ExpectLog(gen_log, "SSL Error|Uncaught exception",
                       required=False):
            resp = self.fetch(
                "/hello", ssl_options=dict(cert_reqs=ssl.CERT_REQUIRED))
        self.assertRaises(ssl.SSLError, resp.rethrow)