Python ssl.OP_NO_TLSv1() Examples

The following are 27 code examples of ssl.OP_NO_TLSv1(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: __init__.py    From addon with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.ssl_context = kwargs.pop('ssl_context', None)
        self.cipherSuite = kwargs.pop('cipherSuite', None)
        self.source_address = kwargs.pop('source_address', None)

        if self.source_address:
            if isinstance(self.source_address, str):
                self.source_address = (self.source_address, 0)

            if not isinstance(self.source_address, tuple):
                raise TypeError(
                    "source_address must be IP address string or (ip, port) tuple"
                )

        if not self.ssl_context:
            self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            self.ssl_context.set_ciphers(self.cipherSuite)
            self.ssl_context.set_ecdh_curve('prime256v1')
            self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)

        super(CipherSuiteAdapter, self).__init__(**kwargs)

    # ------------------------------------------------------------------------------- # 
Example #2
Source File: cloudscraper.py    From a4kScrapers with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.ssl_context = kwargs.pop('ssl_context', None)
        self.cipherSuite = kwargs.pop('cipherSuite', None)
        self.source_address = kwargs.pop('source_address', None)

        if self.source_address:
            if isinstance(self.source_address, str):
                self.source_address = (self.source_address, 0)

            if not isinstance(self.source_address, tuple):
                raise TypeError(
                    "source_address must be IP address string or (ip, port) tuple"
                )

        if not self.ssl_context:
            self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            self.ssl_context.set_ciphers(self.cipherSuite)
            self.ssl_context.set_ecdh_curve('prime256v1')
            self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)

        super(CipherSuiteAdapter, self).__init__(**kwargs)

    # ------------------------------------------------------------------------------- # 
Example #3
Source File: client.py    From grpclib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_default_ssl_context(self) -> '_ssl.SSLContext':
        if _ssl is None:
            raise RuntimeError('SSL is not supported.')

        try:
            import certifi
        except ImportError:
            cafile = None
        else:
            cafile = certifi.where()

        ctx = _ssl.create_default_context(
            purpose=_ssl.Purpose.SERVER_AUTH,
            cafile=cafile,
        )
        ctx.options |= (_ssl.OP_NO_TLSv1 | _ssl.OP_NO_TLSv1_1)
        ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20')
        ctx.set_alpn_protocols(['h2'])
        try:
            ctx.set_npn_protocols(['h2'])
        except NotImplementedError:
            pass

        return ctx 
Example #4
Source File: connection.py    From th2c with MIT License 6 votes vote down vote up
def parse_ssl_opts(self):
        """
        Parses ssl options and creates a SSLContext if self.secure is True.
        """
        if not self.secure:
            return

        ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        ssl_context.options |= ssl.OP_NO_TLSv1
        ssl_context.options |= ssl.OP_NO_TLSv1_1

        if not self.ssl_options.get('verify_certificate', True):
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE

        if self.ssl_options.get('key') and self.ssl_options.get('cert'):
            ssl_context.load_cert_chain(
                self.ssl_options.get('cert'),
                keyfile=self.ssl_options.get('key')
            )

        ssl_context.set_ciphers('ECDHE+AESGCM')
        ssl_context.set_alpn_protocols(AlPN_PROTOCOLS)

        self.ssl_context = ssl_context 
Example #5
Source File: parallel.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def conn(self):
        try:
            if self.ssl:
                ctx = ssl.SSLContext()
                ctx.verify_mode = ssl.CERT_NONE
                ctx.check_hostname = False
                ctx.options |= (
                    ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
                )  # RFC 7540 Section 9.2: MUST be TLS >=1.2
                ctx.options |= ssl.OP_NO_COMPRESSION  # RFC 7540 Section 9.2.1: MUST disable compression
                ctx.load_default_certs()
                self.client_stream = await trio.open_ssl_over_tcp_stream(self.host, self.port, ssl_context=ctx)
            else:
                self.client_stream = await trio.open_tcp_stream(self.host, self.port)
        except OSError as exc:
            raise BUIserverException(str(exc))

        self.logger.debug('Connected')
        self.connected = True
        return self.client_stream 
