GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — SNOW-29826: better invalid SSL certificate error message · byule/snowflake-connector-python@1e8206d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • chunk_downloader.py
  • connection.py
  • cursor.py
  • errorcode.py
  • errors.py
  • network.py
  • ssl_wrap_socket.py
  • test
    • test_unit_auth_webbrowser.py
    • test_unit_renew_session.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎chunk_downloader.py‎

Copy file name to clipboardExpand all lines: chunk_downloader.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def _pre_init(self, chunks, connection, cursor, qrmk, chunk_headers,
6969
self._chunk_size)
7070

7171
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,
7373
chunk[u'rowCount'])
7474
self._chunks[idx] = SnowflakeChunk(
7575
url=chunk[u'url'],
@@ -101,7 +101,7 @@ def __init__(self, chunks, connection, cursor, qrmk, chunk_headers,
101101
prefetch_slots=prefetch_slots,
102102
prefetch_threads=prefetch_threads,
103103
use_ijson=use_ijson)
104-
logger.info('Chunk Downloader in memory')
104+
logger.debug('Chunk Downloader in memory')
105105
for idx in range(self._num_chunks_to_prefetch):
106106
self._pool.apply_async(self._download_chunk, [idx])
107107
self._chunk_locks[idx] = Condition()
Collapse file

‎connection.py‎

Copy file name to clipboardExpand all lines: connection.py
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
SnowflakeConverter if not PY_ISSUE_23517 else SnowflakeConverterIssue23517,
7272
u'chunk_downloader_class': SnowflakeChunkDownloader, # snowflake internal
7373
u'validate_default_parameters': False, # snowflake
74+
u'probe_connection': False, # snowflake
7475
}
7576

7677
APPLICATION_RE = re.compile(r'[\w\d_]+')
Collapse file

‎cursor.py‎

