예제 #1
0
    def __init__(self):
        self.log = create_logger(__name__)

        self.matches = None
        self.rule = None
        self.namespace = None
        self.tags = None
        self.meta = None
        self.strings = None
예제 #2
0
    def __init__(self, name: str, tags: List[str] = None, meta: List[YaraMeta] = None,
                 strings: List[YaraString] = None, condition: YaraCondition = None, namespace: str = None,
                 compiled_blob: yara.Rules = None, compiled_path: str = None,
                 compiled_match_source: bool = None):
        """
        YARA rule object.

        :param name:            Rule name.
        :param tags:            List of tags.
        :param meta:            Metadata.
        :param strings:         List of strings (variables).
        :param condition:       YaraCondition object.
        :param namespace:       Namespace of YARA rule.
        :param compiled_blob:   Raw yara.Rules object generated by yara.compile
                                (usually set when spawned by cls from_compiled_file).
        :param compiled_path:   Path to the compiled YARA rule
                                (usually set when spawned by cls from_compiled_file).
        """
        self.log = create_logger(__name__)

        self.name: str = sanitize_identifier(name)

        if tags is not None:
            self.tags: list = [sanitize_identifier(x) for x in tags]
        else:
            self.tags = None

        self.meta: List[YaraMeta] = meta
        self.strings: List[YaraString] = strings

        if isinstance(condition, str):
            condition = YaraCondition(condition)

        self.condition = condition

        self.namespace = namespace
        self.compiled_blob = compiled_blob
        self.compiled_path = compiled_path
        self.compiled_match_source = compiled_match_source
예제 #3
0
import os

from flask import make_response, jsonify, request
from flask_restx import Namespace, Resource, fields

from utils import list_keys
from .handling import generate_yara_rule

from handlers import git_handler
from database.operations import update_rule, get_rule, get_rules
from handlers.config_handler import CONFIG
from handlers.log_handler import create_logger

api = Namespace('core', description='Core API')

log = create_logger(__name__)

yara_metadata_model = api.model("YARA-Metadata", {
    "identifier": fields.String(required=True, pattern=r"([a-zA-Z]([a-z0-9])+)"),
    "value": fields.String(required=True, pattern=r'.*'),
    "value_type": fields.String(required=True, pattern=r'str|int|bool'),
})

yara_string_model = api.model("YARA-String", {
    "identifier": fields.String(required=True, pattern=r"([a-zA-Z]([a-z0-9])+)"),
    "value": fields.String(required=True, pattern=r'.*'),
    "value_type": fields.String(required=True, pattern=r'str|int|bool'),
    "string_type": fields.String(required=True, pattern=r'text|hex|regex'),
    "modifiers": fields.List(
        fields.String(
            required=True,
예제 #4
0
    def __init__(self,
                 identifier: str = None,
                 value: str = None,
                 value_type: str = None,
                 string_type: str = TEXT_TYPE,
                 modifiers: List[Union[str, dict, YaraStringModifier]] = None,
                 from_dict: dict = None):
        """
        YARA String with optional modifiers.

        :param identifier:      Name/identifier.
        :param value:           String/variable data.
        :param string_type:     Valid types: Hexadecimal, text or regular expression.
        :param modifiers:       List of modifiers.
                                Valid modifiers: nocase, wide, ascii, xor, base64, base64wide, fullword or private.
        :param from_dict:       Define YARA String from a dict instead of individual values.
        """
        self.log = create_logger(__name__)
        self.identifier = None

        if from_dict is not None:
            self.create_from_dict(from_dict)
        else:
            self.determine_identifier(identifier)

            self.value_type = value_type
            # Set value by specified value_type argument.
            if value_type:
                if value_type == 'str' or value_type == str:
                    value = str(value)
                elif value_type == 'bool' or value_type == bool:
                    value = value.lower() == "true"
                elif value_type == 'int' or value_type == int:
                    value = int(value)
                else:
                    raise ValueError(
                        "value_type set but '{vt}' is not one of [{vdt}]".
                        format(vt=value_type,
                               vdt=", ".join(
                                   [x.__name__ for x in VALID_DATA_TYPES])))

            self.value = value

            if modifiers is not None and len(modifiers) > 0:
                # Ensure modifiers are instances of YaraStringModifier
                yara_string_modifier_objects = []
                for modifier in modifiers:
                    if isinstance(modifier, str):
                        self.log.info(
                            "Converting YARA String modifier keyword='{keyword}', type='str' "
                            "to YaraStringModifier object...".format(
                                keyword=modifier))

                        yara_string_modifier_objects.append(
                            YaraStringModifier(modifier))
                    elif isinstance(modifier, dict):
                        self.log.info(
                            "Converting YARA String modifier keyword='{keyword}', data={data}, type='dict' "
                            "to YaraStringModifier object...".format(
                                keyword=modifier["keyword"],
                                data=modifier["data"]))

                        yara_string_modifier_objects.append(
                            YaraStringModifier(modifier["keyword"],
                                               modifier["data"]))
                    elif isinstance(modifier, YaraStringModifier):
                        self.log.debug(
                            "Appending YaraStringModifier object to list: '{obj}'"
                            .format(obj=modifier))

                        yara_string_modifier_objects.append(modifier)
                    else:
                        raise YaraStringModifierInvalidModifierType(
                            "Got modifier '{modifier}' of invalid type "
                            "(must be either str, dict or YaraStringModifier)!"
                            .format(modifier=modifier), modifier)

                # Throws exception if not valid.
                validate_modifiers(yara_string_modifier_objects)

                # If no exception was thrown store the valid modifiers list.
                self.modifiers = yara_string_modifier_objects

        if string_type is None:
            self.determine_type()
        else:
            self.type = string_type
예제 #5
0
import json
from datetime import date

from flask import Flask
from flask.json import JSONEncoder
from flask_cors import CORS

from apis import blueprint as api
from flask_helpers import ReverseProxied
from handlers import config_handler
from handlers.log_handler import create_logger
from handlers import git_handler
from database import init_db

log = create_logger(__name__)
log_utility_functions = create_logger("{}.utility_functions".format(__name__))


class MyJSONEncoder(JSONEncoder):
    def default(self, o):
        """Override Flask JSONEncoder's date serializer (RFC 1123) to use ISO8601.."""
        if isinstance(o, date):
            return o.isoformat()

        return super().default(o)


class MyFlask(Flask):
    json_encoder = MyJSONEncoder