Example #6
Source File: parallel.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def conn(self):
        try:
            if self.ssl:
                ctx = ssl.SSLContext()
                ctx.verify_mode = ssl.CERT_NONE
                ctx.check_hostname = False
                ctx.options |= (
                    ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
                )  # RFC 7540 Section 9.2: MUST be TLS >=1.2
                ctx.options |= ssl.OP_NO_COMPRESSION  # RFC 7540 Section 9.2.1: MUST disable compression
                ctx.load_default_certs()
                self.client_stream = await trio.open_ssl_over_tcp_stream(self.host, self.port, ssl_context=ctx)
            else:
                self.client_stream = await trio.open_tcp_stream(self.host, self.port)
        except OSError as exc:
            raise BUIserverException(str(exc))

        self.logger.debug('Connected')
        self.connected = True
        return self.client_stream 
Example #7
Source File: parallel.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def conn(self):
        try:
            if self.ssl:
                ctx = ssl.SSLContext()
                ctx.verify_mode = ssl.CERT_NONE
                ctx.check_hostname = False
                ctx.options |= (
                    ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
                )  # RFC 7540 Section 9.2: MUST be TLS >=1.2
                ctx.options |= ssl.OP_NO_COMPRESSION  # RFC 7540 Section 9.2.1: MUST disable compression
                ctx.load_default_certs()
                self.client_stream = await trio.open_ssl_over_tcp_stream(self.host, self.port, ssl_context=ctx)
            else:
                self.client_stream = await trio.open_tcp_stream(self.host, self.port)
        except OSError as exc:
            raise BUIserverException(str(exc))

        self.logger.debug('Connected')
        self.connected = True
        return self.client_stream 
Example #8
Source File: websocket.py    From jellyfin-kodi with GNU General Public License v3.0 6 votes vote down vote up
def _wrap_sni_socket(sock, sslopt, hostname):
    context = ssl.SSLContext(sslopt.get('ssl_version', ssl.PROTOCOL_TLS))
    context.options |= ssl.OP_NO_SSLv2  # Explicitly disable SSLv2
    context.options |= ssl.OP_NO_SSLv3  # Explicitly disable SSLv3
    context.options |= ssl.OP_NO_TLSv1  # Explicitly disable TLSv1.0
    context.options |= ssl.OP_NO_TLSv1_1  # Explicitly disable TLSv1.1

    if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE:
        capath = ssl.get_default_verify_paths().capath
        context.load_verify_locations(
            cafile=sslopt.get('ca_certs', None),
            capath=sslopt.get('ca_cert_path', capath)
        )

    return context.wrap_socket(
        sock,
        do_handshake_on_connect=sslopt.get('do_handshake_on_connect', True),
        suppress_ragged_eofs=sslopt.get('suppress_ragged_eofs', True),
        server_hostname=hostname,
    ) 
Example #9
Source File: __init__.py    From script.module.openscrapers with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.ssl_context = kwargs.pop('ssl_context', None)
        self.cipherSuite = kwargs.pop('cipherSuite', None)
        self.source_address = kwargs.pop('source_address', None)

        if self.source_address:
            if isinstance(self.source_address, str):
                self.source_address = (self.source_address, 0)

            if not isinstance(self.source_address, tuple):
                raise TypeError(
                    "source_address must be IP address string or (ip, port) tuple"
                )

        if not self.ssl_context:
            self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            self.ssl_context.set_ciphers(self.cipherSuite)
            self.ssl_context.set_ecdh_curve('prime256v1')
            self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)

        super(CipherSuiteAdapter, self).__init__(**kwargs)

    # ------------------------------------------------------------------------------- # 
Example #10
Source File: client_https_setup_fragment.py    From hyper-h2 with MIT License 5 votes vote down vote up
def get_http2_ssl_context():
    """
    This function creates an SSLContext object that is suitably configured for
    HTTP/2. If you're working with Python TLS directly, you'll want to do the
    exact same setup as this function does.
    """
    # Get the basic context from the standard library.
    ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)

    # RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
    # or higher. Disable TLS 1.1 and lower.
    ctx.options |= (
        ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
    )

    # RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
    # compression.
    ctx.options |= ssl.OP_NO_COMPRESSION

    # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
    # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
    # blocklist defined in this section allows only the AES GCM and ChaCha20
    # cipher suites with ephemeral key negotiation.
    ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")

    # We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
    # be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
    ctx.set_alpn_protocols(["h2", "http/1.1"])

    try:
        ctx.set_npn_protocols(["h2", "http/1.1"])
    except NotImplementedError:
        pass

    return ctx 
Example #11
Source File: FederatedHook.py    From federated-averaging-tutorials with Apache License 2.0 5 votes vote down vote up
def _start_socket_worker(self):
        """Creates a socket with ssl protection that will act as client.
           Returns:
              sever_socket (socket): ssl secured socket that will work as client.
         """
        to_wrap_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1  # optional

        client_socket = ssl.wrap_socket(to_wrap_socket)
        client_socket.connect((self._public_ip, self._public_port))
        return client_socket 
