Python ssl.CERT_OPTIONAL Examples

The following are 30 code examples of ssl.CERT_OPTIONAL(). 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: connection.py    From Flask with Apache License 2.0 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                 ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #2
Source File: connection.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None,
                 ssl_cert_reqs='required', ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #3
Source File: connection.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                 ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #4
Source File: test_connection_pool.py    From aredis with MIT License 6 votes vote down vote up
def test_cert_reqs_options(self):
        import ssl
        with pytest.raises(TypeError) as e:
            pool = aredis.ConnectionPool.from_url(
                'rediss://?ssl_cert_reqs=none&ssl_keyfile=test')
            assert e.message == 'certfile should be a valid filesystem path'
            assert pool.get_connection().ssl_context.verify_mode == ssl.CERT_NONE

        with pytest.raises(TypeError) as e:
            pool = aredis.ConnectionPool.from_url(
                'rediss://?ssl_cert_reqs=optional&ssl_keyfile=test')
            assert e.message == 'certfile should be a valid filesystem path'
            assert pool.get_connection().ssl_context.verify_mode == ssl.CERT_OPTIONAL

        with pytest.raises(TypeError) as e:
            pool = aredis.ConnectionPool.from_url(
                'rediss://?ssl_cert_reqs=required&ssl_keyfile=test')
            assert e.message == 'certfile should be a valid filesystem path'
            assert pool.get_connection().ssl_context.verify_mode == ssl.CERT_REQUIRED 
Example #5
Source File: connection.py    From aredis with MIT License 6 votes vote down vote up
def __init__(self, keyfile=None, certfile=None,
                 cert_reqs=None, ca_certs=None):
        self.keyfile = keyfile
        self.certfile = certfile
        if cert_reqs is None:
            self.cert_reqs = ssl.CERT_NONE
        elif isinstance(cert_reqs, str):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    cert_reqs)
            self.cert_reqs = CERT_REQS[cert_reqs]
        self.ca_certs = ca_certs
        self.context = None 
Example #6
Source File: connection.py    From gimel with MIT License 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                 ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #7
Source File: mongo.py    From oslo.cache with Apache License 2.0 6 votes vote down vote up
def _ssl_cert_req_type(self, req_type):
        try:
            import ssl
        except ImportError:
            raise exception.ConfigurationError(_('no ssl support available'))
        req_type = req_type.upper()
        try:
            return {
                'NONE': ssl.CERT_NONE,
                'OPTIONAL': ssl.CERT_OPTIONAL,
                'REQUIRED': ssl.CERT_REQUIRED
            }[req_type]
        except KeyError:
            msg = _('Invalid ssl_cert_reqs value of %s, must be one of '
                    '"NONE", "OPTIONAL", "REQUIRED"') % req_type
            raise exception.ConfigurationError(msg) 
Example #8
Source File: mqtt.py    From thingflow-python with Apache License 2.0 6 votes vote down vote up
def _connect(self):
        if self.server_tls:
            raise Exception("TBD")
            print(self.client.tls_set(self.server_tls.server_cert, cert_reqs=ssl.CERT_OPTIONAL))
            print(self.client.connect(self.host, self.port))
        else:
            self.client.connect(self.host, self.port) 
            self.client.subscribe(self.topics)
   
        def on_connect(client, userdata, flags, rc):
            print("Connected with result code "+str(rc))
        self.client.on_connect = on_connect

        def on_publish(client, userdata, mid):
            print("Successfully published mid %d" % mid)
        self.client.on_publish = on_publish 
Example #9
Source File: connection.py    From revsync with MIT License 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                 ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #10
Source File: connection.py    From satori with Apache License 2.0 6 votes vote down vote up
def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                 ssl_ca_certs=None, **kwargs):
        if not ssl_available:
            raise RedisError("Python wasn't built with SSL support")

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

        self.keyfile = ssl_keyfile
        self.certfile = ssl_certfile
        if ssl_cert_reqs is None:
            ssl_cert_reqs = ssl.CERT_NONE
        elif isinstance(ssl_cert_reqs, basestring):
            CERT_REQS = {
                'none': ssl.CERT_NONE,
                'optional': ssl.CERT_OPTIONAL,
                'required': ssl.CERT_REQUIRED
            }
            if ssl_cert_reqs not in CERT_REQS:
                raise RedisError(
                    "Invalid SSL Certificate Requirements Flag: %s" %
                    ssl_cert_reqs)
            ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
        self.cert_reqs = ssl_cert_reqs
        self.ca_certs = ssl_ca_certs 