Copy file name to clipboardExpand all lines: cursor.py
+3-4Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ def abort_exit(*_):
341341
try:
342342
signal.signal(signal.SIGINT, abort_exit)
343343
except ValueError:
344-
logger.info(
344+
logger.debug(
345345
u'Failed to set SIGINT handler. '
346346
u'Not in main thread. Ignored...')
347347
ret = {u'data': {}}
@@ -358,7 +358,7 @@ def abort_exit(*_):
358358
try:
359359
signal.signal(signal.SIGINT, original_sigint)
360360
except ValueError:
361-
logger.info(
361+
logger.debug(
362362
u'Failed to reset SIGINT handler. Not in main '
363363
u'thread. Ignored...')
364364
if self._timebomb is not None:
@@ -457,7 +457,7 @@ def execute(self, command, params=None, timeout=None,
457457
self._sqlstate = ret[u'data'][
458458
u'sqlState'] if u'data' in ret and u'sqlState' in ret[
459459
u'data'] else None
460-
logger.debug(u'sfqid=%s', self._sfqid)
460+
logger.debug('sfqid: %s', self.sfqid)
461461

462462
if ret[u'success']:
463463
logger.debug(u'SUCCESS')
@@ -500,7 +500,6 @@ def execute(self, command, params=None, timeout=None,
500500
else:
501501
self._total_rowcount = ret[u'data'][
502502
u'total'] if u'data' in ret and u'total' in ret[u'data'] else -1
503-
logger.info(u'failed')
504503
logger.debug(ret)
505504
err = ret[u'message']
506505
code = ret.get(u'code', -1)
Collapse file

‎errorcode.py‎

Copy file name to clipboardExpand all lines: errorcode.py
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
ER_INCORRECT_DESTINATION = 250008
1717
ER_UNABLE_TO_OPEN_BROWSER = 250009
1818
ER_UNABLE_TO_START_WEBSERVER = 250010
19+
ER_INVALID_CERTIFICATE = 250011
1920

2021
# connection
2122
ER_NO_ACCOUNT_NAME = 251001
Collapse file

‎errors.py‎

Copy file name to clipboardExpand all lines: errors.py
+15-2Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def __init__(self, msg=None, errno=None, sqlstate=None, sfqid=None,
3131
if self.errno != -1 and not done_format_msg:
3232
if self.sqlstate != "n/a":
3333
if logger.getEffectiveLevel() in (logging.INFO,
34-
logging.DEBUG):
34+
logging.DEBUG):
3535
self.msg = u'{errno:06d} ({sqlstate}): {sfqid}: {msg}'.format(
3636
errno=self.errno, msg=self.msg,
3737
sqlstate=self.sqlstate,
@@ -43,7 +43,7 @@ def __init__(self, msg=None, errno=None, sqlstate=None, sfqid=None,
4343
msg=self.msg)
4444
else:
4545
if logger.getEffectiveLevel() in (logging.INFO,
46-
logging.DEBUG):
46+
logging.DEBUG):
4747
self.msg = u'{errno:06d}: {sfqid}: {msg}'.format(
4848
errno=self.errno, msg=self.msg,
4949
sfqid=self.sfqid)
@@ -237,3 +237,16 @@ def __init__(self, **kwargs):
237237
errno=kwargs.get('errno'),
238238
sqlstate=kwargs.get('sqlstate'),
239239
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

‎network.py‎

Copy file name to clipboardExpand all lines: network.py
+55-12Lines changed: 55 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import logging
1212
import platform
1313
import random
14+
import ssl
1415
import sys
1516
import time
1617
import uuid
@@ -25,6 +26,8 @@
2526
ConnectionError, ConnectTimeout, ReadTimeout, SSLError)
2627
from botocore.vendored.requests.packages.urllib3.exceptions import (
2728
ProtocolError, ReadTimeoutError)
29+
from botocore.vendored.requests.packages.urllib3.exceptions \
30+
import SSLError as urllib3_SSLError
2831

2932
from . import proxy
3033
from . import ssl_wrap_socket
@@ -36,16 +39,18 @@
3639
from .compat import proxy_bypass
3740
from .errorcode import (ER_FAILED_TO_CONNECT_TO_DB, ER_CONNECTION_IS_CLOSED,
3841
ER_FAILED_TO_REQUEST, ER_FAILED_TO_RENEW_SESSION,
39-
ER_FAILED_TO_SERVER)
42+
ER_FAILED_TO_SERVER, ER_INVALID_CERTIFICATE)
4043
from .errors import (Error, OperationalError, DatabaseError, ProgrammingError,
4144
GatewayTimeoutError, ServiceUnavailableError,
4245
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)
4449
from .gzip_decoder import decompress_raw_data
4550
from .sqlstate import (SQLSTATE_CONNECTION_NOT_EXISTS,
4651
SQLSTATE_CONNECTION_WAS_NOT_ESTABLISHED,
4752
SQLSTATE_CONNECTION_REJECTED)
48-
from .ssl_wrap_socket import set_proxies
53+
from .ssl_wrap_socket import (set_proxies, probe_connection)
4954
from .util_text import split_rows_from_stream
5055
from .version import VERSION
5156

@@ -56,6 +61,9 @@
5661
"""
5762
ssl_wrap_socket.inject_into_urllib3()
5863

64+
# known applications
65+
APPLICATION_SNOWSQL = u'SnowSQL'
66+
5967
# requests parameters
6068
REQUESTS_RETRY = 1 # requests library builtin retry
6169
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,
354362
port=self._port,
355363
url=url,
356364
)
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+
357373
ret = self.fetch(u'post', full_url, headers, data=body,
358374
timeout=timeout, token=token,
359375
no_retry=no_retry)
@@ -462,18 +478,12 @@ def _request_exec_wrapper(
462478
if retry_ctx.timeout is not None:
463479
retry_ctx.timeout -= int(time.time() - start_request_thread)
464480
if retry_ctx.timeout <= 0:
481+
logger.error(cause)
465482
if isinstance(cause, Error):
466-
logger.error(cause)
467483
Error.errorhandler_wrapper(conn, None, cause)
468484
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)
477487
return {} # required for tests
478488
sleeping_time = retry_ctx.next_sleep()
479489
logger.debug(
@@ -496,6 +506,39 @@ def _request_exec_wrapper(
496506
logger.debug("Ignored error", exc_info=True)
497507
return {}
498508

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+
499542
def _handle_unknown_error(
500543
self, method, full_url, headers, data, conn, proxies):
501544
"""
Collapse file

‎ssl_wrap_socket.py‎

Copy file name to clipboardExpand all lines: ssl_wrap_socket.py
+31-1Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import logging
2222
import ssl
2323
import sys
24-
from socket import timeout, error as SocketError
24+
from socket import socket, timeout, error as SocketError
2525

2626
import OpenSSL.SSL
2727
from botocore.vendored.requests.packages.urllib3 import connection \
@@ -32,6 +32,7 @@
3232
from cryptography.hazmat.backends.openssl import backend as openssl_backend
3333
from cryptography.hazmat.backends.openssl.x509 import _Certificate
3434

35+
from .compat import urlsplit
3536
from .errorcode import (ER_SERVER_CERTIFICATE_REVOKED)
3637
from .errors import (OperationalError)
3738
from .ocsp_pyopenssl import SnowflakeOCSP
@@ -395,3 +396,32 @@ def ssl_wrap_socket_with_ocsp(
395396
u'STATUS WILL NOT BE CHECKED.')
396397

397398
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

‎test/test_unit_auth_webbrowser.py‎

Copy file name to clipboardExpand all lines: test/test_unit_auth_webbrowser.py
+18-33Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@
1414
else:
1515
from unittest.mock import MagicMock, Mock, PropertyMock
1616

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+
1725

1826
def mock_webserver(target_instance, application, port):
1927
_ = application
@@ -25,16 +33,9 @@ def test_auth_webbrowser():
2533
"""
2634
Authentication by WebBrowser positive test case
2735
"""
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'
3436
ref_token = "MOCK_TOKEN"
3537

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)
3839

3940
# mock webbrowser
4041
mock_webbrowser = MagicMock()
@@ -53,30 +54,22 @@ def test_auth_webbrowser():
5354
mock_socket = Mock(return_value=mock_socket_instance)
5455

5556
auth = AuthByWebBrowser(
56-
rest, application,
57+
rest, APPLICATION,
5758
webbrowser_pkg=mock_webbrowser, socket_pkg=mock_socket)
58-
auth.authenticate(authenticator, account, user, password)
59+
auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD)
5960
assert not rest._connection.errorhandler.called # no error
6061
assert auth.assertion_content == ref_token
6162
body = {u'data': {}}
6263
auth.update_body(body)
6364
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
6566