Example #12
Source File: FederatedHook.py    From federated-averaging-tutorials with Apache License 2.0 5 votes vote down vote up
def _start_socket_server(self):
        """Creates a socket with ssl protection that will act as server.
            Returns:
              sever_socket (socket): ssl secured socket that will act as server.
         """
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1  # optional
        context.set_ciphers('EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH')
        server_socket.bind((self._private_ip, self._private_port))
        server_socket.listen()
        return server_socket 
Example #13
Source File: NMOSTesting.py    From nmos-testing with Apache License 2.0 5 votes vote down vote up
def start_web_servers():
    ctx = None
    if CONFIG.ENABLE_HTTPS:
        # ssl.create_default_context() provides options that broadly correspond to the requirements of BCP-003-01
        ctx = ssl.create_default_context()
        for cert, key in zip(CONFIG.CERTS_MOCKS, CONFIG.KEYS_MOCKS):
            ctx.load_cert_chain(cert, key)
        # additionally disable TLS v1.0 and v1.1
        ctx.options &= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
        # BCP-003-01 however doesn't require client certificates, so disable those
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

    web_threads = []
    for app in FLASK_APPS:
        port = app.config['PORT']
        secure = app.config['SECURE']
        t = threading.Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': port, 'threaded': True,
                                                     'ssl_context': ctx if secure else None,
                                                     'request_handler': PortLoggingHandler})
        t.daemon = True
        t.start()
        web_threads.append(t)

    # Wait for all threads to get going
    time.sleep(1)
    for thread in web_threads:
        if not thread.is_alive():
            print(" * ERROR: One or more web servers could not start. The port may already be in use")
            sys.exit(ExitCodes.ERROR) 
Example #14
Source File: session.py    From smartsheet-python-sdk with Apache License 2.0 5 votes vote down vote up
def create_ssl_context(self):
        ctx = ssl.create_default_context()
        ctx.options |= ssl.OP_NO_SSLv2
        ctx.options |= ssl.OP_NO_SSLv3
        ctx.options |= ssl.OP_NO_TLSv1
        return ctx 
Example #15
Source File: config.py    From opendrop with GNU General Public License v3.0 5 votes vote down vote up
def get_ssl_context(self):
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)  # lgtm[py/insecure-protocol], TODO see https://github.com/Semmle/ql/issues/2554
        ctx.options |= ssl.OP_NO_TLSv1  # TLSv1.0 is insecure
        ctx.load_cert_chain(self.cert_file, keyfile=self.key_file)
        ctx.load_verify_locations(cafile=self.root_ca_file)
        ctx.verify_mode = ssl.CERT_NONE  # we accept self-signed certificates as does Apple
        return ctx 
Example #16
Source File: __init__.py    From PyExfil with MIT License 5 votes vote down vote up
def Send(self, data_to_send):
		certs = []

		data_to_send = bytes(data_to_send, 'ascii')

		self._parse_input(input_data=data_to_send)

		for data_packet in self.input_chunks:
			k, c = self._create_cert(serial=data_packet, cn=self.server)
			certs.append([k,c])

		i = 0

		for k, cert in certs:
			i += 1
			open('/tmp/now.pem', 'wb').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))#.decode("utf-8") )
			open('/tmp/now.pem', 'ab').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))#.decode("utf-8") )

			sock = socket.socket()
			sock.bind((self.server, self.port))
			sock.listen(1)

			context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
			context.load_cert_chain(certfile='/tmp/now.pem')
			context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1  # optional
			context.set_ciphers('EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH')

			sys.stdout.write("Serving cert %s.\n" % i)
			ssock, addr = sock.accept()
			try:
				conn = context.wrap_socket(ssock, server_side=True)
				conn.write(b'HTTP/1.1 200 OK\n\n%s' % conn.getpeername()[0].encode())
			except ssl.SSLError as e:
				print(e)
			finally:
				# conn.close()
				sock.close()
				sys.stdout.write("Cert %i out of %i received.\n" % (i, len(certs))) 