Example #11
Source File: __init__.py    From tikapy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _connect(self):
        """
        Connects a ssl socket.
        """
        self._connect_socket()
        try:
            ctx = ssl.create_default_context()
            if not self.verify_cert:
                ctx.verify_mode = ssl.CERT_OPTIONAL
            if not self.verify_addr:
                ctx.check_hostname = False
            self._sock = ctx.wrap_socket(self._base_sock,
                                         server_hostname=self.address)
        except ssl.SSLError:
            LOG.error('could not establish SSL connection')
            raise ClientError('could not establish SSL connection') 
Example #12
Source File: config.py    From karapace with Apache License 2.0 6 votes vote down vote up
def create_ssl_context(config):
    # taken from conn.py, as it adds a lot more logic to the context configuration than the initial version
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)  # pylint: disable=no-member
    ssl_context.options |= ssl.OP_NO_SSLv2  # pylint: disable=no-member
    ssl_context.options |= ssl.OP_NO_SSLv3  # pylint: disable=no-member
    ssl_context.verify_mode = ssl.CERT_OPTIONAL
    if config.get('ssl_check_hostname'):
        ssl_context.check_hostname = True
    if config['ssl_cafile']:
        ssl_context.load_verify_locations(config['ssl_cafile'])
        ssl_context.verify_mode = ssl.CERT_REQUIRED
    if config['ssl_certfile'] and config['ssl_keyfile']:
        ssl_context.load_cert_chain(
            certfile=config['ssl_certfile'], keyfile=config['ssl_keyfile'], password=config.get('ssl_password')
        )
    if config.get('ssl_crlfile'):
        if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'):
            raise RuntimeError('This version of Python does not support ssl_crlfile!')
        ssl_context.load_verify_locations(config['ssl_crlfile'])
        # pylint: disable=no-member
        ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
    if config.get('ssl_ciphers'):
        ssl_context.set_ciphers(config['ssl_ciphers'])
    return ssl_context 
Example #13
Source File: rocket.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def wrap_socket(self, sock):
        try:
            if self.clientcert_req:
                ca_certs = self.interface[4]
                cert_reqs = ssl.CERT_OPTIONAL
                sock = ssl.wrap_socket(sock,
                                       keyfile=self.interface[2],
                                       certfile=self.interface[3],
                                       server_side=True,
                                       cert_reqs=cert_reqs,
                                       ca_certs=ca_certs,
                                       ssl_version=ssl.PROTOCOL_SSLv23)
            else:
                sock = ssl.wrap_socket(sock,
                                       keyfile=self.interface[2],
                                       certfile=self.interface[3],
                                       server_side=True,
                                       ssl_version=ssl.PROTOCOL_SSLv23)
        except SSLError:
            # Generally this happens when an HTTP request is received on a
            # secure socket. We don't do anything because it will be detected
            # by Worker and dealt with appropriately.
            pass

        return sock 
Example #14
Source File: transport.py    From python-logstash-async with MIT License 5 votes vote down vote up
def _create_socket(self):
        if self._sock is not None:
            return

        # from logging.handlers.SocketHandler
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if self._timeout is not TimeoutNotSet:
            self._sock.settimeout(self._timeout)

        try:
            self._sock.connect((self._host, self._port))
            # non-SSL
            if not self._ssl_enable:
                return
            # SSL
            cert_reqs = ssl.CERT_REQUIRED
            if not self._ssl_verify:
                if self._ca_certs:
                    cert_reqs = ssl.CERT_OPTIONAL
                else:
                    cert_reqs = ssl.CERT_NONE
            self._sock = ssl.wrap_socket(
                self._sock,
                keyfile=self._keyfile,
                certfile=self._certfile,
                ca_certs=self._ca_certs,
                cert_reqs=cert_reqs)
        except socket.error:
            self._close()
            raise

    # ---------------------------------------------------------------------- 
Example #15
Source File: ssl_context.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def __get_verify_mode(self):
        """Whether to try to verify other peers' certificates and how to
        behave if verification fails. This attribute must be one of
        ssl.CERT_NONE, ssl.CERT_OPTIONAL or ssl.CERT_REQUIRED.
        """
        return self._verify_mode 
