Skip to content

Commit 535986a

Browse files
committed
connection: preserve explicit empty ssl_options
1 parent bcc2d3d commit 535986a

17 files changed

Lines changed: 1244 additions & 90 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: 218 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,197 @@ 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+
if check_hostname and context.get_verify_mode() == ssl_module.VERIFY_NONE:
183+
context.set_verify(
184+
ssl_module.VERIFY_PEER,
185+
callback=lambda _connection, _x509, _errnum, _errdepth, ok: ok
186+
)
187+
188+
189+
def _build_pyopenssl_context_from_options(ssl_module, ssl_options):
190+
ssl_options = ssl_options or {}
191+
context = ssl_module.Context(
192+
_pyopenssl_ssl_method_from_stdlib(ssl_module, ssl_options.get('ssl_version', None))
193+
)
194+
if 'certfile' in ssl_options:
195+
context.use_certificate_file(ssl_options['certfile'])
196+
if 'keyfile' in ssl_options:
197+
context.use_privatekey_file(ssl_options['keyfile'])
198+
if 'ca_certs' in ssl_options:
199+
context.load_verify_locations(ssl_options['ca_certs'])
200+
cert_reqs = _pyopenssl_verify_mode_from_cert_reqs(
201+
ssl_module, ssl_options.get('cert_reqs', None))
202+
if cert_reqs is None:
203+
cert_reqs = (ssl_module.VERIFY_PEER
204+
if ssl_options
205+
else ssl_module.VERIFY_NONE)
206+
elif ssl_options.get('check_hostname', False) and cert_reqs == ssl_module.VERIFY_NONE:
207+
cert_reqs = ssl_module.VERIFY_PEER
208+
context.set_verify(
209+
cert_reqs,
210+
callback=lambda _connection, _x509, _errnum, _errdepth, ok: ok
211+
)
212+
ciphers = ssl_options.get('ciphers', None)
213+
if ciphers:
214+
if isinstance(ciphers, str):
215+
ciphers = ciphers.encode('ascii')
216+
context.set_cipher_list(ciphers)
217+
return context
218+
219+
220+
def _normalized_hostname(hostname):
221+
return hostname.rstrip('.').lower()
222+
223+
224+
def _dnsname_match(dn, hostname):
225+
dn = _normalized_hostname(dn)
226+
hostname = _normalized_hostname(hostname)
227+
228+
if not dn or not hostname:
229+
return False
230+
231+
if '*' not in dn:
232+
return dn == hostname
233+
234+
dn_labels = dn.split('.')
235+
hostname_labels = hostname.split('.')
236+
if (len(dn_labels) != len(hostname_labels) or
237+
len(dn_labels) < 2 or dn_labels[0] != '*' or
238+
not hostname_labels[0] or
239+
any('*' in label for label in dn_labels[1:])):
240+
return False
241+
242+
return dn_labels[1:] == hostname_labels[1:]
243+
244+
245+
def _ipaddress_match(cert_ip, hostname):
246+
try:
247+
host_ip = ipaddress.ip_address(hostname)
248+
cert_ip = ipaddress.ip_address(cert_ip)
249+
except ValueError:
250+
return False
251+
return cert_ip == host_ip
252+
253+
254+
def _is_ip_address(hostname):
255+
try:
256+
ipaddress.ip_address(hostname)
257+
except ValueError:
258+
return False
259+
return True
260+
261+
262+
def _decode_x509_name(value):
263+
if isinstance(value, bytes):
264+
return value.decode('utf-8')
265+
return value
266+
267+
268+
def _pyopenssl_cert_subject_alt_names(cert):
269+
dns_names = []
270+
ip_addresses = []
271+
272+
for i in range(cert.get_extension_count()):
273+
extension = cert.get_extension(i)
274+
if extension.get_short_name() != b'subjectAltName':
275+
continue
276+
for item in str(extension).split(','):
277+
item = item.strip()
278+
if item.startswith('DNS:'):
279+
dns_names.append(item[4:])
280+
elif item.startswith('IP Address:'):
281+
ip_addresses.append(item[11:])
282+
283+
return dns_names, ip_addresses
284+
285+
286+
def _pyopenssl_cert_common_names(cert):
287+
return [
288+
_decode_x509_name(value)
289+
for key, value in cert.get_subject().get_components()
290+
if key == b'CN'
291+
]
292+
293+
294+
def _validate_pyopenssl_hostname(cert, hostname):
295+
san_dns_names, san_ip_addresses = _pyopenssl_cert_subject_alt_names(cert)
296+
san_names = san_dns_names + san_ip_addresses
297+
hostname_is_ip = _is_ip_address(hostname)
298+
299+
for cert_ip in san_ip_addresses:
300+
if _ipaddress_match(cert_ip, hostname):
301+
return
302+
if hostname_is_ip and san_names:
303+
raise ssl.CertificateError(
304+
"hostname %r doesn't match certificate subjectAltName %r" %
305+
(hostname, san_names))
306+
307+
for cert_hostname in san_dns_names:
308+
if _dnsname_match(cert_hostname, hostname):
309+
return
310+
if san_names:
311+
raise ssl.CertificateError(
312+
"hostname %r doesn't match certificate subjectAltName %r" %
313+
(hostname, san_names))
314+
315+
common_names = _pyopenssl_cert_common_names(cert)
316+
for common_name in common_names:
317+
if (_ipaddress_match(common_name, hostname) if hostname_is_ip
318+
else _dnsname_match(common_name, hostname)):
319+
return
320+
321+
raise ssl.CertificateError(
322+
"hostname %r doesn't match certificate commonName %r" %
323+
(hostname, common_names))
324+
325+
133326
class EndPoint(object):
134327
"""
135328
Represents the information to connect to a cassandra node.
@@ -803,6 +996,7 @@ class Connection(object):
803996
endpoint = None
804997
ssl_options = None
805998
ssl_context = None
999+
_ssl_options_explicit = False
8061000
last_error = None
8071001

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

8871081
self.authenticator = authenticator
888-
self.ssl_options = ssl_options.copy() if ssl_options else {}
1082+
endpoint_ssl_options = self.endpoint.ssl_options
1083+
# Explicit ssl_options={} enables SSL with default options; omitted
1084+
# ssl_options=None leaves SSL disabled unless an endpoint supplies options.
1085+
self._ssl_options_explicit = ssl_options is not None
1086+
self.ssl_options = ssl_options.copy() if ssl_options is not None else {}
8891087
self.ssl_context = ssl_context
8901088
self.sockopts = sockopts
8911089
self.compression = compression
@@ -905,10 +1103,13 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9051103
self._on_orphaned_stream_released = on_orphaned_stream_released
9061104
self._application_info = application_info
9071105

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
1106+
if ssl_options is not None:
1107+
self.ssl_options.update(endpoint_ssl_options or {})
1108+
elif endpoint_ssl_options is not None:
1109+
self._ssl_options_explicit = True
1110+
self.ssl_options = endpoint_ssl_options
1111+
self._check_hostname = bool(self.ssl_options.get('check_hostname', False) or
1112+
getattr(self.ssl_context, 'check_hostname', False))
9121113

9131114
# PYTHON-1331
9141115
#
@@ -918,7 +1119,7 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9181119
#
9191120
# Note the use of pop() here; we are very deliberately removing these params from ssl_options if they're present. After this
9201121
# 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:
1122+
if self.ssl_context is None and self._ssl_options_explicit:
9221123
self.ssl_context = self._build_ssl_context_from_options()
9231124

9241125
self.max_request_id = min(self.max_in_flight - 1, (2 ** 15) - 1)
@@ -942,6 +1143,10 @@ def host(self):
9421143
def port(self):
9431144
return self.endpoint.port
9441145

1146+
@property
1147+
def _ssl_enabled(self):
1148+
return self.ssl_context is not None or self._ssl_options_explicit
1149+
9451150
@classmethod
9461151
def initialize_reactor(cls):
9471152
"""
@@ -1000,10 +1205,15 @@ def _build_ssl_context_from_options(self):
10001205
# Python >= 3.10 requires either PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER so we'll get ahead of things by always
10011206
# being explicit
10021207
ssl_version = opts.get('ssl_version', None) or ssl.PROTOCOL_TLS_CLIENT
1003-
cert_reqs = opts.get('cert_reqs', None) or ssl.CERT_REQUIRED
1208+
cert_reqs = opts.get('cert_reqs', None)
1209+
if cert_reqs is None:
1210+
cert_reqs = (ssl.CERT_REQUIRED
1211+
if self.ssl_options
1212+
else ssl.CERT_NONE)
10041213
rv = ssl.SSLContext(protocol=int(ssl_version))
1214+
rv.check_hostname = False
1215+
rv.verify_mode = cert_reqs
10051216
rv.check_hostname = bool(opts.get('check_hostname', False))
1006-
rv.options = int(cert_reqs)
10071217

10081218
certfile = opts.get('certfile', None)
10091219
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)