Example #17
Source File: Plugwise-2-web.py    From Plugwise-2-py with GNU General Public License v3.0 5 votes vote down vote up
def main():
    try:
        server = ThreadedHTTPServer(('', port), PW2PYwebHandler)
        server.daemon_threads = True
        server.auth = b64encode(credentials)
        if secure:
            if sys.hexversion < 0x02071000:
                #server.socket = ssl.wrap_socket (server.socket, certfile='./server.pem', server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2)
                server.socket = ssl.wrap_socket (server.socket, certfile='./server.pem', server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
            else:
                ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ctx.load_cert_chain(certfile="./server.pem")
                ctx.options |= ssl.OP_NO_TLSv1
                ctx.options |= ssl.OP_NO_TLSv1_1
                ctx.options |= ssl.OP_CIPHER_SERVER_PREFERENCE
                ctx.set_ciphers('ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-SHA384 ECDHE-RSA-AES256-SHA')
                server.socket = ctx.wrap_socket(server.socket, server_side=True)
            
            info('started secure https server at port %d' % (port,))
        else: 
            info('started http server at port %d' % (port,))
        server.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        server.shutdown()
        print "exit after server.shutdown()" 
Example #18
Source File: utils.py    From hass-nabucasa with GNU General Public License v3.0 5 votes vote down vote up
def server_context_modern() -> ssl.SSLContext:
    """Return an SSL context following the Mozilla recommendations.
    TLS configuration follows the best-practice guidelines specified here:
    https://wiki.mozilla.org/Security/Server_Side_TLS
    Modern guidelines are followed.
    """
    context = ssl.SSLContext(ssl.PROTOCOL_TLS)  # pylint: disable=no-member

    context.options |= (
        ssl.OP_NO_SSLv2
        | ssl.OP_NO_SSLv3
        | ssl.OP_NO_TLSv1
        | ssl.OP_NO_TLSv1_1
        | ssl.OP_CIPHER_SERVER_PREFERENCE
    )
    if hasattr(ssl, "OP_NO_COMPRESSION"):
        context.options |= ssl.OP_NO_COMPRESSION

    context.set_ciphers(
        "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
        "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:"
        "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
        "ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:"
        "ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"
    )

    return context 
Example #19
Source File: client.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_secure_context(
    client_cert: Path, client_key: Path, *, trusted: Path,
) -> ssl.SSLContext:
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
    ctx.verify_mode = ssl.CERT_REQUIRED
    ctx.load_cert_chain(str(client_cert), str(client_key))
    ctx.load_verify_locations(str(trusted))
    ctx.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
    ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20')
    ctx.set_alpn_protocols(['h2'])
    try:
        ctx.set_npn_protocols(['h2'])
    except NotImplementedError:
        pass
    return ctx 
Example #20
Source File: server.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_secure_context(
    server_cert: Path, server_key: Path, *, trusted: Path,
) -> ssl.SSLContext:
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
    ctx.verify_mode = ssl.CERT_REQUIRED
    ctx.load_cert_chain(str(server_cert), str(server_key))
    ctx.load_verify_locations(str(trusted))
    ctx.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
    ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20')
    ctx.set_alpn_protocols(['h2'])
    try:
        ctx.set_npn_protocols(['h2'])
    except NotImplementedError:
        pass
    return ctx 
Example #21
Source File: test_config.py    From hypercorn with MIT License 5 votes vote down vote up
def test_create_ssl_context() -> None:
    path = os.path.join(os.path.dirname(__file__), "assets/config_ssl.py")
    config = Config.from_pyfile(path)
    context = config.create_ssl_context()
    assert context.options & (
        ssl.OP_NO_SSLv2
        | ssl.OP_NO_SSLv3
        | ssl.OP_NO_TLSv1
        | ssl.OP_NO_TLSv1_1
        | ssl.OP_NO_COMPRESSION
    ) 
Example #22
Source File: stats.py    From rpisurv with GNU General Public License v2.0 5 votes vote down vote up
def send_stats(version, uniqid, runtime):
    #Because this is run as a subprocess we need to start logging again
    logger_send_stats = setup_logging(logfilepath="logs/send_stats.log",loggername="send_stats")

    destination="https://statscollector.rpisurv.net"

    #SSL options
    context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile="core/util/statscollector.rpisurv.net.pem")
    #Force TLS higher then 1.1
    context.options |= ssl.OP_NO_SSLv2
    context.options |= ssl.OP_NO_SSLv3
    context.options |= ssl.OP_NO_TLSv1
    context.options |= ssl.OP_NO_TLSv1_1
    #Normally this has been set by ssl.Purpose.SERVER_AUTH but for safety in future explicitly set CERT_REQUIRED
    context.verify_mode = ssl.CERT_REQUIRED
    httpshandler = urllib2.HTTPSHandler(context=context)

    opener = urllib2.build_opener(httpshandler)
    opener.addheaders=[
        ('User-Agent', uniqid),
        ('Pragma', 'no-cache'),
        ('Cache-Control', 'no-cache')
    ]
    #Extra info will be send via cookie headers
    #opener.addheaders.append(('Cookie', 'runtime='+ runtime + ';reservedkey=reservedvalue'))
    opener.addheaders.append(('Cookie', 'runtime='+ runtime + ';version='+ str(version)  ))

    urllib2.install_opener(opener)

    #f = opener.open("http://httpbin.org/cookies")
    logger_send_stats.debug("Start sending uniqid " + uniqid + ", runtime " + runtime + ", version " + str(version) + " to " + destination + " for updating stats rpisurv community")
    try:
        response = opener.open(destination, timeout=20)
    except urllib2.HTTPError, e:
        logger_send_stats.error("There was an error connecting to the statistics server at " + destination + ". Failed with code " + str(e.code)) 
