Exemplo n.º 1
0
def _convert_exception(e):
    """Convert an ldap backend exception to an LDAPError and raise it."""
    args = ("exception in ldap backend: {0}".format(repr(e)), e)
    if six.PY2:
        six.reraise(LDAPError, args, sys.exc_info()[2])
    else:
        six.raise_from(LDAPError(*args), e)
Exemplo n.º 2
0
Arquivo: ldap3.py Projeto: bryson/salt
def _convert_exception(e):
    """Convert an ldap backend exception to an LDAPError and raise it."""
    args = ("exception in ldap backend: {0}".format(repr(e)), e)
    if six.PY2:
        six.reraise(LDAPError, args, sys.exc_info()[2])
    else:
        six.raise_from(LDAPError(*args), e)
Exemplo n.º 3
0
def _session():
    '''
    Return the boto3 session to use for the KMS client.

    If aws_kms:profile_name is set in the salt configuration, use that profile.
    Otherwise, fall back on the default aws profile.

    We use the boto3 profile system to avoid having to duplicate
    individual boto3 configuration settings in salt configuration.
    '''
    profile_name = _cfg('profile_name')
    if profile_name:
        log.info('Using the "%s" aws profile.', profile_name)
    else:
        log.info(
            'aws_kms:profile_name is not set in salt. Falling back on default profile.'
        )
    try:
        return boto3.Session(profile_name=profile_name)
    except botocore.exceptions.ProfileNotFound as orig_exc:
        err_msg = 'Boto3 could not find the "{}" profile configured in Salt.'.format(
            profile_name or 'default')
        config_error = salt.exceptions.SaltConfigurationError(err_msg)
        six.raise_from(config_error, orig_exc)
    except botocore.exceptions.NoRegionError as orig_exc:
        err_msg = ('Boto3 was unable to determine the AWS '
                   'endpoint region using the {} profile.').format(
                       profile_name or 'default')
        config_error = salt.exceptions.SaltConfigurationError(err_msg)
        six.raise_from(config_error, orig_exc)
Exemplo n.º 4
0
def _api_decrypt():
    '''
    Return the response dictionary from the KMS decrypt API call.
    '''
    kms = _kms()
    data_key = _cfg_data_key()
    try:
        return kms.decrypt(CiphertextBlob=data_key)
    except botocore.exceptions.ClientError as orig_exc:
        error_code = orig_exc.response.get('Error', {}).get('Code', '')
        if error_code != 'InvalidCiphertextException':
            raise
        err_msg = 'aws_kms:data_key is not a valid KMS data key'
        config_error = salt.exceptions.SaltConfigurationError(err_msg)
        six.raise_from(config_error, orig_exc)
Exemplo n.º 5
0
def _api_decrypt():
    """
    Return the response dictionary from the KMS decrypt API call.
    """
    kms = _kms()
    data_key = _cfg_data_key()
    try:
        return kms.decrypt(CiphertextBlob=data_key)
    except botocore.exceptions.ClientError as orig_exc:
        error_code = orig_exc.response.get("Error", {}).get("Code", "")
        if error_code != "InvalidCiphertextException":
            raise
        err_msg = "aws_kms:data_key is not a valid KMS data key"
        config_error = salt.exceptions.SaltConfigurationError(err_msg)
        six.raise_from(config_error, orig_exc)
