Skip to content

Commit d05df6c

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

17 files changed

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

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

8871067
self.authenticator = authenticator
888-
self.ssl_options = ssl_options.copy() if ssl_options else {}
1068+
endpoint_ssl_options = self.endpoint.ssl_options
1069+
# Explicit ssl_options={} enables SSL with default options; omitted
1070+
# ssl_options=None leaves SSL disabled unless an endpoint supplies options.
1071+
self._ssl_options_explicit = ssl_options is not None
1072+
self.ssl_options = ssl_options.copy() if ssl_options is not None else {}
8891073
self.ssl_context = ssl_context
8901074
self.sockopts = sockopts
8911075
self.compression = compression
@@ -905,10 +1089,13 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9051089
self._on_orphaned_stream_released = on_orphaned_stream_released
9061090
self._application_info = application_info
9071091

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
1092+
if ssl_options is not None:
1093+
self.ssl_options.update(endpoint_ssl_options or {})
1094+
elif endpoint_ssl_options is not None:
1095+
self._ssl_options_explicit = True
1096+
self.ssl_options = endpoint_ssl_options
1097+
self._check_hostname = bool(self.ssl_options.get('check_hostname', False) or
1098+
getattr(self.ssl_context, 'check_hostname', False))
9121099

9131100
# PYTHON-1331
9141101
#
@@ -918,7 +1105,7 @@ def __init__(self, host='127.0.0.1', port=9042, authenticator=None,
9181105
#
9191106
# Note the use of pop() here; we are very deliberately removing these params from ssl_options if they're present. After this
9201107
# 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:
1108+
if self.ssl_context is None and self._ssl_options_explicit:
9221109
self.ssl_context = self._build_ssl_context_from_options()
9231110

9241111
self.max_request_id = min(self.max_in_flight - 1, (2 ** 15) - 1)
@@ -942,6 +1129,10 @@ def host(self):
9421129
def port(self):
9431130
return self.endpoint.port
9441131

1132+
@property
1133+
def _ssl_enabled(self):
1134+
return self.ssl_context is not None or self._ssl_options_explicit
1135+
9451136
@classmethod
9461137
def initialize_reactor(cls):
9471138
"""
@@ -1000,10 +1191,15 @@ def _build_ssl_context_from_options(self):
10001191
# Python >= 3.10 requires either PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER so we'll get ahead of things by always
10011192
# being explicit
10021193
ssl_version = opts.get('ssl_version', None) or ssl.PROTOCOL_TLS_CLIENT
1003-
cert_reqs = opts.get('cert_reqs', None) or ssl.CERT_REQUIRED
1194+
cert_reqs = opts.get('cert_reqs', None)
1195+
if cert_reqs is None:
1196+
cert_reqs = (ssl.CERT_REQUIRED
1197+
if (opts.get('ca_certs', None) or opts.get('check_hostname', False))
1198+
else ssl.CERT_NONE)
10041199
rv = ssl.SSLContext(protocol=int(ssl_version))
1200+
rv.check_hostname = False
1201+
rv.verify_mode = cert_reqs
10051202
rv.check_hostname = bool(opts.get('check_hostname', False))
1006-
rv.options = int(cert_reqs)
10071203

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