Example #23
Source File: tornado-server.py    From hyper-h2 with MIT License 5 votes vote down vote up
def create_ssl_context(certfile, keyfile):
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.options |= (
        ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION
    )
    ssl_context.set_ciphers("ECDHE+AESGCM")
    ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile)
    ssl_context.set_alpn_protocols(["h2"])
    return ssl_context 
Example #24
Source File: server_https_setup_fragment.py    From hyper-h2 with MIT License 5 votes vote down vote up
def get_http2_ssl_context():
    """
    This function creates an SSLContext object that is suitably configured for
    HTTP/2. If you're working with Python TLS directly, you'll want to do the
    exact same setup as this function does.
    """
    # Get the basic context from the standard library.
    ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)

    # RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
    # or higher. Disable TLS 1.1 and lower.
    ctx.options |= (
        ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
    )

    # RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
    # compression.
    ctx.options |= ssl.OP_NO_COMPRESSION

    # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
    # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
    # blocklist defined in this section allows only the AES GCM and ChaCha20
    # cipher suites with ephemeral key negotiation.
    ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")

    # We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
    # be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
    ctx.set_alpn_protocols(["h2", "http/1.1"])

    try:
        ctx.set_npn_protocols(["h2", "http/1.1"])
    except NotImplementedError:
        pass

    return ctx 
Example #25
Source File: ssl_utils.py    From ansible-kafka-admin with Apache License 2.0 4 votes vote down vote up
def generate_ssl_context(ssl_check_hostname,
                         ssl_cafile,
                         ssl_certfile,
                         ssl_keyfile,
                         ssl_password,
                         ssl_crlfile,
                         ssl_supported_protocols,
                         ssl_ciphers):
    """
    Generate SSLContext for kafka client.
    """
    log.debug('Configuring default SSL Context')
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ssl_context.options |= ssl.OP_NO_SSLv2
    ssl_context.options |= ssl.OP_NO_SSLv3
    ssl_context.verify_mode = ssl.CERT_OPTIONAL
    if ssl_supported_protocols:
        if 'TLSv1' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1
        if 'TLSv1.1' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1_1
        if 'TLSv1.2' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1_2
    if ssl_check_hostname:
        ssl_context.check_hostname = True
    if ssl_cafile:
        log.info('Loading SSL CA from %s', ssl_cafile)
        ssl_context.load_verify_locations(ssl_cafile)
        ssl_context.verify_mode = ssl.CERT_REQUIRED
    else:
        log.info('Loading system default SSL CAs from %s',
                 ssl.get_default_verify_paths())
        ssl_context.load_default_certs()
    if ssl_certfile and ssl_keyfile:
        log.info('Loading SSL Cert from %s', ssl_certfile)
        log.info('Loading SSL Key from %s', ssl_keyfile)
        ssl_context.load_cert_chain(
            certfile=ssl_certfile,
            keyfile=ssl_keyfile,
            password=ssl_password)
    if ssl_crlfile:
        if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'):
            raise RuntimeError('This version of Python does not'
                               ' support ssl_crlfile!')
        log.info('Loading SSL CRL from %s', ssl_crlfile)
        ssl_context.load_verify_locations(ssl_crlfile)
        ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
    if ssl_ciphers:
        log.info('Setting SSL Ciphers: %s', ssl_ciphers)
        ssl_context.set_ciphers(ssl_ciphers)
    return ssl_context 
