def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None ): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) # Py32 raises IOError # Py33 raises FileNotFoundError except Exception: # Reraise as SSLError e = sys.exc_info()[1] raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs # Disable TLS compression to migitate CRIME attack (issue #309) OP_NO_COMPRESSION = 0x20000 context.options |= OP_NO_COMPRESSION if ca_certs: try: context.load_verify_locations(ca_certs) # Py32 raises IOError # Py33 raises FileNotFoundError except Exception as e: # Reraise as SSLError raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def get_connection(self): """ Returns Cassandra session """ auth_provider = None if self.ssl: ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_verify_locations(path_cert) ssl_context.verify_mode = CERT_REQUIRED #ssl_options = { # 'ca_certs' : self.ssl, # 'ssl_version' : PROTOCOL_TLSv1_2 #} else: ssl_context = None if (self.username and self.password): auth_provider = PlainTextAuthProvider(self.username, self.password) node1_profile = ExecutionProfile( load_balancing_policy=WhiteListRoundRobinPolicy( [self.endpoint_name])) profiles = {'node1': node1_profile} cluster = Cluster([self.endpoint_name], port=self.port, auth_provider=auth_provider, ssl_context=ssl_context, control_connection_timeout=360, execution_profiles=profiles) session = cluster.connect() return session
def create_context(keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs # Disable TLS compression to migitate CRIME attack (issue #309) OP_NO_COMPRESSION = 0x20000 context.options |= OP_NO_COMPRESSION if ca_certs: try: context.load_verify_locations(ca_certs) # Py32 raises IOError # Py33 raises FileNotFoundError except Exception as e: # Reraise as SSLError raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) return context
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) print('------') except Exception as e: raise SSLError(e) else: context.load_default_certs(purpose=Purpose.SERVER_AUTH) if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # server name indication enabled by OpenSSL return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
class DataProvider: def __init__(self, *, name, cs, members, lvl=0, config_source, full_path): assert isinstance(cs, str) or isinstance( cs, type(None)), (cs, 'should be a string or None') assert isinstance(name, str), (name, 'should be a string.') self._cs = cs self._name = name self._members = members self._lvl = lvl self._config_source = config_source self._full_path = full_path self._ssl_cert_path = self._config_source.parent / Path( f'{self._full_path}_{self._name}.givemedata.cer') # if SSL cert provided - configure context if self._ssl_cert_path.exists(): self.ssl_context = SSLContext(PROTOCOL_TLSv1) self.ssl_context.load_verify_locations(self._ssl_cert_path) self.ssl_context.verify_mode = CERT_REQUIRED else: self.ssl_context = None def __str__(self): spaces = ' ' * self._lvl arrow = '=>' if not self._members else '' s = f'\n{spaces}{self._name} {arrow} {self._cs or [m for m in self._members]}' return s.replace('[', '').replace(']', '').replace(',', '') def __repr__(self): return self.__str__()
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs OP_NO_COMPRESSION = 131072 context.options |= OP_NO_COMPRESSION if ca_certs: try: context.load_verify_locations(ca_certs) except Exception as e: raise SSLError(e) if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None, server_hostname=None, ssl_version=PROTOCOL_SSLv23): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) except TypeError as e: # Reraise as SSLError # fixme: This block needs a test. raise SSLError(e) if certfile: # fixme: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def __init__(self, host, port, certfile=None, keyfile=None, cacertfile=None, force_ssl=False, *args, **kw): super(ConnectionPoolManager, self).__init__(*args, **kw) self.logger.debug("Creating ConnectionPoolManager for %s:%s", host, port) if certfile or keyfile or force_ssl: #https://docs.python.org/2/library/ssl.html#ssl.SSLContext from ssl import SSLContext, PROTOCOL_SSLv23 ssl_context = SSLContext(PROTOCOL_SSLv23) ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) ssl_context.load_verify_locations(cafile=cacertfile) #https://docs.python.org/2/library/httplib.html self.__pool = HTTPSConnectionPool(host, port, maxsize=16, context=ssl_context) else: self.__pool = HTTPConnectionPool(host, port, maxsize=16)
def connect_db(self, connection_options=None): port = connection_options.get("port") endpoint = connection_options.get("endpoint") username = connection_options.get("credentials").get("username") password = connection_options.get("credentials").get("password") ssl_certificate_path = connection_options.get("ssl_certificate_path") if connection_options: try: ssl_context = SSLContext(PROTOCOL_TLSv1_2) ssl_context.load_verify_locations(ssl_certificate_path) ssl_context.verify_mode = CERT_REQUIRED auth_provider = PlainTextAuthProvider(username=username, password=password) cluster = Cluster([endpoint], ssl_context=ssl_context, auth_provider=auth_provider, port=port) connection = cluster.connect() print() print("Connected to Amazon Keyspaces at ", connection_options.get("endpoint")) return connection except (Exception) as connection_error: print(connection_error)
def __init__(self, ip_addresses, cassandra_config): self._ip_addresses = ip_addresses self._auth_provider = None self._ssl_context = None self._cassandra_config = cassandra_config if cassandra_config.cql_username is not None and cassandra_config.cql_password is not None: auth_provider = PlainTextAuthProvider( username=cassandra_config.cql_username, password=cassandra_config.cql_password) self._auth_provider = auth_provider if cassandra_config.certfile is not None and cassandra_config.usercert is not None and \ cassandra_config.userkey is not None: ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_verify_locations(cassandra_config.certfile) ssl_context.verify_mode = CERT_REQUIRED ssl_context.load_cert_chain(certfile=cassandra_config.usercert, keyfile=cassandra_config.userkey) self._ssl_context = ssl_context load_balancing_policy = WhiteListRoundRobinPolicy(ip_addresses) self._execution_profiles = { 'local': ExecutionProfile(load_balancing_policy=load_balancing_policy) }
def _ssl_context_from_cert(ca_cert_location, cert_location, key_location): ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_verify_locations(ca_cert_location) ssl_context.verify_mode = CERT_REQUIRED ssl_context.load_cert_chain(certfile=cert_location, keyfile=key_location) return ssl_context
def create_ssl_context(): ssl_context = SSLContext() ssl_context.verify_mode = VerifyMode.CERT_REQUIRED ssl_context.load_verify_locations( cafile="ww-np-dl-playstation-net-root.pem" ) # Load the CA certificate for Playsation servers return ssl_context
def create_ssl_context(ssl_params): if not ssl_params.get('use_ssl'): return None keyfile = ssl_params.get('ssl_keyfile', None) certfile = ssl_params.get('ssl_certfile', None) if keyfile and not certfile: raise ValueError("certfile must be specified") password = ssl_params.get('ssl_keyfile_password', None) ssl_version = ssl_params.get('ssl_version', SSL_DEFAULT_VERSION) ciphers = ssl_params.get('ssl_ciphers', SSL_DEFAULT_CIPHERS) cert_reqs = ssl_params.get('ssl_cert_reqs', ssl.CERT_NONE) ca_certs = ssl_params.get('ssl_ca_certfile', None) context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: context.load_verify_locations(ca_certs) if certfile: context.load_cert_chain(certfile, keyfile, password) if ciphers: context.set_ciphers(ciphers) return context
def connect_cassandra(is_client_encryption_enable, tls_version=PROTOCOL_TLS): connected = False attempt = 0 session = None _ssl_context = None if is_client_encryption_enable: ssl_context = SSLContext(tls_version) ssl_context.load_verify_locations(certfile) ssl_context.verify_mode = CERT_REQUIRED ssl_context.load_cert_chain(certfile=usercert, keyfile=userkey) _ssl_context = ssl_context while not connected and attempt < 10: try: cluster = Cluster(contact_points=["127.0.0.1"], ssl_context=_ssl_context, protocol_version=ProtocolVersion.V4) session = cluster.connect() connected = True except cassandra.cluster.NoHostAvailable: attempt += 1 time.sleep(10) if tls_version is not PROTOCOL_TLS: # other TLS versions used for testing, close the session session.shutdown() return session
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) # Py32 raises IOError # Py33 raises FileNotFoundError except Exception as e: # Reraise as SSLError raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def connect_cassandra(is_client_encryption_enable): connected = False attempt = 0 session = None _ssl_context = None if is_client_encryption_enable: ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_verify_locations(certfile) ssl_context.verify_mode = CERT_REQUIRED ssl_context.load_cert_chain(certfile=usercert, keyfile=userkey) _ssl_context = ssl_context while not connected and attempt < 10: try: cluster = Cluster(contact_points=["127.0.0.1"], ssl_context=_ssl_context) session = cluster.connect() connected = True except cassandra.cluster.NoHostAvailable: attempt += 1 time.sleep(10) return session
def wrap(client, _socket): """ Wrap socket in SSL wrapper. """ if client.init_kwargs.get('use_ssl', None): keyfile = client.init_kwargs.get('ssl_keyfile', None) certfile = client.init_kwargs.get('ssl_certfile', None) if keyfile and not certfile: raise ValueError("certfile must be specified") password = client.init_kwargs.get('ssl_keyfile_password', None) ssl_version = client.init_kwargs.get('ssl_version', SSL_DEFAULT_VERSION) ciphers = client.init_kwargs.get('ssl_ciphers', SSL_DEFAULT_CIPHERS) cert_reqs = client.init_kwargs.get('ssl_cert_reqs', ssl.CERT_NONE) ca_certs = client.init_kwargs.get('ssl_ca_certfile', None) context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: context.load_verify_locations(ca_certs) if certfile: context.load_cert_chain(certfile, keyfile, password) if ciphers: context.set_ciphers(ciphers) _socket = context.wrap_socket(sock=_socket) return _socket
def main(port=None): # load db db = pickle.loads(Path('users.pickle').read_bytes()) # read user id splash_screen() print('Assume the role of a card reader, and type the card id, will you?') userid = sys.stdin.readline()[:-1].encode() # read card pin print('\nGood, good... Now punch in the pin:') pin = sys.stdin.readline()[:-1].encode() # fetch secret _, _, _, pin_salt = db[userid] pin = hash_pin(pin, pin_salt) # start server ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.load_verify_locations('cert.pem') ok = 'ok' err = 'err' with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: with ctx.wrap_socket(sock, server_hostname='localhost') as c: print('\nDialing backend...') # connect c.connect(('localhost', port)) print('...All good!\n') # send user id and pin msg = pickle.dumps(dict(userid=userid, pin=pin)) c.sendall(msg) # check if ok msg = pickle.loads(c.recv(1024)) if not msg[ok]: print(f'Error: {msg[err]}') return # read 2fa token print('Punch in your 2fa token:') token = sys.stdin.readline()[:-1] # send token msg = pickle.dumps(dict(token=token)) c.sendall(msg) # check if ok msg = pickle.loads(c.recv(1024)) if not msg[ok]: print(f'Error: {msg[err]}') return print(f'\n\nAutheticated as: {str(userid, "utf8")}') print('Alright, time to order some Uber Eats(tm)!')
def sslContext(trustStore: str, keyStore: str) -> SSLContext: sslContext = SSLContext(PROTOCOL_TLSv1_2) sslContext.verify_mode = CERT_REQUIRED storePath = "../../certificates/" sslContext.load_verify_locations(storePath + trustStore) sslContext.load_cert_chain(storePath + keyStore, password="******") sslContext.set_ciphers("AES128-SHA") return sslContext
def getSSLContext(capath, crtpath, keypath, keypass=None): ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # client certificate is required ctx.verify_mode = CERT_REQUIRED ctx.options |= OP_NO_COMPRESSION ctx.load_verify_locations(capath) ctx.load_cert_chain(crtpath, keypath, password=keypass) return ctx
def load_cert(self, context: ssl.SSLContext, hostname: str) -> bool: cert_path = self._cert_path(hostname) if not cert_path.exists(): return False logger.debug("loading self-signed certificate for %s from %s", hostname, str(cert_path)) context.load_verify_locations(cafile=str(cert_path)) return True
def context(self) -> Optional[SSLContext]: if self.ssl: self.logger.info("Setting up SSL") context = SSLContext(PROTOCOL_TLS) if self.cert and self.key: self.logger.info("Using SSL Cert: %s", self.cert) try: context.load_cert_chain(str(self.cert), str(self.key), password=self.key_password) except FileNotFoundError as e: raise FileNotFoundError( better_file_not_found_error( self.cert, self.key, purpose='ssl cert loading')) if self.warn_if_expires_before_days: self._warn_expiry_task = create_task( self.check_cert_expiry()) set_task_name(self._warn_expiry_task, 'CheckSSLCertValidity') context.verify_mode = CERT_REQUIRED if self.cert_required else CERT_NONE context.check_hostname = self.check_hostname self.logger.info('%s, Check Hostname: %s' % (context.verify_mode, context.check_hostname)) if context.verify_mode != CERT_NONE: if self.cafile or self.capath or self.cadata: locations = { 'cafile': str(self.cafile) if self.cafile else None, 'capath': str(self.capath) if self.capath else None, 'cadata': self.cadata } try: context.load_verify_locations(**locations) self.logger.info("Verifying SSL certs with: %s", locations) except FileNotFoundError: raise FileNotFoundError( better_file_not_found_error( *locations.values(), purpose='CA ssl cert validation')) else: context.load_default_certs(self.purpose) self.logger.info("Verifying SSL certs with: %s", get_default_verify_paths()) self.logger.info("SSL Context loaded") # OpenSSL 1.1.1 keylog file if hasattr(context, 'keylog_filename'): keylogfile = os.environ.get('SSLKEYLOGFILE') if keylogfile and not sys.flags.ignore_environment: self.logger.warning( "TLS encryption secrets are being stored in %s", keylogfile) context.keylog_filename = keylogfile return context return None
def load_TLS(self): context = SSLContext(PROTOCOL_TLS) context.minimum_version = TLSVersion.TLSv1_3 context.verify_mode = CERT_REQUIRED context.check_hostname = True if self.CA != 'default' and self.CA != '': context.load_verify_locations(self.CA) else: context.load_default_certs() self.server = create_connection((self.SERVER_HOST, self.SERVER_PORT)) self.server = context.wrap_socket(self.server, server_hostname=self.SERVER_HOST)
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, ca_certs, cert_reqs = args ctx = SSLContext(ssl.PROTOCOL_SSLv23) if certfile is not None: ctx.load_cert_chain(certfile, keyfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) if cert_reqs is not None: ctx.verify_mode = cert_reqs return ctx
def __init__(self): ssl_context = SSLContext(PROTOCOL_TLSv1_2) ssl_context.load_verify_locations('.cassandra/AmazonRootCA1.pem') ssl_context.verify_mode = CERT_REQUIRED auth_provider = PlainTextAuthProvider(username='******', password='******') self.cluster = Cluster(['cassandra.us-east-1.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider, port=9142) self.session = self.cluster.connect("test_keyspace")
def _create_ssl_context(self) -> Optional[SSLContext]: ssl_context = None if self.cfg.is_ssl: ssl_context = SSLContext(self.cfg.ssl_version) ssl_context.load_cert_chain(self.cfg.certfile, self.cfg.keyfile) if self.cfg.ca_certs: ssl_context.load_verify_locations(self.cfg.ca_certs) if self.cfg.ciphers: ssl_context.set_ciphers(self.cfg.ciphers) ssl_context.set_alpn_protocols(['h2', 'http/1.1']) return ssl_context
def connect_server(): global client HOSTNAME = 'example.org' SERVER = "127.0.0.1" PORT = 3443 context = SSLContext(PROTOCOL_TLS_CLIENT) context.load_verify_locations('certificates/cert.pem') tls = create_connection((SERVER, PORT)) client = context.wrap_socket(tls, server_hostname=HOSTNAME) print("insert the input then press ENTER") print("press q + ENTER so exit") print() #sending the data to server
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. ctx = SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ctx, "options"): # Explicitly disable SSLv2 and SSLv3. Note that up to # date versions of MongoDB 2.4 and above already do this, # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4 # and SSLv3 in >= 3.4.3. There is no way for us to do this # explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) if certfile is not None: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
def _config_ssl_context(config): if config.get_ssl_context() is not None: return if config.get_service_url().scheme == 'https': try: if config.get_ssl_protocol() is None: ctx = create_default_context() else: ctx = SSLContext(config.get_ssl_protocol()) if config.get_ssl_cipher_suites() is not None: ctx.set_ciphers(config.get_ssl_cipher_suites()) if config.get_ssl_ca_certs() is not None: ctx.load_verify_locations(config.get_ssl_ca_certs()) config.set_ssl_context(ctx) except (SSLError, ValueError) as err: raise IllegalArgumentException(str(err))
def ssl_wrap_socket(sock, keyfile = None, certfile = None, cert_reqs = None, ca_certs = None, server_hostname = None, ssl_version = None): context = SSLContext(ssl_version) context.verify_mode = cert_reqs OP_NO_COMPRESSION = 131072 context.options |= OP_NO_COMPRESSION if ca_certs: try: context.load_verify_locations(ca_certs) except Exception as e: raise SSLError(e) if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def get_cassandra_connection(cluster_mode=False): if cluster_mode: ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_verify_locations(cnt.AWS_KEYSPACES_PEM) ssl_context.verify_mode = CERT_REQUIRED auth_provider = PlainTextAuthProvider( username=cnt.AWS_KEYSPACES_USER, password=cnt.AWS_KEYSPACES_PASSWD) cluster = Cluster([cnt.CASSANDRA_URL], ssl_context=ssl_context, auth_provider=auth_provider, port=cnt.CASSANDRA_PORT) else: cluster = Cluster(['127.0.0.1'], port=9042) return cluster
def get_keyspaces_cluster() -> Cluster: ssl_context = SSLContext(PROTOCOL_TLSv1_2) ssl_context.load_verify_locations(config["keyspaces"]["cert_path"]) ssl_context.verify_mode = CERT_REQUIRED auth_provider = PlainTextAuthProvider( username=config["keyspaces"]["username"], password=config["keyspaces"]["password"], ) cluster = Cluster( [config["keyspaces"]["cluster_url"]], ssl_context=ssl_context, auth_provider=auth_provider, port=9142, connect_timeout=30, control_connection_timeout=15, ) return cluster
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.5+ / 3.4+') # pylint: disable=no-name-in-module,import-outside-toplevel from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module,import-outside-toplevel ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module,import-outside-toplevel from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 9)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.9+ / 3.4+') # pylint: disable=no-name-in-module from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) # Py32 raises IOError # Py33 raises FileNotFoundError except Exception as e: # Reraise as SSLError raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return (context, context.wrap_socket(sock, server_hostname=server_hostname)) return (context, context.wrap_socket(sock))
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None, server_hostname=None, ssl_version=PROTOCOL_SSLv23): """ All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate """ context = SSLContext(ssl_version) context.verify_mode = cert_reqs if ca_certs: try: context.load_verify_locations(ca_certs) except TypeError as e: # Reraise as SSLError # FIXME: This block needs a test. raise SSLError(e) if certfile: # FIXME: This block needs a test. context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, ca_certs, cert_reqs = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. ctx = SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ctx, "options"): # Explicitly disable SSLv2 and SSLv3. Note that up to # date versions of MongoDB 2.4 and above already do this, # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4 # and SSLv3 in >= 3.4.3. There is no way for us to do this # explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) if certfile is not None: ctx.load_cert_chain(certfile, keyfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
def get_ssl_context(*args): """Create and return an SSLContext object.""" certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating # PROTOCOL_SSLv23. ctx = SSLContext( getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23)) # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4. # PROTOCOL_TLS_CLIENT enables it by default. Using it # requires passing server_hostname to wrap_socket, which we already # do for SNI support. To support older versions of Python we have to # call match_hostname directly, so we disable check_hostname explicitly # to avoid calling match_hostname twice. if hasattr(ctx, "check_hostname"): ctx.check_hostname = False if hasattr(ctx, "options"): # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that # up to date versions of MongoDB 2.4 and above already disable # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7 # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do # any of this explicitly for python 2.6 or 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) # OpenSSL >= 1.0.0 ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0) if certfile is not None: try: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) except ssl.SSLError as exc: raise ConfigurationError( "Private key doesn't match certificate: %s" % (exc,)) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs return ctx
def get_ssl_context(*args): """Create and return an SSLContext object.""" (certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile, match_hostname) = args verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs # Note PROTOCOL_SSLv23 is about the most misleading name imaginable. # This configures the server and client to negotiate the # highest protocol version they both support. A very good thing. # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating # PROTOCOL_SSLv23. ctx = SSLContext( getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23)) # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4. # PROTOCOL_TLS_CLIENT (added in Python 3.6) enables it by default. if hasattr(ctx, "check_hostname"): if _PY37PLUS and verify_mode != ssl.CERT_NONE: # Python 3.7 uses OpenSSL's hostname matching implementation # making it the obvious version to start using this with. # Python 3.6 might have been a good version, but it suffers # from https://bugs.python.org/issue32185. # We'll use our bundled match_hostname for older Python # versions, which also supports IP address matching # with Python < 3.5. ctx.check_hostname = match_hostname else: ctx.check_hostname = False if hasattr(ctx, "options"): # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that # up to date versions of MongoDB 2.4 and above already disable # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7 # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do # any of this explicitly for python 2.7 before 2.7.9. ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0) ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0) # OpenSSL >= 1.0.0 ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0) # Python 3.7+ with OpenSSL >= 1.1.0h ctx.options |= getattr(ssl, "OP_NO_RENEGOTIATION", 0) if certfile is not None: try: if passphrase is not None: vi = sys.version_info # Since python just added a new parameter to an existing method # this seems to be about the best we can do. if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi < (3, 3)): raise ConfigurationError( "Support for ssl_pem_passphrase requires " "python 2.7.9+ (pypy 2.5.1+) or 3.3+") ctx.load_cert_chain(certfile, keyfile, passphrase) else: ctx.load_cert_chain(certfile, keyfile) except ssl.SSLError as exc: raise ConfigurationError( "Private key doesn't match certificate: %s" % (exc,)) if crlfile is not None: if not hasattr(ctx, "verify_flags"): raise ConfigurationError( "Support for ssl_crlfile requires " "python 2.7.9+ (pypy 2.5.1+) or 3.4+") # Match the server's behavior. ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.load_verify_locations(crlfile) if ca_certs is not None: ctx.load_verify_locations(ca_certs) elif cert_reqs != ssl.CERT_NONE: # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1 if hasattr(ctx, "load_default_certs"): ctx.load_default_certs() # Python >= 3.2.0, useless on Windows. elif (sys.platform != "win32" and hasattr(ctx, "set_default_verify_paths")): ctx.set_default_verify_paths() elif sys.platform == "win32" and HAVE_WINCERTSTORE: with _WINCERTSLOCK: if _WINCERTS is None: _load_wincerts() ctx.load_verify_locations(_WINCERTS.name) elif HAVE_CERTIFI: ctx.load_verify_locations(certifi.where()) else: raise ConfigurationError( "`ssl_cert_reqs` is not ssl.CERT_NONE and no system " "CA certificates could be loaded. `ssl_ca_certs` is " "required.") ctx.verify_mode = verify_mode return ctx