예제 #1
0
def debug_print(msg: str, c: Optional[Console] = None) -> None:
    debug = load_config().get("debug", False)
    if not debug:
        return
    if not c:
        # Use stderr so piped output is still valid
        c = Console(stderr=True)

    c.print("[cyan]DEBUG[reset]: " + msg)
예제 #2
0
def set(db_num):
    c, ec = Console(), Console(stderr=True, style="bold red")
    config = load_config()
    if db_num > len(config["db"]["databases"]) - 1:
        ec.print(
            "Number of DB to chose is higher than number of available databases."
        )
        exit(-1)
    change_db(db_num)
예제 #3
0
파일: session.py 프로젝트: 3c7/yaramanager
def get_path() -> str:
    config = load_config()
    db = config.get_current_db()
    driver = db["driver"]
    path = db["path"]
    if driver == "sqlite":
        driver += ":///"
    else:
        driver += "://"
    return f"{driver}{path}"
예제 #4
0
def plyara_object_to_ruleset(obj: Dict,
                             session: Session) -> Union[Ruleset, None]:
    """Returns ruleset object, if ruleset is given as meta tag, or None"""
    key = load_config().get("ruleset_meta_key", "ruleset")
    for m_dict in obj.get("metadata", []):
        for k, v in m_dict.items():
            if k != key:
                continue

            return get_ruleset_by_name(name=v, session=session, create=True)
    return None
예제 #5
0
def open_temp_file_with_template():
    ec = Console(stderr=True, style="bold red")
    config = load_config()
    fd_temp, path = mkstemp(".yar")
    with os.fdopen(fd_temp, "w") as fh:
        try:
            fh.write(config["template"])
        except KeyError:
            ec.print(
                "Template is missing. Please set template variable in config.")
            exit(-1)
    open_file(path)
    return path
예제 #6
0
def plyara_object_to_ruleset(obj: Dict,
                             session: Session) -> Union[Ruleset, None]:
    """Returns ruleset object, if ruleset is given as meta tag, or None"""
    key = load_config().get("ruleset_meta_key", "ruleset")
    for m_dict in obj.get("metadata", []):
        for k, v in m_dict.items():
            if k != key:
                continue

            ruleset = session.query(Ruleset).filter(Ruleset.name == v).first()
            if not ruleset:
                ruleset = Ruleset(name=v)
            return ruleset
    return None
예제 #7
0
파일: session.py 프로젝트: 3c7/yaramanager
def get_session() -> Session:
    ec = Console(stderr=True, style="bold red")
    config = load_config()
    db = config.get_current_db()
    driver = db["driver"]
    path = db["path"]
    if driver == "sqlite" and not (os.path.exists(path) or os.path.getsize(path) == 0):
        ec.print("Database not initialized.")
        exit(-1)
    engine = get_engine()
    s_maker = sessionmaker(autocommit=False, bind=engine)
    db_alembic_version = get_alembic_version(s_maker())
    if db_alembic_version != alembic_version:
        ec.print(f"Database schema not up to date (is {db_alembic_version}, but should be {alembic_version}). "
                 f"Please run ym db upgrade.")
        exit(-1)
    return s_maker()
예제 #8
0
def stats():
    c = Console()
    config = load_config()
    db = config.get_current_db()
    session = get_session()
    rule_count = session.query(Rule).count()
    string_count = session.query(String).count()
    meta_count = session.query(Meta).count()
    tag_count = session.query(Tag).count()
    c.print(f"Number of rules:\t{rule_count}")
    c.print(f"Number of strings:\t{string_count}")
    c.print(f"Number of meta fields:\t{meta_count}")
    c.print(f"Number of tags:\t\t{tag_count}")
    c.print()

    if db["driver"] == "sqlite":
        c.print(
            f"Database size: \t\t{os.path.getsize(db['path'])/1024/1024:.2}MB")