Example #16
Source File: ssl_support.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_cert_reqs(option, value):
        """Validate the cert reqs are valid. It must be None or one of the
        three values ``ssl.CERT_NONE``, ``ssl.CERT_OPTIONAL`` or
        ``ssl.CERT_REQUIRED``.
        """
        if value is None:
            return value
        elif isinstance(value, string_type) and hasattr(ssl, value):
            value = getattr(ssl, value)

        if value in (ssl.CERT_NONE, ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED):
            return value
        raise ValueError("The value of %s must be one of: "
                         "`ssl.CERT_NONE`, `ssl.CERT_OPTIONAL` or "
                         "`ssl.CERT_REQUIRED`" % (option,)) 
Example #17
Source File: ssl_context.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __get_verify_mode(self):
        """Whether to try to verify other peers' certificates and how to
        behave if verification fails. This attribute must be one of
        ssl.CERT_NONE, ssl.CERT_OPTIONAL or ssl.CERT_REQUIRED.
        """
        return self._verify_mode 
Example #18
Source File: ad_users.py    From django_auth_ldap3_ad with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        # check configuration
        if not (hasattr(settings, 'LDAP_SERVERS') and hasattr(settings, 'LDAP_BIND_ADMIN') and
                hasattr(settings, 'LDAP_BIND_ADMIN_PASS') and hasattr(settings, 'LDAP_AD_DOMAIN')
                and hasattr(settings, 'LDAP_CERT_FILE')
                ):
            raise ImproperlyConfigured()

        # first: build server pool from settings
        tls = Tls(validate=ssl.CERT_OPTIONAL, version=ssl.PROTOCOL_TLSv1, ca_certs_file=settings.LDAP_CERT_FILE)

        if self.pool is None:
            self.pool = ServerPool(None, pool_strategy=FIRST, active=True)
            for srv in settings.LDAP_SERVERS:
                # Only add servers that supports SSL, impossible to make changes without
                if srv['use_ssl']:
                    server = Server(srv['host'], srv['port'], srv['use_ssl'], tls=tls)
                    self.pool.add(server)

        # then, try to connect with user/pass from settings
        self.con = Connection(self.pool, auto_bind=True, authentication=SIMPLE,
                              user=settings.LDAP_BIND_ADMIN, password=settings.LDAP_BIND_ADMIN_PASS) 
Example #19
Source File: util.py    From JWTConnect-Python-OidcRP with Apache License 2.0 5 votes vote down vote up
def create_context(dir_path, config, **kwargs):
    _fname = lower_or_upper(config, "server_cert")
    if _fname:
        if _fname.startswith("/"):
            _cert_file = _fname
        else:
            _cert_file = os.path.join(dir_path, _fname)
    else:
        return None

    _fname = lower_or_upper(config, "server_key")
    if _fname:
        if _fname.startswith("/"):
            _key_file = _fname
        else:
            _key_file = os.path.join(dir_path, _fname)
    else:
        return None

    context = ssl.SSLContext(**kwargs)  # PROTOCOL_TLS by default

    _verify_user = lower_or_upper(config, "verify_user")
    if _verify_user:
        if _verify_user == "optional":
            context.verify_mode = ssl.CERT_OPTIONAL
        elif _verify_user == "required":
            context.verify_mode = ssl.CERT_REQUIRED
        else:
            sys.exit("Unknown verify_user specification: '{}'".format(_verify_user))
        _ca_bundle = lower_or_upper(config, "ca_bundle")
        if _ca_bundle:
            context.load_verify_locations(_ca_bundle)
    else:
        context.verify_mode = ssl.CERT_NONE

    try:
        context.load_cert_chain(_cert_file, _key_file)
    except Exception as e:
        sys.exit("Error starting server. Missing cert or key. Details: {}".format(e))

    return context 
Example #20
Source File: iostream.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def _verify_cert(self, peercert: Any) -> bool:
        """Returns ``True`` if peercert is valid according to the configured
        validation mode and hostname.

        The ssl handshake already tested the certificate for a valid
        CA signature; the only thing that remains is to check
        the hostname.
        """
        if isinstance(self._ssl_options, dict):
            verify_mode = self._ssl_options.get("cert_reqs", ssl.CERT_NONE)
        elif isinstance(self._ssl_options, ssl.SSLContext):
            verify_mode = self._ssl_options.verify_mode
        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)
        if verify_mode == ssl.CERT_NONE or self._server_hostname is None:
            return True
        cert = self.socket.getpeercert()
        if cert is None and verify_mode == ssl.CERT_REQUIRED:
            gen_log.warning("No SSL certificate given")
            return False
        try:
            ssl.match_hostname(peercert, self._server_hostname)
        except ssl.CertificateError as e:
            gen_log.warning("Invalid SSL certificate: %s" % e)
            return False
        else:
            return True 
