Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions redshift_connector/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ def get_calling_module() -> str:
# create ssl connection with Redshift CA certificates and check the hostname
if ssl is True:
try:
from ssl import CERT_REQUIRED, SSLContext
from ssl import CERT_REQUIRED, PROTOCOL_TLS_CLIENT, SSLContext

# ssl_context = ssl.create_default_context()

Expand All @@ -686,7 +686,10 @@ def get_calling_module() -> str:
else:
path = "/".join(path.split("/")[:-1]) + "/files/redshift-ca-bundle.crt"

ssl_context: SSLContext = SSLContext()
ssl_context: SSLContext = SSLContext(PROTOCOL_TLS_CLIENT)
# Preserve the mode-specific hostname policy below. In
# particular, verify-ca validates the chain without a name.
ssl_context.check_hostname = False
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_default_certs()
_logger.debug("try to load Redshift CA certs from location %s", path)
Expand Down
53 changes: 53 additions & 0 deletions test/unit/test_ssl_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import ssl
import typing
import warnings
from unittest import mock

import pytest

from redshift_connector.core import Connection


class _StopAtTLS(Exception):
"""Stop before authentication, after inspecting the real SSL context."""


@pytest.mark.parametrize(
"sslmode,sslmode_defaulted,check_hostname",
[
("verify-ca", False, False),
("verify-full", True, False),
("verify-full", False, True),
],
)
def test_tls_context_uses_client_protocol_without_deprecated_defaults(
sslmode: str, sslmode_defaulted: bool, check_hostname: bool
) -> None:
sock = mock.MagicMock()
sock.recv.return_value = b"S"
contexts: typing.List[ssl.SSLContext] = []

def stop_at_tls(context, raw_socket, **kwargs):
contexts.append(context)
raise _StopAtTLS()

with warnings.catch_warnings(), mock.patch(
"redshift_connector.core.socket.socket", return_value=sock
), mock.patch.object(ssl.SSLContext, "wrap_socket", stop_at_tls):
warnings.simplefilter("error", DeprecationWarning)
with pytest.raises(_StopAtTLS):
Connection(
user="u",
password="p",
host="localhost",
port=5439,
database="dev",
ssl=True,
sslmode=sslmode,
sslmode_defaulted=sslmode_defaulted,
)

assert len(contexts) == 1
assert contexts[0].protocol == ssl.PROTOCOL_TLS_CLIENT
assert contexts[0].verify_mode == ssl.CERT_REQUIRED
assert contexts[0].check_hostname is check_hostname