GeezerVison is showing github.com — SNOW-29826: better invalid SSL certificate error message · byule/snowflake-connector-python@1e8206d
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: chunk_downloader.py +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -69,7 +69,7 @@ def _pre_init(self, chunks, connection, cursor, qrmk, chunk_headers, | 69 | 69 | self._chunk_size) | 70 | 70 |
| 71 | 71 | for idx, chunk in enumerate(chunks): | 72 | | - logger.info(u"queued chunk %d: rowCount=%s", idx, | | 72 | + logger.debug(u"queued chunk %d: rowCount=%s", idx, | 73 | 73 | chunk[u'rowCount']) | 74 | 74 | self._chunks[idx] = SnowflakeChunk( | 75 | 75 | url=chunk[u'url'], | @@ -101,7 +101,7 @@ def __init__(self, chunks, connection, cursor, qrmk, chunk_headers, | 101 | 101 | prefetch_slots=prefetch_slots, | 102 | 102 | prefetch_threads=prefetch_threads, | 103 | 103 | use_ijson=use_ijson) | 104 | | - logger.info('Chunk Downloader in memory') | | 104 | + logger.debug('Chunk Downloader in memory') | 105 | 105 | for idx in range(self._num_chunks_to_prefetch): | 106 | 106 | self._pool.apply_async(self._download_chunk, [idx]) | 107 | 107 | self._chunk_locks[idx] = Condition() | |
Collapse file Copy file name to clipboardExpand all lines: connection.py +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 71 | 71 | SnowflakeConverter if not PY_ISSUE_23517 else SnowflakeConverterIssue23517, | 72 | 72 | u'chunk_downloader_class': SnowflakeChunkDownloader, # snowflake internal | 73 | 73 | u'validate_default_parameters': False, # snowflake | | 74 | + u'probe_connection': False, # snowflake | 74 | 75 | } | 75 | 76 |
| 76 | 77 | APPLICATION_RE = re.compile(r'[\w\d_]+') | |
Collapse file Copy file name to clipboardExpand all lines: cursor.py +3-4Lines changed: 3 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -341,7 +341,7 @@ def abort_exit(*_): | 341 | 341 | try: | 342 | 342 | signal.signal(signal.SIGINT, abort_exit) | 343 | 343 | except ValueError: | 344 | | - logger.info( | | 344 | + logger.debug( | 345 | 345 | u'Failed to set SIGINT handler. ' | 346 | 346 | u'Not in main thread. Ignored...') | 347 | 347 | ret = {u'data': {}} | @@ -358,7 +358,7 @@ def abort_exit(*_): | 358 | 358 | try: | 359 | 359 | signal.signal(signal.SIGINT, original_sigint) | 360 | 360 | except ValueError: | 361 | | - logger.info( | | 361 | + logger.debug( | 362 | 362 | u'Failed to reset SIGINT handler. Not in main ' | 363 | 363 | u'thread. Ignored...') | 364 | 364 | if self._timebomb is not None: | @@ -457,7 +457,7 @@ def execute(self, command, params=None, timeout=None, | 457 | 457 | self._sqlstate = ret[u'data'][ | 458 | 458 | u'sqlState'] if u'data' in ret and u'sqlState' in ret[ | 459 | 459 | u'data'] else None | 460 | | - logger.debug(u'sfqid=%s', self._sfqid) | | 460 | + logger.debug('sfqid: %s', self.sfqid) | 461 | 461 |
| 462 | 462 | if ret[u'success']: | 463 | 463 | logger.debug(u'SUCCESS') | @@ -500,7 +500,6 @@ def execute(self, command, params=None, timeout=None, | 500 | 500 | else: | 501 | 501 | self._total_rowcount = ret[u'data'][ | 502 | 502 | u'total'] if u'data' in ret and u'total' in ret[u'data'] else -1 | 503 | | - logger.info(u'failed') | 504 | 503 | logger.debug(ret) | 505 | 504 | err = ret[u'message'] | 506 | 505 | code = ret.get(u'code', -1) | |
Collapse file Copy file name to clipboardExpand all lines: errorcode.py +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 16 | 16 | ER_INCORRECT_DESTINATION = 250008 | 17 | 17 | ER_UNABLE_TO_OPEN_BROWSER = 250009 | 18 | 18 | ER_UNABLE_TO_START_WEBSERVER = 250010 | | 19 | +ER_INVALID_CERTIFICATE = 250011 | 19 | 20 |
| 20 | 21 | # connection | 21 | 22 | ER_NO_ACCOUNT_NAME = 251001 | |
Collapse file Copy file name to clipboardExpand all lines: errors.py +15-2Lines changed: 15 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -31,7 +31,7 @@ def __init__(self, msg=None, errno=None, sqlstate=None, sfqid=None, | 31 | 31 | if self.errno != -1 and not done_format_msg: | 32 | 32 | if self.sqlstate != "n/a": | 33 | 33 | if logger.getEffectiveLevel() in (logging.INFO, | 34 | | - logging.DEBUG): | | 34 | + logging.DEBUG): | 35 | 35 | self.msg = u'{errno:06d} ({sqlstate}): {sfqid}: {msg}'.format( | 36 | 36 | errno=self.errno, msg=self.msg, | 37 | 37 | sqlstate=self.sqlstate, | @@ -43,7 +43,7 @@ def __init__(self, msg=None, errno=None, sqlstate=None, sfqid=None, | 43 | 43 | msg=self.msg) | 44 | 44 | else: | 45 | 45 | if logger.getEffectiveLevel() in (logging.INFO, | 46 | | - logging.DEBUG): | | 46 | + logging.DEBUG): | 47 | 47 | self.msg = u'{errno:06d}: {sfqid}: {msg}'.format( | 48 | 48 | errno=self.errno, msg=self.msg, | 49 | 49 | sfqid=self.sfqid) | @@ -237,3 +237,16 @@ def __init__(self, **kwargs): | 237 | 237 | errno=kwargs.get('errno'), | 238 | 238 | sqlstate=kwargs.get('sqlstate'), | 239 | 239 | sfqid=kwargs.get('sfqid')) | | 240 | + | | 241 | + | | 242 | +ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE = ( | | 243 | + u"Failed to validate SSL certificate. The potential cause is you are " | | 244 | + u"behind a SSL proxy that doesn't bypass the certificate. Call " | | 245 | + u"snowflake.connector.connect() method with probe_connection option to " | | 246 | + u"print out the certificate chain. URL: {}") | | 247 | + | | 248 | +ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE_SNOWSQL = ( | | 249 | + u"Failed to validate SSL certificate. The potential cause is you are " | | 250 | + u"behind a SSL proxy that doesn't bypass the certificate. Specify " | | 251 | + u"--probe-connection option to print out the certificate chain. " | | 252 | + u"URL: {}") |
Collapse file Copy file name to clipboardExpand all lines: network.py +55-12Lines changed: 55 additions & 12 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 11 | 11 | import logging | 12 | 12 | import platform | 13 | 13 | import random | | 14 | +import ssl | 14 | 15 | import sys | 15 | 16 | import time | 16 | 17 | import uuid | | 25 | 26 | ConnectionError, ConnectTimeout, ReadTimeout, SSLError) | 26 | 27 | from botocore.vendored.requests.packages.urllib3.exceptions import ( | 27 | 28 | ProtocolError, ReadTimeoutError) | | 29 | +from botocore.vendored.requests.packages.urllib3.exceptions \ | | 30 | + import SSLError as urllib3_SSLError | 28 | 31 |
| 29 | 32 | from . import proxy | 30 | 33 | from . import ssl_wrap_socket | | 36 | 39 | from .compat import proxy_bypass | 37 | 40 | from .errorcode import (ER_FAILED_TO_CONNECT_TO_DB, ER_CONNECTION_IS_CLOSED, | 38 | 41 | ER_FAILED_TO_REQUEST, ER_FAILED_TO_RENEW_SESSION, | 39 | | - ER_FAILED_TO_SERVER) | | 42 | + ER_FAILED_TO_SERVER, ER_INVALID_CERTIFICATE) | 40 | 43 | from .errors import (Error, OperationalError, DatabaseError, ProgrammingError, | 41 | 44 | GatewayTimeoutError, ServiceUnavailableError, | 42 | 45 | InterfaceError, InternalServerError, ForbiddenError, | 43 | | - BadGatewayError, BadRequest) | | 46 | + BadGatewayError, BadRequest, | | 47 | + ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE, | | 48 | + ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE_SNOWSQL) | 44 | 49 | from .gzip_decoder import decompress_raw_data | 45 | 50 | from .sqlstate import (SQLSTATE_CONNECTION_NOT_EXISTS, | 46 | 51 | SQLSTATE_CONNECTION_WAS_NOT_ESTABLISHED, | 47 | 52 | SQLSTATE_CONNECTION_REJECTED) | 48 | | -from .ssl_wrap_socket import set_proxies | | 53 | +from .ssl_wrap_socket import (set_proxies, probe_connection) | 49 | 54 | from .util_text import split_rows_from_stream | 50 | 55 | from .version import VERSION | 51 | 56 |
| | 56 | 61 | """ | 57 | 62 | ssl_wrap_socket.inject_into_urllib3() | 58 | 63 |
| | 64 | +# known applications | | 65 | +APPLICATION_SNOWSQL = u'SnowSQL' | | 66 | + | 59 | 67 | # requests parameters | 60 | 68 | REQUESTS_RETRY = 1 # requests library builtin retry | 61 | 69 | DEFAULT_SOCKET_CONNECT_TIMEOUT = 1 * 60 # don't reduce less than 45 seconds | @@ -354,6 +362,14 @@ def _post_request(self, url, headers, body, token=None, | 354 | 362 | port=self._port, | 355 | 363 | url=url, | 356 | 364 | ) | | 365 | + if self._connection._probe_connection: | | 366 | + from pprint import pprint | | 367 | + ret = probe_connection(full_url) | | 368 | + ret['url'] = full_url | | 369 | + print(u"Contact to the support if the following certificates " | | 370 | + u"don't look valid:") | | 371 | + pprint(ret) | | 372 | + | 357 | 373 | ret = self.fetch(u'post', full_url, headers, data=body, | 358 | 374 | timeout=timeout, token=token, | 359 | 375 | no_retry=no_retry) | @@ -462,18 +478,12 @@ def _request_exec_wrapper( | 462 | 478 | if retry_ctx.timeout is not None: | 463 | 479 | retry_ctx.timeout -= int(time.time() - start_request_thread) | 464 | 480 | if retry_ctx.timeout <= 0: | | 481 | + logger.error(cause) | 465 | 482 | if isinstance(cause, Error): | 466 | | - logger.error(cause) | 467 | 483 | Error.errorhandler_wrapper(conn, None, cause) | 468 | 484 | else: | 469 | | - logger.error(cause) | 470 | | - Error.errorhandler_wrapper( | 471 | | - conn, None, OperationalError, | 472 | | - { | 473 | | - u'msg': u'Failed to execute request: {0}'.format( | 474 | | - cause), | 475 | | - u'errno': ER_FAILED_TO_REQUEST, | 476 | | - }) | | 485 | + self.handle_invalid_certificate_error( | | 486 | + conn, full_url, cause) | 477 | 487 | return {} # required for tests | 478 | 488 | sleeping_time = retry_ctx.next_sleep() | 479 | 489 | logger.debug( | @@ -496,6 +506,39 @@ def _request_exec_wrapper( | 496 | 506 | logger.debug("Ignored error", exc_info=True) | 497 | 507 | return {} | 498 | 508 |
| | 509 | + def handle_invalid_certificate_error(self, conn, full_url, cause): | | 510 | + # checking if the cause is SSL certificate error | | 511 | + if isinstance(cause, SSLError): | | 512 | + if isinstance(cause.args[0], urllib3_SSLError): | | 513 | + if isinstance( | | 514 | + cause.args[0].args[0], ssl.SSLError): | | 515 | + err = cause.args[0].args[0].args[0] | | 516 | + if u'bad handshake' in err and \ | | 517 | + u'certificate verify failed' in err: | | 518 | + if conn.application == APPLICATION_SNOWSQL: | | 519 | + # SnowSQL has an option to probe connection. | | 520 | + msg = \ | | 521 | + ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE_SNOWSQL | | 522 | + else: | | 523 | + msg = ER_MSG_FAILED_TO_VALIDATE_SSL_CERTIFICATE | | 524 | + Error.errorhandler_wrapper( | | 525 | + conn, None, OperationalError, | | 526 | + { | | 527 | + u'errno': ER_INVALID_CERTIFICATE, | | 528 | + u'msg': msg.format(full_url), | | 529 | + u'error': ER_FAILED_TO_REQUEST, | | 530 | + } | | 531 | + ) | | 532 | + return # required for tests | | 533 | + # all other errors raise exception | | 534 | + Error.errorhandler_wrapper( | | 535 | + conn, None, OperationalError, | | 536 | + { | | 537 | + u'msg': u'Failed to execute request: {0}'.format( | | 538 | + cause), | | 539 | + u'errno': ER_FAILED_TO_REQUEST, | | 540 | + }) | | 541 | + | 499 | 542 | def _handle_unknown_error( | 500 | 543 | self, method, full_url, headers, data, conn, proxies): | 501 | 544 | """ | |
Collapse file Copy file name to clipboardExpand all lines: ssl_wrap_socket.py +31-1Lines changed: 31 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 21 | 21 | import logging | 22 | 22 | import ssl | 23 | 23 | import sys | 24 | | -from socket import timeout, error as SocketError | | 24 | +from socket import socket, timeout, error as SocketError | 25 | 25 |
| 26 | 26 | import OpenSSL.SSL | 27 | 27 | from botocore.vendored.requests.packages.urllib3 import connection \ | | 32 | 32 | from cryptography.hazmat.backends.openssl import backend as openssl_backend | 33 | 33 | from cryptography.hazmat.backends.openssl.x509 import _Certificate | 34 | 34 |
| | 35 | +from .compat import urlsplit | 35 | 36 | from .errorcode import (ER_SERVER_CERTIFICATE_REVOKED) | 36 | 37 | from .errors import (OperationalError) | 37 | 38 | from .ocsp_pyopenssl import SnowflakeOCSP | @@ -395,3 +396,32 @@ def ssl_wrap_socket_with_ocsp( | 395 | 396 | u'STATUS WILL NOT BE CHECKED.') | 396 | 397 |
| 397 | 398 | return ret | | 399 | + | | 400 | + | | 401 | +def _openssl_connect(hostname, port=443): | | 402 | + """ | | 403 | + OpenSSL connection without validating certificates. This is used to diagnose | | 404 | + SSL issues. | | 405 | + """ | | 406 | + client = socket() | | 407 | + client.connect((hostname, port)) | | 408 | + client_ssl = OpenSSL.SSL.Connection( | | 409 | + OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD), client) | | 410 | + client_ssl.set_connect_state() | | 411 | + client_ssl.set_tlsext_host_name(hostname.encode('utf-8')) | | 412 | + client_ssl.do_handshake() | | 413 | + return client_ssl | | 414 | + | | 415 | + | | 416 | +def probe_connection(url): | | 417 | + certificates = [] | | 418 | + parsed_url = urlsplit(url) | | 419 | + connection = _openssl_connect(parsed_url.hostname, parsed_url.port) | | 420 | + for cert in connection.get_peer_cert_chain(): | | 421 | + certificates.append( | | 422 | + {'hash': cert.get_subject().hash(), | | 423 | + 'name': cert.get_subject(), | | 424 | + 'issuer': cert.get_issuer(), | | 425 | + 'serial_number': cert.get_serial_number(), | | 426 | + }) | | 427 | + return {'certificates': certificates} |
Collapse file Copy file name to clipboardExpand all lines: test/test_unit_auth_webbrowser.py +18-33Lines changed: 18 additions & 33 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 14 | 14 | else: | 15 | 15 | from unittest.mock import MagicMock, Mock, PropertyMock | 16 | 16 |
| | 17 | +AUTHENTICATOR = 'https://testsso.snowflake.net/' | | 18 | +APPLICATION = 'testapplication' | | 19 | +ACCOUNT = 'testaccount' | | 20 | +USER = 'testuser' | | 21 | +PASSWORD = 'testpassword' | | 22 | +REF_PROOF_KEY = 'MOCK_PROOF_KEY' | | 23 | +REF_SSO_URL = 'https://testsso.snowflake.net/sso' | | 24 | + | 17 | 25 |
| 18 | 26 | def mock_webserver(target_instance, application, port): | 19 | 27 | _ = application | @@ -25,16 +33,9 @@ def test_auth_webbrowser(): | 25 | 33 | """ | 26 | 34 | Authentication by WebBrowser positive test case | 27 | 35 | """ | 28 | | - authenticator = 'https://testsso.snowflake.net/' | 29 | | - application = 'testapplication' | 30 | | - account = 'testaccount' | 31 | | - user = 'testuser' | 32 | | - password = 'testpassword' | 33 | | - ref_proof_key = 'MOCK_PROOF_KEY' | 34 | 36 | ref_token = "MOCK_TOKEN" | 35 | 37 |
| 36 | | - ref_sso_url = 'https://testsso.snowflake.net/sso' | 37 | | - rest = _init_rest(ref_sso_url, ref_proof_key) | | 38 | + rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY) | 38 | 39 |
| 39 | 40 | # mock webbrowser | 40 | 41 | mock_webbrowser = MagicMock() | @@ -53,30 +54,22 @@ def test_auth_webbrowser(): | 53 | 54 | mock_socket = Mock(return_value=mock_socket_instance) | 54 | 55 |
| 55 | 56 | auth = AuthByWebBrowser( | 56 | | - rest, application, | | 57 | + rest, APPLICATION, | 57 | 58 | webbrowser_pkg=mock_webbrowser, socket_pkg=mock_socket) | 58 | | - auth.authenticate(authenticator, account, user, password) | | 59 | + auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD) | 59 | 60 | assert not rest._connection.errorhandler.called # no error | 60 | 61 | assert auth.assertion_content == ref_token | 61 | 62 | body = {u'data': {}} | 62 | 63 | auth.update_body(body) | 63 | 64 | assert body[u'data'][u'SAML_RESPONSE'] == ref_token | 64 | | - assert body[u'data'][u'PROOF_KEY'] == ref_proof_key | | 65 | + assert body[u'data'][u'PROOF_KEY'] == REF_PROOF_KEY | 65 | 66 |
| 66 | 67 |
| 67 | 68 | def test_auth_webbrowser_fail_webbrowser(): | 68 | 69 | """ | 69 | 70 | Authentication by WebBrowser. fail to start web browser | 70 | 71 | """ | 71 | | - authenticator = 'https://testsso.snowflake.net/' | 72 | | - application = 'testapplication' | 73 | | - account = 'testaccount' | 74 | | - user = 'testuser' | 75 | | - password = 'testpassword' | 76 | | - ref_proof_key = 'MOCK_PROOF_KEY' | 77 | | - | 78 | | - ref_sso_url = 'https://testsso.snowflake.net/sso' | 79 | | - rest = _init_rest(ref_sso_url, ref_proof_key) | | 72 | + rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY) | 80 | 73 |
| 81 | 74 | # mock webbrowser | 82 | 75 | mock_webbrowser = MagicMock() | @@ -95,9 +88,9 @@ def test_auth_webbrowser_fail_webbrowser(): | 95 | 88 | mock_socket = Mock(return_value=mock_socket_instance) | 96 | 89 |
| 97 | 90 | auth = AuthByWebBrowser( | 98 | | - rest, application, webbrowser_pkg=mock_webbrowser, | | 91 | + rest, APPLICATION, webbrowser_pkg=mock_webbrowser, | 99 | 92 | socket_pkg=mock_socket) | 100 | | - auth.authenticate(authenticator, account, user, password) | | 93 | + auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD) | 101 | 94 | assert rest._connection.errorhandler.called # an error | 102 | 95 | assert auth.assertion_content is None | 103 | 96 |
| @@ -106,15 +99,7 @@ def test_auth_webbrowser_fail_webserver(): | 106 | 99 | """ | 107 | 100 | Authentication by WebBrowser. fail to start web browser | 108 | 101 | """ | 109 | | - authenticator = 'https://testsso.snowflake.net/' | 110 | | - application = 'testapplication' | 111 | | - account = 'testaccount' | 112 | | - user = 'testuser' | 113 | | - password = 'testpassword' | 114 | | - ref_proof_key = 'MOCK_PROOF_KEY' | 115 | | - | 116 | | - ref_sso_url = 'https://testsso.snowflake.net/sso' | 117 | | - rest = _init_rest(ref_sso_url, ref_proof_key) | | 102 | + rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY) | 118 | 103 |
| 119 | 104 | # mock webbrowser | 120 | 105 | mock_webbrowser = MagicMock() | @@ -134,9 +119,9 @@ def test_auth_webbrowser_fail_webserver(): | 134 | 119 |
| 135 | 120 | # case 1: invalid HTTP request | 136 | 121 | auth = AuthByWebBrowser( | 137 | | - rest, application, webbrowser_pkg=mock_webbrowser, | | 122 | + rest, APPLICATION, webbrowser_pkg=mock_webbrowser, | 138 | 123 | socket_pkg=mock_socket) | 139 | | - auth.authenticate(authenticator, account, user, password) | | 124 | + auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD) | 140 | 125 | assert rest._connection.errorhandler.called # an error | 141 | 126 | assert auth.assertion_content is None | 142 | 127 |
| |
|