Example #21
Source File: ssl_context.py    From opsbro with MIT License 5 votes vote down vote up
def __get_verify_mode(self):
        """Whether to try to verify other peers' certificates and how to
        behave if verification fails. This attribute must be one of
        ssl.CERT_NONE, ssl.CERT_OPTIONAL or ssl.CERT_REQUIRED.
        """
        return self._verify_mode 
Example #22
Source File: ssl_support.py    From opsbro with MIT License 5 votes vote down vote up
def validate_cert_reqs(option, value):
        """Validate the cert reqs are valid. It must be None or one of the
        three values ``ssl.CERT_NONE``, ``ssl.CERT_OPTIONAL`` or
        ``ssl.CERT_REQUIRED``.
        """
        if value is None:
            return value
        elif isinstance(value, string_type) and hasattr(ssl, value):
            value = getattr(ssl, value)

        if value in (ssl.CERT_NONE, ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED):
            return value
        raise ValueError("The value of %s must be one of: "
                         "`ssl.CERT_NONE`, `ssl.CERT_OPTIONAL` or "
                         "`ssl.CERT_REQUIRED`" % (option,)) 
Example #23
Source File: data.py    From python-sdk with MIT License 5 votes vote down vote up
def set_verify_mode(self, verify_mode=None):
        """
        Set verify_mode of SSL Context:

        ssl.CERT_NONE = 0
        ssl.CERT_OPTIONAL = 1
        ssl.CERT_REQUIRED = 2

        :param verify_mode: verify mode value
        :return
        """
        self._sender_config.verify_mode = verify_mode

    # TODO: Deprecated 
Example #24
Source File: iostream.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def _verify_cert(self, peercert):
        """Returns True if peercert is valid according to the configured
        validation mode and hostname.

        The ssl handshake already tested the certificate for a valid
        CA signature; the only thing that remains is to check
        the hostname.
        """
        if isinstance(self._ssl_options, dict):
            verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE)
        elif isinstance(self._ssl_options, ssl.SSLContext):
            verify_mode = self._ssl_options.verify_mode
        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)
        if verify_mode == ssl.CERT_NONE or self._server_hostname is None:
            return True
        cert = self.socket.getpeercert()
        if cert is None and verify_mode == ssl.CERT_REQUIRED:
            gen_log.warning("No SSL certificate given")
            return False
        try:
            ssl_match_hostname(peercert, self._server_hostname)
        except SSLCertificateError as e:
            gen_log.warning("Invalid SSL certificate: %s" % e)
            return False
        else:
            return True 
Example #25
Source File: __init__.py    From st2 with Apache License 2.0 5 votes vote down vote up
def _get_ssl_kwargs(ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                    ssl_ca_certs=None, authentication_mechanism=None, ssl_match_hostname=True):
    # NOTE: In pymongo 3.9.0 some of the ssl related arguments have been renamed -
    # https://api.mongodb.com/python/current/changelog.html#changes-in-version-3-9-0
    # Old names still work, but we should eventually update to new argument names.
    ssl_kwargs = {
        'ssl': ssl,
    }
    if ssl_keyfile:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['ssl_keyfile'] = ssl_keyfile
    if ssl_certfile:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['ssl_certfile'] = ssl_certfile
    if ssl_cert_reqs:
        if ssl_cert_reqs == 'none':
            ssl_cert_reqs = ssl_lib.CERT_NONE
        elif ssl_cert_reqs == 'optional':
            ssl_cert_reqs = ssl_lib.CERT_OPTIONAL
        elif ssl_cert_reqs == 'required':
            ssl_cert_reqs = ssl_lib.CERT_REQUIRED
        ssl_kwargs['ssl_cert_reqs'] = ssl_cert_reqs
    if ssl_ca_certs:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['ssl_ca_certs'] = ssl_ca_certs
    if authentication_mechanism:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['authentication_mechanism'] = authentication_mechanism
    if ssl_kwargs.get('ssl', False):
        # pass in ssl_match_hostname only if ssl is True. The right default value
        # for ssl_match_hostname in almost all cases is True.
        ssl_kwargs['ssl_match_hostname'] = ssl_match_hostname
    return ssl_kwargs 