Example #26
Source File: messageHubProduce.py    From openwhisk-package-kafka with Apache License 2.0 4 votes vote down vote up
def getProducer(validatedParams, timeout_ms):
    connectionHash = getConnectionHash(validatedParams)

    if globals().get("cached_producers") is None:
        logging.info("dictionary was None")
        globals()["cached_producers"] = dict()

    # remove arbitrary connection to make room for new one
    if len(globals()["cached_producers"]) == max_cached_producers:
        poppedProducer = globals()["cached_producers"].popitem()[1]
        poppedProducer.close(timeout=1)
        logging.info("Removed cached producer")

    if connectionHash not in globals()["cached_producers"]:
        logging.info("cache miss")
        # create a new connection
        sasl_mechanism = 'PLAIN'
        security_protocol = 'SASL_SSL'

        # Create a new context using system defaults, disable all but TLS1.2
        context = ssl.create_default_context()
        context.options &= ssl.OP_NO_TLSv1
        context.options &= ssl.OP_NO_TLSv1_1

        producer = KafkaProducer(
            api_version=(0, 10),
            batch_size=0,
            bootstrap_servers=validatedParams['kafka_brokers_sasl'],
            max_block_ms=timeout_ms,
            request_timeout_ms=timeout_ms,
            sasl_plain_username=validatedParams['user'],
            sasl_plain_password=validatedParams['password'],
            security_protocol=security_protocol,
            ssl_context=context,
            sasl_mechanism=sasl_mechanism
        )

        logging.info("Created producer")

        # store the producer globally for subsequent invocations
        globals()["cached_producers"][connectionHash] = producer

        # return it
        return producer
    else:
        logging.info("Reusing existing producer")
        return globals()["cached_producers"][connectionHash] 
Example #27
Source File: parser.py    From alertR with GNU Affero General Public License v3.0 4 votes vote down vote up
def configure_server(configRoot: xml.etree.ElementTree.Element, global_data: GlobalData) -> bool:

    # Get server configurations
    try:
        global_data.logger.debug("[%s]: Parsing server configuration." % fileName)
        global_data.serverCertFile = make_path(str(configRoot.find("general").find("server").attrib["certFile"]))
        global_data.serverKeyFile = make_path(str(configRoot.find("general").find("server").attrib["keyFile"]))
        global_data.server_port = int(configRoot.find("general").find("server").attrib["port"])

    except Exception:
        global_data.logger.exception("[%s]: Configuring server failed." % log_tag)
        return False

    if os.path.exists(global_data.serverCertFile) is False or os.path.exists(global_data.serverKeyFile) is False:
        global_data.logger.error("[%s]: Server certificate or key does not exist." % log_tag)
        return False

    # get client configurations
    try:
        global_data.useClientCertificates = (str(configRoot.find("general").find("client").attrib[
                                                     "useClientCertificates"]).upper() == "TRUE")

    except Exception:
        global_data.logger.exception("[%s]: Configuring client certificate failed." % log_tag)
        return False

    if global_data.useClientCertificates is True:
        global_data.clientCAFile = make_path(str(configRoot.find("general").find("client").attrib["clientCAFile"]))

        if os.path.exists(global_data.clientCAFile) is False:
            global_data.logger.error("[%s]: Client CA file does not exist." % log_tag)
            return False

    # Get TLS/SSL configurations.
    try:
        noSSLv2 = (str(configRoot.find("general").find("ssl").attrib["noSSLv2"]).upper() == "TRUE")
        noSSLv3 = (str(configRoot.find("general").find("ssl").attrib["noSSLv3"]).upper() == "TRUE")
        noTLSv1_0 = (str(configRoot.find("general").find("ssl").attrib["noTLSv1_0"]).upper() == "TRUE")
        noTLSv1_1 = (str(configRoot.find("general").find("ssl").attrib["noTLSv1_1"]).upper() == "TRUE")
        noTLSv1_2 = (str(configRoot.find("general").find("ssl").attrib["noTLSv1_2"]).upper() == "TRUE")

        if noSSLv2:
            global_data.sslOptions |= ssl.OP_NO_SSLv2
        if noSSLv3:
            global_data.sslOptions |= ssl.OP_NO_SSLv3
        if noTLSv1_0:
            global_data.sslOptions |= ssl.OP_NO_TLSv1
        if noTLSv1_1:
            global_data.sslOptions |= ssl.OP_NO_TLSv1_1
        if noTLSv1_2:
            global_data.sslOptions |= ssl.OP_NO_TLSv1_2

    except Exception:
        global_data.logger.exception("[%s]: Configuring TLS/SSL failed." % log_tag)
        return False

    return True