|
| 1 | +# Copyright ScyllaDB, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import sys |
| 16 | +import ssl |
| 17 | +import tempfile |
| 18 | +import base64 |
| 19 | +from ssl import SSLContext |
| 20 | +from contextlib import contextmanager |
| 21 | +from itertools import islice |
| 22 | + |
| 23 | +import six |
| 24 | +import yaml |
| 25 | + |
| 26 | +from cassandra.connection import SniEndPointFactory |
| 27 | +from cassandra.auth import AuthProvider, PlainTextAuthProvider |
| 28 | + |
| 29 | + |
| 30 | +@contextmanager |
| 31 | +def file_or_memory(path=None, data=None): |
| 32 | + # since we can't read keys/cert from memory yet |
| 33 | + # see https://github.com/python/cpython/pull/2449 which isn't accepted and PEP-543 that was withdrawn |
| 34 | + # so we use temporary file to load the key |
| 35 | + if data: |
| 36 | + with tempfile.NamedTemporaryFile(mode="wb") as f: |
| 37 | + d = base64.decodebytes(bytes(data, encoding='utf-8')) |
| 38 | + f.write(d) |
| 39 | + if not d.endswith(b"\n"): |
| 40 | + f.write(b"\n") |
| 41 | + |
| 42 | + f.flush() |
| 43 | + yield f.name |
| 44 | + |
| 45 | + if path: |
| 46 | + yield path |
| 47 | + |
| 48 | + |
| 49 | +def nth(iterable, n, default=None): |
| 50 | + "Returns the nth item or a default value" |
| 51 | + return next(islice(iterable, n, None), default) |
| 52 | + |
| 53 | + |
| 54 | +class CloudConfiguration: |
| 55 | + endpoint_factory: SniEndPointFactory |
| 56 | + contact_points: list |
| 57 | + auth_provider: AuthProvider = None |
| 58 | + ssl_options: dict |
| 59 | + ssl_context: SSLContext |
| 60 | + skip_tls_verify: bool |
| 61 | + |
| 62 | + def __init__(self, configuration_file, pyopenssl=False): |
| 63 | + cloud_config = yaml.safe_load(open(configuration_file)) |
| 64 | + |
| 65 | + self.current_context = cloud_config['contexts'][cloud_config['currentContext']] |
| 66 | + self.data_centers = cloud_config['datacenters'] |
| 67 | + self.auth_info = cloud_config['authInfos'][self.current_context['authInfoName']] |
| 68 | + self.ssl_options = {} |
| 69 | + self.skip_tls_verify = self.auth_info.get('insecureSkipTLSVerify', False) |
| 70 | + self.ssl_context = self.create_pyopenssl_context() if pyopenssl else self.create_ssl_context() |
| 71 | + |
| 72 | + proxy_address, port, node_domain = self.get_server(self.data_centers[self.current_context['datacenterName']], |
| 73 | + keys_order=['testServer', 'server']) |
| 74 | + self.endpoint_factory = SniEndPointFactory(proxy_address, port=int(port), node_domain=node_domain) |
| 75 | + |
| 76 | + username, password = self.auth_info.get('username'), self.auth_info.get('password') |
| 77 | + if username and password: |
| 78 | + self.auth_provider = PlainTextAuthProvider(username, password) |
| 79 | + |
| 80 | + |
| 81 | + @property |
| 82 | + def contact_points(self): |
| 83 | + _contact_points = [] |
| 84 | + for data_center in self.data_centers.values(): |
| 85 | + address, _, _ = self.get_server(data_center) |
| 86 | + _contact_points.append(self.endpoint_factory.create_from_sni(address)) |
| 87 | + return _contact_points |
| 88 | + |
| 89 | + def get_server(self, data_center, keys_order=None): |
| 90 | + keys_order = keys_order or ['server'] |
| 91 | + for key in keys_order: |
| 92 | + address = data_center.get(key, '') |
| 93 | + if not address: |
| 94 | + continue |
| 95 | + address = address.split(":") |
| 96 | + port = nth(address, 1, default=443) |
| 97 | + address = nth(address, 0) |
| 98 | + node_domain = data_center.get('nodeDomain') |
| 99 | + return address, port, node_domain |
| 100 | + |
| 101 | + def create_ssl_context(self): |
| 102 | + ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_SSLv23) |
| 103 | + ssl_context.verify_mode = ssl.VerifyMode.CERT_NONE if self.skip_tls_verify else ssl.VerifyMode.CERT_REQUIRED |
| 104 | + for data_center in self.data_centers.values(): |
| 105 | + with file_or_memory(path=data_center.get('certificateAuthorityPath'), |
| 106 | + data=data_center.get('certificateAuthorityData')) as cafile: |
| 107 | + ssl_context.load_verify_locations(cadata=open(cafile).read()) |
| 108 | + with file_or_memory(path=self.auth_info.get('clientCertificatePath'), |
| 109 | + data=self.auth_info.get('clientCertificateData')) as certfile, \ |
| 110 | + file_or_memory(path=self.auth_info.get('clientKeyPath'), data=self.auth_info.get('clientKeyData')) as keyfile: |
| 111 | + ssl_context.load_cert_chain(keyfile=keyfile, |
| 112 | + certfile=certfile) |
| 113 | + |
| 114 | + return ssl_context |
| 115 | + |
| 116 | + def create_pyopenssl_context(self): |
| 117 | + try: |
| 118 | + from OpenSSL import SSL |
| 119 | + except ImportError as e: |
| 120 | + six.reraise( |
| 121 | + ImportError, |
| 122 | + ImportError( |
| 123 | + "PyOpenSSL must be installed to connect to scylla-cloud with the Eventlet or Twisted event loops"), |
| 124 | + sys.exc_info()[2] |
| 125 | + ) |
| 126 | + ssl_context = SSL.Context(SSL.TLS_METHOD) |
| 127 | + ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: True if self.skip_tls_verify else ok) |
| 128 | + for data_center in self.data_centers.values(): |
| 129 | + with file_or_memory(path=data_center.get('certificateAuthorityPath'), |
| 130 | + data=data_center.get('certificateAuthorityData')) as cafile: |
| 131 | + ssl_context.load_verify_locations(cafile) |
| 132 | + with file_or_memory(path=self.auth_info.get('clientCertificatePath'), |
| 133 | + data=self.auth_info.get('clientCertificateData')) as certfile, \ |
| 134 | + file_or_memory(path=self.auth_info.get('clientKeyPath'), data=self.auth_info.get('clientKeyData')) as keyfile: |
| 135 | + ssl_context.use_privatekey_file(keyfile) |
| 136 | + ssl_context.use_certificate_file(certfile) |
| 137 | + |
| 138 | + return ssl_context |
| 139 | + |
| 140 | + @classmethod |
| 141 | + def create(cls, configuration_file, pyopenssl=False): |
| 142 | + return cls(configuration_file, pyopenssl) |
0 commit comments