Example #26
Source File: utils.py    From st2 with Apache License 2.0 5 votes vote down vote up
def _get_ssl_kwargs(ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
                    ssl_ca_certs=None, login_method=None):
    """
    Return SSL keyword arguments to be used with the kombu.Connection class.
    """
    ssl_kwargs = {}

    # NOTE: If "ssl" is not set to True we don't pass "ssl=False" argument to the constructor
    # because user could still specify to use SSL by including "?ssl=true" query param at the
    # end of the connection URL string
    if ssl is True:
        ssl_kwargs['ssl'] = True

    if ssl_keyfile:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['keyfile'] = ssl_keyfile

    if ssl_certfile:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['certfile'] = ssl_certfile

    if ssl_cert_reqs:
        if ssl_cert_reqs == 'none':
            ssl_cert_reqs = ssl_lib.CERT_NONE
        elif ssl_cert_reqs == 'optional':
            ssl_cert_reqs = ssl_lib.CERT_OPTIONAL
        elif ssl_cert_reqs == 'required':
            ssl_cert_reqs = ssl_lib.CERT_REQUIRED
        ssl_kwargs['cert_reqs'] = ssl_cert_reqs

    if ssl_ca_certs:
        ssl_kwargs['ssl'] = True
        ssl_kwargs['ca_certs'] = ssl_ca_certs

    return ssl_kwargs 
Example #27
Source File: api.py    From patroni with MIT License 5 votes vote down vote up
def __initialize(self, listen, ssl_options):
        try:
            host, port = split_host_port(listen, None)
        except Exception:
            raise ValueError('Invalid "restapi" config: expected <HOST>:<PORT> for "listen", but got "{0}"'
                             .format(listen))

        reloading_config = self.__listen is not None  # changing config in runtime
        if reloading_config:
            self.shutdown()

        self.__listen = listen
        self.__ssl_options = ssl_options

        self.__httpserver_init(host, port)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        self.__protocol = 'https' if ssl_options.get('certfile') else 'http'
        if self.__protocol == 'https':
            import ssl
            ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=ssl_options.get('cafile'))
            ctx.load_cert_chain(certfile=ssl_options['certfile'], keyfile=ssl_options.get('keyfile'))
            verify_client = ssl_options.get('verify_client')
            if verify_client:
                modes = {'none': ssl.CERT_NONE, 'optional': ssl.CERT_OPTIONAL, 'required': ssl.CERT_REQUIRED}
                if verify_client in modes:
                    ctx.verify_mode = modes[verify_client]
                else:
                    logger.error('Bad value in the "restapi.verify_client": %s', verify_client)
            self.socket = ctx.wrap_socket(self.socket, server_side=True)
        if reloading_config:
            self.start() 
Example #28
Source File: ssl_context.py    From satori with Apache License 2.0 5 votes vote down vote up
def __get_verify_mode(self):
        """Whether to try to verify other peers' certificates and how to
        behave if verification fails. This attribute must be one of
        ssl.CERT_NONE, ssl.CERT_OPTIONAL or ssl.CERT_REQUIRED.
        """
        return self._verify_mode 
Example #29
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def _verify_cert(self, peercert):
        """Returns True if peercert is valid according to the configured
        validation mode and hostname.

        The ssl handshake already tested the certificate for a valid
        CA signature; the only thing that remains is to check
        the hostname.
        """
        if isinstance(self._ssl_options, dict):
            verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE)
        elif isinstance(self._ssl_options, ssl.SSLContext):
            verify_mode = self._ssl_options.verify_mode
        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)
        if verify_mode == ssl.CERT_NONE or self._server_hostname is None:
            return True
        cert = self.socket.getpeercert()
        if cert is None and verify_mode == ssl.CERT_REQUIRED:
            gen_log.warning("No SSL certificate given")
            return False
        try:
            ssl_match_hostname(peercert, self._server_hostname)
        except SSLCertificateError as e:
            gen_log.warning("Invalid SSL certificate: %s" % e)
            return False
        else:
            return True 
Example #30
Source File: common.py    From recruit with Apache License 2.0 5 votes vote down vote up
def validate_cert_reqs(option, value):
    """Validate the cert reqs are valid. It must be None or one of the three
    values ``ssl.CERT_NONE``, ``ssl.CERT_OPTIONAL`` or ``ssl.CERT_REQUIRED``"""
    if value is None:
        return value
    if HAS_SSL:
        if value in (ssl.CERT_NONE, ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED):
            return value
        raise ConfigurationError("The value of %s must be one of: "
                                 "`ssl.CERT_NONE`, `ssl.CERT_OPTIONAL` or "
                                 "`ssl.CERT_REQUIRED" % (option,))
    else:
        raise ConfigurationError("The value of %s is set but can't be "
                                 "validated. The ssl module is not available"
                                 % (option,))