(filepath, sigma_config=None)
Returns a JSON represenation for a rule
    Args:
        filepath: path to the sigma rule to be parsed
        sigma_config: optional argument to pass a
                sigma.configuration.SigmaConfiguration object
    Returns:
        Json representation of the parsed rule
    Raises:
        ValueError: Parsing error
        IsADirectoryError: If a directory is passed as filepath
Returns a JSON represenation for a rule
    Args:
        filepath: path to the sigma rule to be parsed
        sigma_config: optional argument to pass a
                sigma.configuration.SigmaConfiguration object
    Returns:
        Json representation of the parsed rule
    Raises:
        ValueError: Parsing error
        IsADirectoryError: If a directory is passed as filepath
Returns a JSON represenation for a rule Args : filepath : path to the sigma rule to be parsed sigma_config : optional argument to pass a sigma . configuration . SigmaConfiguration object Returns : Json representation of the parsed rule Raises : ValueError : Parsing error IsADirectoryError : If a directory is passed as filepath
def get_sigma_rule(filepath, sigma_config=None):
    """Returns a JSON represenation for a rule
    Args:
        filepath: path to the sigma rule to be parsed
        sigma_config: optional argument to pass a
                sigma.configuration.SigmaConfiguration object
    Returns:
        Json representation of the parsed rule
    Raises:
        ValueError: Parsing error
        IsADirectoryError: If a directory is passed as filepath
    """
    try:
        if isinstance(sigma_config, sigma_configuration.SigmaConfiguration):
            sigma_conf_obj = sigma_config
        elif isinstance(sigma_config, str):
            sigma_conf_obj = get_sigma_config_file(sigma_config)
        else:
            sigma_conf_obj = get_sigma_config_file()
    except ValueError as e:
        logger.error(
            'Problem reading the Sigma config', exc_info=True)
        raise ValueError('Problem reading the Sigma config') from e

    sigma_backend = sigma_es.ElasticsearchQuerystringBackend(
        sigma_conf_obj, {})

    try:
        sigma_rules_paths = get_sigma_rules_path()
    except ValueError:
        sigma_rules_paths = None

    if not filepath.lower().endswith('.yml'):
        raise ValueError(f'{filepath} does not end with .yml')

    # if a sub dir is found, nothing can be parsed
    if os.path.isdir(filepath):
        raise IsADirectoryError(f'{filepath} is a directory - must be a file')

    abs_path = os.path.abspath(filepath)

    with codecs.open(
            abs_path, 'r', encoding='utf-8', errors='replace') as file:
        try:
            rule_return = {}
            rule_yaml_data = yaml.safe_load_all(file.read())
            for doc in rule_yaml_data:
                rule_return.update(doc)
                parser = sigma_collection.SigmaCollectionParser(
                    yaml.safe_dump(doc), sigma_conf_obj, None)
                parsed_sigma_rules = parser.generate(sigma_backend)

        except NotImplementedError as exception:
            logger.error(
                'Error generating rule in file {0:s}: {1!s}'
                .format(abs_path, exception))
            add_problematic_rule(filepath, doc.get('id'),
                                 'Parts of the rule not implemented in TS')
            return None

        except sigma_exceptions.SigmaParseError as exception:
            logger.error(
                'Sigma parsing error generating rule in file {0:s}: {1!s}'
                .format(abs_path, exception))
            add_problematic_rule(
                filepath, doc.get('id'), 'sigma_exceptions.SigmaParseError')
            return None

        except yaml.parser.ParserError as exception:
            logger.error(
                'Yaml parsing error generating rule in file {0:s}: {1!s}'
                .format(abs_path, exception))
            add_problematic_rule(
                filepath, None, 'yaml.parser.ParserError')
            return None

        sigma_es_query = ''

        for sigma_rule in parsed_sigma_rules:

            sigma_es_query = _sanatize_sigma_rule(sigma_rule)

        rule_return.update(
            {'es_query': sigma_es_query})
        rule_return.update(
            {'file_name': os.path.basename(filepath)})

        # in case multiple folders are in the config, need to remove them
        if sigma_rules_paths:
            for rule_path in sigma_rules_paths:
                file_relpath = os.path.relpath(filepath, rule_path)
        else:
            file_relpath = 'N/A'

        rule_return.update(
            {'file_relpath': file_relpath})

        return rule_return
def get_sigma_rule ( filepath , sigma_config = None ) : try : if isinstance ( sigma_config , sigma_configuration . SigmaConfiguration ) : sigma_conf_obj = sigma_config elif isinstance ( sigma_config , str ) : sigma_conf_obj = get_sigma_config_file ( sigma_config ) else : sigma_conf_obj = get_sigma_config_file ( ) except ValueError as e : logger . error ( 'Problem reading the Sigma config' , exc_info = True ) raise ValueError ( 'Problem reading the Sigma config' ) from e sigma_backend = sigma_es . ElasticsearchQuerystringBackend ( sigma_conf_obj , { } ) try : sigma_rules_paths = get_sigma_rules_path ( ) except ValueError : sigma_rules_paths = None if not filepath . lower ( ) . endswith ( '.yml' ) : raise ValueError ( f'{filepath} does not end with .yml' ) # if a sub dir is found, nothing can be parsed if os . path . isdir ( filepath ) : raise IsADirectoryError ( f'{filepath} is a directory - must be a file' ) abs_path = os . path . abspath ( filepath ) with codecs . open ( abs_path , 'r' , encoding = 'utf-8' , errors = 'replace' ) as file : try : rule_return = { } rule_yaml_data = yaml . safe_load_all ( file . read ( ) ) for doc in rule_yaml_data : rule_return . update ( doc ) parser = sigma_collection . SigmaCollectionParser ( yaml . safe_dump ( doc ) , sigma_conf_obj , None ) parsed_sigma_rules = parser . generate ( sigma_backend ) except NotImplementedError as exception : logger . error ( 'Error generating rule in file {0:s}: {1!s}' . format ( abs_path , exception ) ) add_problematic_rule ( filepath , doc . get ( 'id' ) , 'Parts of the rule not implemented in TS' ) return None except sigma_exceptions . SigmaParseError as exception : logger . error ( 'Sigma parsing error generating rule in file {0:s}: {1!s}' . format ( abs_path , exception ) ) add_problematic_rule ( filepath , doc . get ( 'id' ) , 'sigma_exceptions.SigmaParseError' ) return None except yaml . parser . ParserError as exception : logger . error ( 'Yaml parsing error generating rule in file {0:s}: {1!s}' . format ( abs_path , exception ) ) add_problematic_rule ( filepath , None , 'yaml.parser.ParserError' ) return None sigma_es_query = '' for sigma_rule in parsed_sigma_rules : sigma_es_query = _sanatize_sigma_rule ( sigma_rule ) rule_return . update ( { 'es_query' : sigma_es_query } ) rule_return . update ( { 'file_name' : os . path . basename ( filepath ) } ) # in case multiple folders are in the config, need to remove them if sigma_rules_paths : for rule_path in sigma_rules_paths : file_relpath = os . path . relpath ( filepath , rule_path ) else : file_relpath = 'N/A' rule_return . update ( { 'file_relpath' : file_relpath } ) return rule_return