6667

6768
def test_auth_webbrowser_fail_webbrowser():
6869
"""
6970
Authentication by WebBrowser. fail to start web browser
7071
"""
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)
8073

8174
# mock webbrowser
8275
mock_webbrowser = MagicMock()
@@ -95,9 +88,9 @@ def test_auth_webbrowser_fail_webbrowser():
9588
mock_socket = Mock(return_value=mock_socket_instance)
9689

9790
auth = AuthByWebBrowser(
98-
rest, application, webbrowser_pkg=mock_webbrowser,
91+
rest, APPLICATION, webbrowser_pkg=mock_webbrowser,
9992
socket_pkg=mock_socket)
100-
auth.authenticate(authenticator, account, user, password)
93+
auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD)
10194
assert rest._connection.errorhandler.called # an error
10295
assert auth.assertion_content is None
10396

@@ -106,15 +99,7 @@ def test_auth_webbrowser_fail_webserver():
10699
"""
107100
Authentication by WebBrowser. fail to start web browser
108101
"""
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)
118103

119104
# mock webbrowser
120105
mock_webbrowser = MagicMock()
@@ -134,9 +119,9 @@ def test_auth_webbrowser_fail_webserver():
134119

135120
# case 1: invalid HTTP request
136121
auth = AuthByWebBrowser(
137-
rest, application, webbrowser_pkg=mock_webbrowser,
122+
rest, APPLICATION, webbrowser_pkg=mock_webbrowser,
138123
socket_pkg=mock_socket)
139-
auth.authenticate(authenticator, account, user, password)
124+
auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD)
140125
assert rest._connection.errorhandler.called # an error
141126
assert auth.assertion_content is None
142127

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.