Exemplo n.º 6
0
    def loads(self, msg, encoding=None, raw=False):
        '''
        Run the correct loads serialization format

        :param encoding: Useful for Python 3 support. If the msgpack data
                         was encoded using "use_bin_type=True", this will
                         differentiate between the 'bytes' type and the
                         'str' type by decoding contents with 'str' type
                         to what the encoding was set as. Recommended
                         encoding is 'utf-8' when using Python 3.
                         If the msgpack data was not encoded using
                         "use_bin_type=True", it will try to decode
                         all 'bytes' and 'str' data (the distinction has
                         been lost in this case) to what the encoding is
                         set as. In this case, it will fail if any of
                         the contents cannot be converted.
        '''
        try:
            def ext_type_decoder(code, data):
                if code == 78:
                    data = salt.utils.stringutils.to_unicode(data)
                    return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')
                return data

            gc.disable()  # performance optimization for msgpack
            if msgpack.version >= (0, 4, 0):
                # msgpack only supports 'encoding' starting in 0.4.0.
                # Due to this, if we don't need it, don't pass it at all so
                # that under Python 2 we can still work with older versions
                # of msgpack.
                try:
                    ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder, encoding=encoding)
                except UnicodeDecodeError:
                    # msg contains binary data
                    ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)
            else:
                ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)
            if six.PY3 and encoding is None and not raw:
                ret = salt.transport.frame.decode_embedded_strs(ret)
        except Exception as exc:
            log.critical(
                'Could not deserialize msgpack message. This often happens '
                'when trying to read a file not in binary mode. '
                'To see message payload, enable debug logging and retry. '
                'Exception: %s', exc
            )
            log.debug('Msgpack deserialization failure on message: %s', msg)
            gc.collect()
            raise six.raise_from(
                SaltDeserializationError(
                    'Could not deserialize msgpack message.'
                    ' See log for more info.'
                ),
                exc,
            )
        finally:
            gc.enable()
        return ret
Exemplo n.º 7
0
    def loads(self, msg, encoding=None, raw=False):
        """
        Run the correct loads serialization format

        :param encoding: Useful for Python 3 support. If the msgpack data
                         was encoded using "use_bin_type=True", this will
                         differentiate between the 'bytes' type and the
                         'str' type by decoding contents with 'str' type
                         to what the encoding was set as. Recommended
                         encoding is 'utf-8' when using Python 3.
                         If the msgpack data was not encoded using
                         "use_bin_type=True", it will try to decode
                         all 'bytes' and 'str' data (the distinction has
                         been lost in this case) to what the encoding is
                         set as. In this case, it will fail if any of
                         the contents cannot be converted.
        """
        try:

            def ext_type_decoder(code, data):
                if code == 78:
                    data = salt.utils.stringutils.to_unicode(data)
                    return datetime.datetime.strptime(data, "%Y%m%dT%H:%M:%S.%f")
                return data

            gc.disable()  # performance optimization for msgpack
            loads_kwargs = {'use_list': True,
                            'ext_hook': ext_type_decoder,
                            '_msgpack_module': msgpack}
            if msgpack.version >= (0, 4, 0):
                # msgpack only supports 'encoding' starting in 0.4.0.
                # Due to this, if we don't need it, don't pass it at all so
                # that under Python 2 we can still work with older versions
                # of msgpack.
                if salt.utils.msgpack.version >= (0, 5, 2):
                    if encoding is None:
                        loads_kwargs["raw"] = True
                    else:
                        loads_kwargs["raw"] = False
                else:
                    loads_kwargs["encoding"] = encoding
                try:
                    ret = salt.utils.msgpack.loads(msg, **loads_kwargs)
                except UnicodeDecodeError:
                    # msg contains binary data
                    loads_kwargs.pop('raw', None)
                    loads_kwargs.pop('encoding', None)
                    ret = salt.utils.msgpack.loads(msg, **loads_kwargs)
            else:
                ret = salt.utils.msgpack.loads(msg, **loads_kwargs)
            if six.PY3 and encoding is None and not raw:
                ret = salt.transport.frame.decode_embedded_strs(ret)
        except Exception as exc:  # pylint: disable=broad-except
            log.critical(
                "Could not deserialize msgpack message. This often happens "
                "when trying to read a file not in binary mode. "
                "To see message payload, enable debug logging and retry. "
                "Exception: %s",
                exc,
            )
            log.debug("Msgpack deserialization failure on message: %s", msg)
            gc.collect()
            raise six.raise_from(
                SaltDeserializationError(
                    "Could not deserialize msgpack message." " See log for more info."
                ),
                exc,
            )
        finally:
            gc.enable()
        return ret