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)
async def wrap_connection(self, packet: bytes, up: AbstractAioSocket, down: AbstractAioSocket, loop: AbstractEventLoop) -> \ Tuple[AbstractAioSocket, AbstractAioSocket]: print("Wrapping connection...") # TODO: What to do, if sni returns 'None'? sni = get_sni_from_handshake(packet) print("Wrapping Server") new_down: AbstractAioSocket = AioTlsSocket( down, _create_unverified_context(PROTOCOL_SSLv23), server_hostname=sni, loop=loop) await new_down.handshake() certificate_file = self.certificate_manager.get_certificate(sni) ctx = SSLContext(PROTOCOL_SSLv23) ctx.set_ciphers(self.ciphers) ctx.load_cert_chain( certificate_file, certificate_file, self.certificate_manager.get_certificate_password()) print("Wrapping Client") new_up = AioTlsSocket(up, ctx, True, loop=loop) new_up.push_data(packet) await new_up.handshake() print("Done") return new_up, new_down
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 server(socket_enabled, server_cert_file, server_key_file): """Run test https server.""" context = SSLContext() context.load_cert_chain(server_cert_file, server_key_file) with pytest_httpserver.HTTPServer(ssl_context=context) as server: server.expect_request('/').respond_with_json({'foo': 'bar'}) yield server
def ssl(self, cert: str = None) -> SSLContext: ssl = SSLContext(PROTOCOL_TLSv1_2) if cert is None: ssl.sni_callback = self.sni else: ssl.load_cert_chain(cert) return ssl
def get_cassandra_session(host, port, user, password, ssl_cert, ssl_key, ssl_v1=False): """Establish Cassandra connection and return session object.""" if ssl_cert is None and ssl_key is None: # skip setting up ssl ssl_context = None else: if ssl_v1: tls_version = PROTOCOL_TLSv1 else: tls_version = PROTOCOL_TLSv1_2 ssl_context = SSLContext(tls_version) ssl_context.load_cert_chain(certfile=ssl_cert, keyfile=ssl_key) auth_provider = PlainTextAuthProvider(username=user, password=password) cluster = Cluster([host], port=port, ssl_context=ssl_context, auth_provider=auth_provider) try: session = cluster.connect() except Exception as e: print("Exception when connecting to Cassandra: {}".format(e.args[0])) sys.exit(1) return session
def validate_cert_file(cert_file): """ Parameters ---------- cert_file: str Path to the certfile to be checked. Raises ------ InvalidCertificateError If the certificate is not valid. """ cert_file = os.path.abspath(cert_file) try: context = SSLContext(PROTOCOL_TLS) context.load_cert_chain(cert_file) except SSLError as e: raise InvalidCertificateError("The certificate {}, you tried to use is not valid. " "Please make sure to use a working certificate or " "leave it unconfigured to use the default certificate. " "Details: {}" "".format(cert_file, e))
def run_risk_level_api(configs): flask_app = _create_risk_level_flask_app(configs) port = int( get_user_defined_configuration(configs.user_config, "api_port", 5000)) host = get_user_defined_configuration(configs.user_config, "host", "0.0.0.0") flask_only = get_user_defined_configuration(configs.user_config, "flask_only", False) http_only = get_user_defined_configuration(configs.user_config, "http_only", False) logging.info("Risk Level API Started...") ssl_context = None if not http_only: ssl_context = SSLContext(PROTOCOL_TLSv1_2) ssl_context.load_cert_chain( certfile=configs.user_config["ssl_certfile"], keyfile=configs.user_config["ssl_keyfile"], password=configs.user_config["ssl_password"], ) if flask_only: flask_app.run(host=host, port=port, ssl_context=ssl_context) else: if ssl_context: http_server = WSGIServer((host, port), flask_app, ssl_context=ssl_context) else: http_server = WSGIServer((host, port), flask_app) http_server.serve_forever()
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 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 __connectIMAPSSL(self, host, port, user, password, certfile=None, keyfile=None, sslpassword=None): ''' return { 'code':CODE_, 'message':'' } ''' outputMessage = { 'code':IMAPConnect.CODE_FAIL, 'message':None } try: sslContext = None if certfile and keyfile: sslContext = SSLContext() sslContext.load_cert_chain(certfile, keyfile, sslpassword) self.__imap = IMAPSSLObject(host, port, ssl_context=sslContext, timeout=3) self.__imap.login(user, password) outputMessage['code'] = IMAPConnect.CODE_OK outputMessage['message'] = 'Success connected to {} {}'.format(host, port) except Exception as ex: outputMessage['message'] = 'Failed {}'.format(ex) return outputMessage
class APNsCertConnectionPool(APNsBaseConnectionPool): def __init__(self, cert_file, max_connections=10, loop=None, use_sandbox=False): self.cert_file = cert_file self.ssl_context = SSLContext() self.ssl_context.load_cert_chain(cert_file) super(APNsCertConnectionPool, self).__init__(max_connections=max_connections, loop=loop, use_sandbox=use_sandbox) with open(self.cert_file, 'rb') as f: body = f.read() cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, body) self.apns_topic = cert.get_subject().UID async def connect(self): _, protocol = await self.loop.create_connection( protocol_factory=partial(self.protocol_class, self.apns_topic, None, self.loop, self.discard_connection), host=self.protocol_class.APNS_SERVER, port=self.protocol_class.APNS_PORT, ssl=self.ssl_context) logger.info('Connection established (total: %d)', len(self.connections) + 1) return protocol
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 run_long_running(params, is_test=False): """ Start the long running server :param params: Demisto params :param is_test: Indicates whether it's test-module run or regular run :return: None """ certificate: str = params.get('certificate', '') private_key: str = params.get('key', '') certificate_path = str() private_key_path = str() try: port = get_params_port(params) ssl_args = dict() if (certificate and not private_key) or (private_key and not certificate): raise DemistoException( 'If using HTTPS connection, both certificate and private key should be provided.' ) if certificate and private_key: certificate_file = NamedTemporaryFile(delete=False) certificate_path = certificate_file.name certificate_file.write(bytes(certificate, 'utf-8')) certificate_file.close() private_key_file = NamedTemporaryFile(delete=False) private_key_path = private_key_file.name private_key_file.write(bytes(private_key, 'utf-8')) private_key_file.close() context = SSLContext(PROTOCOL_TLSv1_2) context.load_cert_chain(certificate_path, private_key_path) ssl_args['ssl_context'] = context demisto.debug('Starting HTTPS Server') else: demisto.debug('Starting HTTP Server') server = WSGIServer(('', port), APP, **ssl_args, log=DEMISTO_LOGGER) if is_test: server_process = Process(target=server.serve_forever) server_process.start() time.sleep(5) server_process.terminate() else: server.serve_forever() except SSLError as e: ssl_err_message = f'Failed to validate certificate and/or private key: {str(e)}' demisto.error(ssl_err_message) raise ValueError(ssl_err_message) except Exception as e: demisto.error(f'An error occurred in long running loop: {str(e)}') raise ValueError(str(e)) finally: if certificate_path: os.unlink(certificate_path) if private_key_path: os.unlink(private_key_path)
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 run(socket_port=None, status_port=None, cert=None, key=None, dhparam=None): """ Run the server. The server always runs with TLS/SSL enabled. Self-signed certificates are included by default and must be trusted by your operating system and browser before use. """ import websockets from aiohttp.web import run_app from asyncio import get_event_loop from ssl import SSLContext, PROTOCOL_TLS_SERVER from .app import app from .frozen import is_frozen, resource_path from .sockets import relay # Set ports app['socket_port'] = socket_port app['status_port'] = status_port # Load SSL Certificate if cert is not None: cert = os.path.realpath(cert) else: cert = resource_path('ssl/server.crt') if not os.path.exists(cert): echo("Internal self-signed public certificate has not been generated. Please " "run `./build_ca_cert` followed by `./build_self_cert`.") if key is not None: key = os.path.realpath(key) else: key = resource_path('ssl/server.key') if not os.path.exists(key): echo("Internal self-signed private key has not been generated. Please " "run `./build_ca_cert` followed by `./build_self_cert`.") if dhparam is not None: dhparam = os.path.realpath(dhparam) else: dhparam = resource_path('ssl/dhparam.pem') if not os.path.exists(key): echo("Internal Diffie-Hellman parameter has not been generated. Please " "run `./build_ca_cert` followed by `./build_self_cert`.") if not os.path.exists(cert): echo(u"Unable to locate certificate: ", cert) if not os.path.exists(key): echo(u"Unable to locate key: ", cert) ssl_context = SSLContext(PROTOCOL_TLS_SERVER) ssl_context.load_cert_chain(cert, key) ssl_context.load_dh_params(dhparam) # Start event loop loop = get_event_loop() loop.run_until_complete(websockets.serve(relay, 'localhost', socket_port, ssl=ssl_context)) loop.call_soon(lambda: print(f"======== WebSockets on https://0.0.0.0:{socket_port} ========")) run_app(app, port=status_port, ssl_context=ssl_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_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 __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 setup_ssl(): config.flask.ssl_context = None if not config.flask.ssl_context: return ssl_flask = config.flask.copy() ssl_flask.debug = False ssl_flask.port = 443 if isinstance(config.flask.ssl_context, Mapping): # EXPECTED PEM ENCODED FILE NAMES # `load_cert_chain` REQUIRES CONCATENATED LIST OF CERTS tempfile = NamedTemporaryFile(delete=False, suffix=".pem") try: tempfile.write( File(ssl_flask.ssl_context.certificate_file).read_bytes()) if ssl_flask.ssl_context.certificate_chain_file: tempfile.write( File(ssl_flask.ssl_context.certificate_chain_file). read_bytes()) tempfile.flush() tempfile.close() context = SSLContext(PROTOCOL_SSLv23) context.load_cert_chain( tempfile.name, keyfile=File(ssl_flask.ssl_context.privatekey_file).abspath) ssl_flask.ssl_context = context except Exception, e: Log.error("Could not handle ssl context construction", cause=e) finally:
def connect_cassandra(self): """ This function will connect to cassandra database and all required connection details will be taken from config.py file """ session = None cluster = None try: ssl_context = SSLContext(PROTOCOL_TLSv1) ssl_context.load_cert_chain(certfile=CERTFILE_FILE_PATH, keyfile=KEYFILE_FILE_PATH) cluster = Cluster(DATABASEIP, ssl_context=ssl_context, load_balancing_policy=RoundRobinPolicy(), control_connection_timeout=None, port=9042, connect_timeout=1000) session = cluster.connect(KEYSPACE) except Exception as ex: logger.error('Failed to connect Cassandra DB : {}'.format( str(ex))) finally: return session, cluster
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)
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): """ 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 __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 main(config_path): # Static directory can be changed here to avoid collisions with underlying app's static directory app = Flask(__name__) USAGE = "Run with --help for options" app.register_blueprint(reverse_proxy) """Read the config""" if not config_path: print(USAGE) exit(1) parse_config(config_path, app) # Set up the app if app.config['debug']: app.logger.setLevel(logging.DEBUG) # Set up SSL if configured to security_context = None if app.config['use_ssl']: cert = app.config['ssl_cert'] key = app.config['ssl_key'] security_context = SSLContext() security_context.load_cert_chain(cert, key) """Run the general modules""" SecurityHeaders(app)() RateLimiter(app)() app.logger.info(f"pyWaf running at 0.0.0.0:{app.config['port']}") http_server = WSGIServer( ('0.0.0.0', app.config['port']), DebuggedApplication(app) if app.config['debug'] else app, ssl_context=security_context) http_server.serve_forever()
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 __init__(self): # Set SSL/TLS context & start dev HTTP server (FYI: This is not a full WSGI) context = SSLContext(SSL_VERSION) context.load_cert_chain(CERT_FILE, KEY_FILE) self.app.run(host='0.0.0.0', port=8443, ssl_context=context, threaded=True)
def __init__(self, server_address, HandlerClass, dir): super().__init__(server_address, HandlerClass, bind_and_activate=False) ctx = SSLContext(PROTOCOL_TLSv1) ctx.load_cert_chain(join(dir, 'server-cert.pem'), join(dir, 'server-key.pem')) # ctx.load_verify_locations(join(dir, 'ca-cert.pem')) self.socket = ctx.wrap_socket(self.socket, server_side=True) self.server_bind() self.server_activate()
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 setup_flask_ssl(flask_app, flask_config): """ SPAWN A NEW THREAD TO RUN AN SSL ENDPOINT REMOVES ssl_context FROM flask_config BEFORE RETURNING :param flask_app: :param flask_config: :return: """ if not flask_config.ssl_context: return ssl_flask = flask_config.copy() ssl_flask.debug = False ssl_flask.port = 443 if is_data(flask_config.ssl_context): # EXPECTED PEM ENCODED FILE NAMES # `load_cert_chain` REQUIRES CONCATENATED LIST OF CERTS with TempFile() as tempfile: try: tempfile.write( File(ssl_flask.ssl_context.certificate_file).read_bytes() ) if ssl_flask.ssl_context.certificate_chain_file: tempfile.write( File(ssl_flask.ssl_context.certificate_chain_file).read_bytes() ) tempfile.flush() tempfile.close() context = SSLContext(PROTOCOL_SSLv23) context.load_cert_chain( tempfile.name, keyfile=File(ssl_flask.ssl_context.privatekey_file).abspath, ) ssl_flask.ssl_context = context except Exception as e: Log.error("Could not handle ssl context construction", cause=e) def runner(please_stop): Log.warning( "ActiveData listening on encrypted port {{port}}", port=ssl_flask.port ) flask_app.run(**ssl_flask) Thread.run("SSL Server", runner) if flask_config.ssl_context and flask_config.port != 80: Log.warning( "ActiveData has SSL context, but is still listening on non-encrypted http port {{port}}", port=flask_config.port, ) flask_config.ssl_context = None
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 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 create_server( callback=None, host='127.0.0.1', port=8000, ssl=None, loop=None, **kargs ): """ This is a function to assist in the creation of a growler HTTP server. @param host str: hostname or ip address on which to bind @param port: the port on which the server will listen @param ssl ssl.SSLContext: The SSLContext for using TLS over the connection @param loop asyncio.BaseEventLoop: The event loop to @param kargs: Extra parameters passed to the HTTPServer instance created. If there is an ssl parameter passed to this function, kargs will require the value 'key' to be present, and an optional 'cert' parameter to pass to load_cert_chain. @return An HTTPServer instance """ loop = asyncio.get_event_loop() if loop is None else loop if ssl: sslctx = SSLContext(ssl.PROTOCOL_SSLv23) key = kargs.pop('key') try: sslctx.load_cert_chain(certfile=kargs.pop('cert'), keyfile=key) except KeyError: sslctx.load_cert_chain(certfile=key) else: sslctx = None # What do I use as a 'callback' here? srv = HTTPServer(cb=callback, loop=loop, ssl=sslctx, host=host, port=port, **kargs ) return srv
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 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)
class SMTPServer(smtpd.SMTPServer): def __init__(self, localaddr, remoteaddr, ssl=False, certfile=None, keyfile=None, ssl_version=ssl.PROTOCOL_SSLv23, require_authentication=False, credential_validator=None, maximum_execution_time=30, process_count=5): smtpd.SMTPServer.__init__(self, localaddr, remoteaddr) self.logger = logging.getLogger( secure_smtpd.LOG_NAME ) self.certfile = certfile self.keyfile = keyfile self.ssl_version = ssl_version self.subprocesses = [] self.require_authentication = require_authentication self.credential_validator = credential_validator self.ssl = ssl self.maximum_execution_time = maximum_execution_time self.process_count = process_count self.process_pool = None self.context = SSLContext(ssl_version) self.context.load_cert_chain(certfile=certfile, keyfile=keyfile) def handle_accept(self): self.process_pool = ProcessPool(self._accept_subprocess, process_count=self.process_count) self.close() def _accept_subprocess(self, queue): while True: try: self.socket.setblocking(1) pair = self.accept() map = {} if pair is not None: self.logger.info('_accept_subprocess(): smtp connection accepted within subprocess.') newsocket, fromaddr = pair newsocket.settimeout(self.maximum_execution_time) if self.ssl: newsocket = self.context.wrap_socket( newsocket, server_side=True, ) channel = SMTPChannel( self, newsocket, fromaddr, require_authentication=self.require_authentication, credential_validator=self.credential_validator, map=map ) self.logger.info('_accept_subprocess(): starting asyncore within subprocess.') asyncore.loop(map=map) self.logger.error('_accept_subprocess(): asyncore loop exited.') except (ExitNow, SSLError): self._shutdown_socket(newsocket) self.logger.info('_accept_subprocess(): smtp channel terminated asyncore.') except Exception as e: self._shutdown_socket(newsocket) self.logger.error('_accept_subprocess(): uncaught exception: %s' % str(e)) def _shutdown_socket(self, s): try: s.shutdown(socket.SHUT_RDWR) s.close() except Exception as e: self.logger.error('_shutdown_socket(): failed to cleanly shutdown socket: %s' % str(e)) def run(self): asyncore.loop() if hasattr(signal, 'SIGTERM'): def sig_handler(signal,frame): self.logger.info("Got signal %s, shutting down." % signal) sys.exit(0) signal.signal(signal.SIGTERM, sig_handler) while 1: time.sleep(1)
from threading import Thread # Pypy compatability try: from ssl import PROTOCOL_TLSv1_2 as PROTOCOL_TLSv1 except ImportError: from ssl import PROTOCOL_TLSv1 as PROTOCOL_TLSv1 run_http = config["insecure"]["enabled"] run_https = config["secure"]["enabled"] if run_https: context = SSLContext(PROTOCOL_TLSv1) context.load_cert_chain( config["secure"]["cert"], config["secure"]["key"] ) if run_http and run_https: if config["debug"]: raise Warning("Cannot run in debug mode with both https and http enabled due to flask limitations.") Thread( target=app.run, kwargs={ "host": config["server"]["address"], "port": config["secure"]["port"], "debug": config["debug"], "ssl_context": context } ).start() Thread(
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
""" CASSH add """ pubkey = request.files['file'] username = request.form['username'] payload = {} payload.update({'realname': current_user['name'], 'password': current_user['password']}) payload.update({'username': username}) payload.update({'pubkey': pubkey.read().decode('UTF-8')}) try: req = put(APP.config['CASSH_URL'] + '/client', \ data=payload, \ headers=APP.config['HEADERS'], \ verify=False) except ConnectionError: return Response('Connection error : %s' % APP.config['CASSH_URL']) if 'Error' in req.text: return Response(req.text) return redirect('/status') @APP.errorhandler(404) def page_not_found(_): """ Display error page """ return render_template('404.html'), 404 if __name__ == '__main__': CONTEXT = SSLContext(PROTOCOL_TLSv1_2) CONTEXT.load_cert_chain(APP.config['SSL_PUB_KEY'], APP.config['SSL_PRIV_KEY']) PORT = int(getenv('PORT', APP.config['PORT'])) APP.run(debug=APP.config['DEBUG'], host='0.0.0.0', port=PORT, ssl_context=CONTEXT)
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