Skip to content

hypnguyen1209/offensive-claude / skills/malware-analysis

malware-analysis

Unverified

Use when reverse-engineering or detecting malware — static triage + capa/YARA-X, emulation/DBI/.NET unpacking, dynamic/fileless/Volatility 3 memory analysis, C2 config extraction (Cobalt Strike/CAPE), C2 traffic detection (JA4+, beaconing)

scripts/yara_gen.py

View on GitHub
#!/usr/bin/env python3
r"""
yara_gen.py - Family YARA rule generator + false-positive validator.

Given a directory of samples from ONE family, extracts candidate strings/byte
sequences common to >= N samples but rare in a goodware corpus, then emits a
YARA-X-compatible rule with imphash/PE module conditions and a tunable
'X of them' threshold. Optionally validates against a goodware dir to flag FPs.

USAGE:
    # generate rule from a family folder, validate against goodware
    python3 yara_gen.py --family samples/latrodectus/ --name Latrodectus_Loader \
        --goodware /usr/bin --out latrodectus.yar --min-share 0.8

    # just validate an existing rule
    python3 yara_gen.py --validate latrodectus.yar --goodware /usr/bin --family samples/latrodectus/

DEPENDENCIES:
    pip install yara-x   (preferred)  OR  pip install yara-python
    pip install pefile   (for imphash condition)
"""
import argparse
import re
import sys
from collections import Counter
from pathlib import Path

ASCII_RE = re.compile(rb"[\x20-\x7e]{6,64}")
NOISE = {b"kernel32.dll", b"KERNEL32.DLL", b"This program cannot be run in DOS mode",
         b"GetProcAddress", b"LoadLibraryA", b"VirtualProtect"}


def extract_strings(data):
    out = set()
    for m in ASCII_RE.finditer(data):
        s = m.group()
        if s in NOISE or len(s) < 6:
            continue
        # skip mostly-digits / paths that vary
        if sum(c in b"0123456789" for c in s) > len(s) * 0.6:
            continue
        out.add(s)
    return out


def imphash_of(path):
    try:
        import pefile
        pe = pefile.PE(str(path), fast_load=True)
        pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"]])
        h = pe.get_imphash()
        pe.close()
        return h
    except Exception:
        return None


def gen_rule(family_dir, name, min_share, goodware_dir):
    samples = [p for p in Path(family_dir).iterdir() if p.is_file()]
    if len(samples) < 2:
        sys.exit("need >= 2 family samples")
    counts = Counter()
    imphashes = Counter()
    for p in samples:
        data = p.read_bytes()
        for s in extract_strings(data):
            counts[s] += 1
        ih = imphash_of(p)
        if ih:
            imphashes[ih] += 1

    threshold = max(2, int(len(samples) * min_share))
    common = [s for s, c in counts.items() if c >= threshold]

    # drop strings that appear in goodware
    if goodware_dir:
        good = set()
        gw = [p for p in Path(goodware_dir).iterdir() if p.is_file()][:200]
        for p in gw:
            try:
                good |= extract_strings(p.read_bytes())
            except Exception:
                pass
        common = [s for s in common if s not in good]

    common = sorted(common, key=len, reverse=True)[:20]
    if not common:
        print("[-] no discriminating strings survived goodware filtering - "
              "consider byte-pattern / code-feature rules (capa) instead")

    lines = [f"rule {name}", "{", "    meta:",
             '        author = "offensive-claude"',
             f'        description = "Auto-generated family rule for {name}"',
             f'        samples = {len(samples)}',
             '        yara_x = "compatible"', "",
             "    strings:"]
    for i, s in enumerate(common):
        esc = s.decode("latin1").replace("\\", "\\\\").replace('"', '\\"')
        lines.append(f'        $s{i} = "{esc}" ascii')
    lines.append("")
    lines.append("    condition:")
    cond = ["uint16(0) == 0x5A4D"]
    dom_imphash = imphashes.most_common(1)
    if dom_imphash and dom_imphash[0][1] >= threshold:
        lines.insert(2, "    // dominant imphash: " + dom_imphash[0][0])
    if common:
        need = max(2, int(len(common) * 0.4))
        cond.append(f"{need} of ($s*)")
    lines.append("        " + " and\n        ".join(cond))
    lines.append("}")
    return "\n".join(lines)


def validate(rule_path, goodware_dir, family_dir):
    try:
        import yara_x
        compiler = yara_x.Compiler()
        compiler.add_source(Path(rule_path).read_text())
        rules = compiler.build()
        scan = lambda data: bool(rules.scan(data).matching_rules)
    except ImportError:
        try:
            import yara
            rules = yara.compile(filepath=str(rule_path))
            scan = lambda data: bool(rules.match(data=data))
        except ImportError:
            sys.exit("pip install yara-x (or yara-python)")

    tp = fn = 0
    for p in Path(family_dir).iterdir():
        if p.is_file():
            (tp := tp + 1) if scan(p.read_bytes()) else (fn := fn + 1)
    fp = 0
    if goodware_dir:
        for p in list(Path(goodware_dir).iterdir())[:500]:
            if p.is_file():
                try:
                    if scan(p.read_bytes()):
                        fp += 1
                        print(f"    [FP] {p.name}")
                except Exception:
                    pass
    print(f"[validate] family TP={tp} FN={fn}  goodware FP={fp}")
    if fp:
        print("[!] false positives present - tighten condition / drop generic strings")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--family")
    ap.add_argument("--name", default="Generated_Family")
    ap.add_argument("--goodware")
    ap.add_argument("--min-share", type=float, default=0.8)
    ap.add_argument("--out")
    ap.add_argument("--validate", help="validate existing rule file")
    a = ap.parse_args()

    if a.validate:
        if not a.family:
            sys.exit("--validate requires --family for TP/FN measurement")
        validate(a.validate, a.goodware, a.family)
        return

    if not a.family:
        sys.exit("--family DIR required to generate")
    rule = gen_rule(a.family, a.name, a.min_share, a.goodware)
    if a.out:
        Path(a.out).write_text(rule)
        print(f"[+] rule -> {a.out}")
        if a.goodware:
            validate(a.out, a.goodware, a.family)
    else:
        print(rule)


if __name__ == "__main__":
    main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall