Skip to content

Commit 9d63584

Browse files
committed
connection: preserve explicit empty ssl_options
1 parent bcc2d3d commit 9d63584

17 files changed

Lines changed: 1271 additions & 93 deletions

cassandra/cluster.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,7 +1298,8 @@ def __init__(self,
12981298

12991299
if cloud is not None:
13001300
self.cloud = cloud
1301-
if contact_points is not _NOT_SET or endpoint_factory or ssl_context or ssl_options:
1301+
if (contact_points is not _NOT_SET or endpoint_factory or
1302+
ssl_context is not None or ssl_options is not None):
13021303
raise ValueError("contact_points, endpoint_factory, ssl_context, and ssl_options "
13031304
"cannot be specified with a cloud configuration")
13041305

@@ -1508,7 +1509,7 @@ def __init__(self,
15081509

15091510
self.metrics_enabled = metrics_enabled
15101511

1511-
if ssl_options and not ssl_context:
1512+
if ssl_options is not None and ssl_context is None:
15121513
warn('Using ssl_options without ssl_context is '
15131514
'deprecated and will result in an error in '
15141515
'the next major release. Please use ssl_context '

cassandra/connection.py

Lines changed: 220 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import errno
1818
from functools import wraps, partial, total_ordering
1919
from heapq import heappush, heappop
20+
import ipaddress
2021
import io
2122
import logging
2223
import socket
@@ -55,6 +56,7 @@
5556

5657
log = logging.getLogger(__name__)
5758

59+
5860
segment_codec_no_compression = SegmentCodec()
5961
segment_codec_lz4 = None
6062

@@ -130,6 +132,199 @@ def decompress(byts):
130132
frame_header_v3 = struct.Struct('>BhBi')
131133

132134

135+
def _default_pyopenssl_ssl_method(ssl_module):
136+
for method_name in ('TLS_CLIENT_METHOD', 'TLS_METHOD', 'TLSv1_2_METHOD'):
137+
method = getattr(ssl_module, method_name, None)
138+
if method is not None:
139+
return method
140+
raise ImportError('pyOpenSSL does not expose a secure TLS client method')
141+
142+
143+
def _pyopenssl_ssl_method_from_stdlib(ssl_module, ssl_version):
144+
if ssl_version is None:
145+
return _default_pyopenssl_ssl_method(ssl_module)
146+
147+
protocol_method_names = (
148+
('PROTOCOL_TLS_CLIENT', ('TLS_CLIENT_METHOD', 'TLS_METHOD', 'TLSv1_2_METHOD')),
149+
('PROTOCOL_TLS', ('TLS_METHOD', 'TLS_CLIENT_METHOD', 'TLSv1_2_METHOD')),
150+
('PROTOCOL_SSLv23', ('TLS_METHOD', 'TLS_CLIENT_METHOD', 'TLSv1_2_METHOD')),
151+
('PROTOCOL_TLSv1_2', ('TLSv1_2_METHOD',)),
152+
('PROTOCOL_TLSv1_1', ('TLSv1_1_METHOD',)),
153+
('PROTOCOL_TLSv1', ('TLSv1_METHOD',)),
154+
)
155+
for protocol_name, method_names in protocol_method_names:
156+
protocol = getattr(ssl, protocol_name, None)
157+
if (protocol is not None and
158+
ssl_version.__class__ is protocol.__class__ and
159+
ssl_version == protocol):
160+
for method_name in method_names:
161+
method = getattr(ssl_module, method_name, None)
162+
if method is not None:
163+
return method
164+
raise ImportError('pyOpenSSL does not expose a method for %s' % (protocol_name,))
165+
166+
return ssl_version
167+
168+
169+
def _pyopenssl_verify_mode_from_cert_reqs(ssl_module, cert_reqs):
170+
if cert_reqs is None:
171+
return None
172+
if cert_reqs.__class__ is not type(ssl.CERT_REQUIRED):
173+
return cert_reqs
174+
if cert_reqs == ssl.CERT_NONE:
175+
return ssl_module.VERIFY_NONE
176+
if cert_reqs in (ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED):
177+
return ssl_module.VERIFY_PEER
178+
return cert_reqs
179+
180+
181+
def _ensure_pyopenssl_context_requires_verification(ssl_module, context, check_hostname):
182+
get_verify_mode = getattr(context, 'get_verify_mode', None)
183+
if (check_hostname and get_verify_mode is not None and
184+
get_verify_mode() == ssl_module.VERIFY_NONE):
185+
context.set_verify(
186+
ssl_module.VERIFY_PEER,
187+
callback=lambda _connection, _x509, _errnum, _errdepth, ok: ok
188+
)
189+
190+
191+
def _build_pyopenssl_context_from_options(ssl_module, ssl_options):
192+
ssl_options = ssl_options or {}
193+
context = ssl_module.Context(
194+
_pyopenssl_ssl_method_from_stdlib(ssl_module, ssl_options.get('ssl_version', None))
195+
)
196+
if 'certfile' in ssl_options:
197+
context.use_certificate_file(ssl_options['certfile'])
198+
if 'keyfile' in ssl_options:
199+
context.use_privatekey_file(ssl_options['keyfile'])
200+
if 'ca_certs' in ssl_options:
201+
context.load_verify_locations(ssl_options['ca_certs'])
202+
cert_reqs = _pyopenssl_verify_mode_from_cert_reqs(
203+
ssl_module, ssl_options.get('cert_reqs', None))
204+
if cert_reqs is None:
205+
cert_reqs = (ssl_module.VERIFY_PEER
206+
if ssl_options
207+
else ssl_module.VERIFY_NONE)
208+
elif ssl_options.get('check_hostname', False) and cert_reqs == ssl_module.VERIFY_NONE:
209+
cert_reqs = ssl_module.VERIFY_PEER
210+
context.set_verify(
211+
cert_reqs,
212+
callback=lambda _connection, _x509, _errnum, _errdepth, ok: ok
213+
)
214+
ciphers = ssl_options.get('ciphers', None)
215+
if ciphers:
216+
if isinstance(ciphers, str):
217+
ciphers = ciphers.encode('ascii')
218+
context.set_cipher_list(ciphers)
219+
return context
220+
221+
222+
def _normalized_hostname(hostname):
223+
return hostname.rstrip('.').lower()
224+
225+
226+
def _dnsname_match(dn, hostname):
227+
dn = _normalized_hostname(dn)
228+
hostname = _normalized_hostname(hostname)
229+
230+
if not dn or not hostname:
231+
return False
232+
233+
if '*' not in dn:
234+
return dn == hostname
235+
236+
dn_labels = dn.split('.')
237+
hostname_labels = hostname.split('.')
238+
if (len(dn_labels) != len(hostname_labels) or
239+
len(dn_labels) < 2 or dn_labels[0] != '*' or
240+
not hostname_labels[0] or
241+
any('*' in label for label in dn_labels[1:])):
242+
return False
243+
244+
return dn_labels[1:] == hostname_labels[1:]
245+
246+
247+
def _ipaddress_match(cert_ip, hostname):
248+
try:
249+
host_ip = ipaddress.ip_address(hostname)
250+
cert_ip = ipaddress.ip_address(cert_ip)
251+
except ValueError:
252+
return False
253+
return cert_ip == host_ip
254+
255+
256+
def _is_ip_address(hostname):
257+
try:
258+
ipaddress.ip_address(hostname)
259+
except ValueError:
260+
return False
261+
return True
262+
263+
264+
def _decode_x509_name(value):
265+
if isinstance(value, bytes):
266+
return value.decode('utf-8')
267+
return value
268+
269+
270+
def _pyopenssl_cert_subject_alt_names(cert):
271+
dns_names = []
272+
ip_addresses = []
273+
274+
for i in range(cert.get_extension_count()):
275+
extension = cert.get_extension(i)
276+
if extension.get_short_name() != b'subjectAltName':
277+
continue
278+
for item in str(extension).split(','):
279+
item = item.strip()
280+
if item.startswith('DNS:'):
281+
dns_names.append(item[4:])
282+
elif item.startswith('IP Address:'):
283+
ip_addresses.append(item[11:])
284+
285+
return dns_names, ip_addresses
286+
287+
288+
def _pyopenssl_cert_common_names(cert):
289+
return [
290+
_decode_x509_name(value)
291+
for key, value in cert.get_subject().get_components()
292+
if key == b'CN'
293+
]
294+
295+
296+
def _validate_pyopenssl_hostname(cert, hostname):
297+
san_dns_names, san_ip_addresses = _pyopenssl_cert_subject_alt_names(cert)
298+
san_names = san_dns_names + san_ip_addresses
299+
hostname_is_ip = _is_ip_address(hostname)
300+
301+
for cert_ip in san_ip_addresses:
302+
if _ipaddress_match(cert_ip, hostname):
303+
return
304+
if hostname_is_ip and san_names:
305+
raise ssl.CertificateError(
306+
"hostname %r doesn't match certificate subjectAltName %r" %
307+
(hostname, san_names))
308+
309+
for cert_hostname in san_dns_names:
310+
if _dnsname_match(cert_hostname, hostname):
311+
return
312+
if san_names:
313+
raise ssl.CertificateError(
314+
"hostname %r doesn't match certificate subjectAltName %r" %
315+
(hostname, san_names))
316+
317+
common_names = _pyopenssl_cert_common_names(cert)
318+
for common_name in common_names:
319+
if (_ipaddress_match(common_name, hostname) if hostname_is_ip
320+
else _dnsname_match(common_name, hostname)):
321+
return
322+
323+
raise ssl.CertificateError(
324+
"hostname %r doesn't match certificate commonName %r" %
325+
(hostname, common_names))
326+
327+
133328
class EndPoint(object):
134329
"""
135330
Represents the information to connect to a cassandra node.
@@ -803,6 +998,7 @@ class Connection(object):
803998
endpoint = None
804999
ssl_options = None
8051000
ssl_context = None
1001+
_ssl_options_explicit = False
8061002
last_error = None
8071003

8081004
# The current number of operations that are in flight. More precisely,
@@ -885,7 +1081,11 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
8851081
self.endpoint = host if isinstance(host, EndPoint) else DefaultEndPoint(host, port)
8861082

8871083
self.authenticator = authenticator
888-
self.ssl_options = ssl_options.copy() if ssl_options else {}
1084+
endpoint_ssl_options = self.endpoint.ssl_options
1085+
# Explicit ssl_options={} enables SSL with default options; omitted
1086+
# ssl_options=None leaves SSL disabled unless an endpoint supplies options.
1087+
self._ssl_options_explicit = ssl_options is not None
1088+
self.ssl_options = ssl_options.copy() if ssl_options is not None else {}
8891089
self.ssl_context = ssl_context
8901090
self.sockopts = sockopts
8911091
self.compression = compression
@@ -905,10 +1105,13 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9051105
self._on_orphaned_stream_released = on_orphaned_stream_released
9061106
self._application_info = application_info
9071107

908-
if ssl_options:
909-
self.ssl_options.update(self.endpoint.ssl_options or {})
910-
elif self.endpoint.ssl_options:
911-
self.ssl_options = self.endpoint.ssl_options
1108+
if ssl_options is not None:
1109+
self.ssl_options.update(endpoint_ssl_options or {})
1110+
elif endpoint_ssl_options is not None:
1111+
self._ssl_options_explicit = True
1112+
self.ssl_options = endpoint_ssl_options
1113+
self._check_hostname = bool(self.ssl_options.get('check_hostname', False) or
1114+
getattr(self.ssl_context, 'check_hostname', False))
9121115

9131116
# PYTHON-1331
9141117
#
@@ -918,7 +1121,7 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9181121
#
9191122
# Note the use of pop() here; we are very deliberately removing these params from ssl_options if they're present. After this
9201123
# operation ssl_options should contain only args needed for the ssl_context.wrap_socket() call.
921-
if not self.ssl_context and self.ssl_options:
1124+
if self.ssl_context is None and self._ssl_options_explicit:
9221125
self.ssl_context = self._build_ssl_context_from_options()
9231126

9241127
self.max_request_id = min(self.max_in_flight - 1, (2 ** 15) - 1)
@@ -942,6 +1145,10 @@ def host(self):
9421145
def port(self):
9431146
return self.endpoint.port
9441147

1148+
@property
1149+
def _ssl_enabled(self):
1150+
return self.ssl_context is not None or self._ssl_options_explicit
1151+
9451152
@classmethod
9461153
def initialize_reactor(cls):
9471154
"""
@@ -1000,10 +1207,15 @@ def _build_ssl_context_from_options(self):
10001207
# Python >= 3.10 requires either PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER so we'll get ahead of things by always
10011208
# being explicit
10021209
ssl_version = opts.get('ssl_version', None) or ssl.PROTOCOL_TLS_CLIENT
1003-
cert_reqs = opts.get('cert_reqs', None) or ssl.CERT_REQUIRED
1210+
cert_reqs = opts.get('cert_reqs', None)
1211+
if cert_reqs is None:
1212+
cert_reqs = (ssl.CERT_REQUIRED
1213+
if self.ssl_options
1214+
else ssl.CERT_NONE)
10041215
rv = ssl.SSLContext(protocol=int(ssl_version))
1216+
rv.check_hostname = False
1217+
rv.verify_mode = cert_reqs
10051218
rv.check_hostname = bool(opts.get('check_hostname', False))
1006-
rv.options = int(cert_reqs)
10071219

10081220
certfile = opts.get('certfile', None)
10091221
keyfile = opts.get('keyfile', None)

cassandra/datastax/cloud/__init__.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
from zipfile import BadZipfile as BadZipFile
3535

3636
from cassandra import DriverException
37+
from cassandra.connection import _default_pyopenssl_ssl_method
3738

3839
log = logging.getLogger(__name__)
3940

@@ -181,12 +182,12 @@ def _pyopenssl_context_from_cert(ca_cert_location, cert_location, key_location):
181182
from OpenSSL import SSL
182183
except ImportError as e:
183184
raise ImportError(
184-
"PyOpenSSL must be installed to connect to Astra with the Eventlet or Twisted event loops")\
185-
.with_traceback(e.__traceback__)
186-
ssl_context = SSL.Context(SSL.TLSv1_METHOD)
185+
"PyOpenSSL must be installed to connect to Astra with the Eventlet or Twisted event loops"
186+
) from e
187+
ssl_context = SSL.Context(_default_pyopenssl_ssl_method(SSL))
187188
ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: ok)
188189
ssl_context.use_certificate_file(cert_location)
189190
ssl_context.use_privatekey_file(key_location)
190191
ssl_context.load_verify_locations(ca_cert_location)
191192

192-
return ssl_context
193+
return ssl_context

0 commit comments

Comments
 (0)