예제 #9
0
def open_file(path: str, status: Optional[str] = None):
    c, ec = Console(), Console(stderr=True, style="bold red")
    config = load_config()
    env_editor = os.getenv("EDITOR", None)
    env_disable_status = os.getenv("DISABLE_STATUS", None)
    if env_editor:
        command = env_editor.split(" ")
    else:
        command = config.get("editor", None)
        if not command:
            ec.print(
                "Editor not given. Please set editor config value or use EDITOR environment variable."
            )
            exit(-1)
    command.append(path)
    if env_disable_status:
        subprocess.call(command)
    else:
        if not status:
            status = f"{path} opened in external editor..."
        with c.status(status):
            subprocess.call(command)
예제 #10
0
    def add_to_yarabuilder(self, yb: YaraBuilder) -> None:
        """Add the rule object to a given YaraBuilder instance

        >>> rule = Rule(...)
        >>> yb = YaraBuilder()
        >>> rule.add_to_yarabuilder(yb)
        >>> print(yb.build_rules())
        """
        yb.create_rule(self.name)
        key = load_config().get("ruleset_meta_key", "ruleset")
        if self.ruleset:
            yb.add_meta(self.name, key, self.ruleset.name)
        for meta in self.meta:
            yb.add_meta(self.name, meta.key, meta.value)
        for string in self.strings:
            s_name = string.name[1:]
            if string.type == "text":
                yb.add_text_string(self.name, string.value, s_name,
                                   string.modifier_list)
            elif string.type == "byte":
                yb.add_hex_string(
                    self.name,
                    string.value,
                    s_name,
                    string.
                    modifier_list  # Todo: Check hex string modifiers - this list should always be empty?
                )
            elif string.type == "regex":
                yb.add_regex_string(self.name, string.value, s_name,
                                    string.modifier_list)
            else:
                print(f"ERROR: Unknown string type \"{string.type}\".",
                      file=stderr)
        for tag in self.tags:
            yb.add_tag(self.name, tag.name)
        for imp in self.import_list:
            yb.add_import(self.name, imp)
        yb.add_condition(self.name, self.condition.strip())
예제 #11
0
def rules_to_table(rules: List[Rule], ensure: Optional[bool] = False) -> Table:
    """Creates a rich.table.Table object from s list of rules."""
    config = load_config()
    meta_columns = config.get("meta", {})
    ensure_meta = config.get("ensure", {}).get("ensure_meta", [])
    ensure_tags = config.get("ensure", {}).get("ensure_tag", True)
    table = Table()
    table.add_column("ID")
    table.add_column("Name")
    table.add_column("Ruleset")
    if ensure and ensure_tags:
        table.add_column("Tags [yellow]:warning:")
    else:
        table.add_column("Tags")
    for column in meta_columns.keys():
        c_header = column + " [yellow]:warning:" if meta_columns[
            column] in ensure_meta and ensure else column
        table.add_column(c_header)

    for rule in rules:
        if ensure and ensure_tags and len(rule.tags) == 0:
            tags = "[yellow]:warning:"
        else:
            tags = ", ".join([tag.name for tag in rule.tags])

        row = [
            str(rule.id), rule.name,
            rule.ruleset.name if rule.ruleset else "None", tags
        ]
        for column in meta_columns.values():
            m_value = rule.get_meta_value(column, default="None")
            if ensure and column in ensure_meta and m_value == "None":
                row.append("[yellow]:warning:")
            else:
                row.append(rule.get_meta_value(column, default="None"))
        table.add_row(*row)
    return table
예제 #12
0
def get():
    c = Console()
    config = load_config()
    c.print(
        f"Selected database: {config['db']['databases'][config['db']['selected']]['path']}",
        highlight=False)
예제 #13
0
import io

import click
from rich.console import Console
from rich.prompt import Confirm
from rich.syntax import Syntax

from yaramanager.config import load_config, config_file, write_initial_config
from yaramanager.utils.utils import open_file

CONFIG = load_config()


@click.group(help="Review and change yaramanager configuration.")
def config():
    pass


@config.command(help="Get single config entry by key.")
@click.argument("key")
def get(key):
    c, ec = Console(), Console(stderr=True, style="bold red")
    if key in CONFIG.keys():
        c.print(CONFIG[key])
    else:
        ec.print("Config key not found")


@config.command(
    help=
    f"Edit your config with an external editor. The config file can be found here: {config_file}. "