[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71F2KBK5C41WD0EX5B0DXR5":3,"skill-same:01M71F2KBK5C41WD0EX5B0DXR5":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":29,"linkOnly":30,"markdownContent":31,"markdownBody":32,"frontMatter":33,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":14,"repositoryHtmlUrl":37,"repositoryHomepageUrl":6,"ownerHtmlUrl":38,"ownerBlogUrl":6,"ownerDescription":39,"updatedAt":40,"install":41,"resources":54},"01M71F2KBK5C41WD0EX5B0DXR5","malware-tools-yara",null,"- Compile all custom rules without syntax errors: `yara -w rules\u002F*.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-tools-yara\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28],"malware","yara","Tools","malware tools yara","cybersecurity","compile","Rules","syntax","errors","custom","2026-11-10 10:12:30",false,"---\nname: malware-tools-yara\ndescription: \"- Compile all custom rules without syntax errors: `yara -w rules\u002F*.\"\ndomain: cybersecurity\n---\n\n# Performing Threat Hunting with YARA Rules\n\nScan files, directories, and memory dumps using YARA rules to identify\nmalware families, suspicious patterns, and IOC matches.\n\n## When to Use\n\n- Proactively hunting for unknown malware variants across network shares, endpoints, and email attachments\n- Scanning quarantine directories or sandbox outputs for malware family classification\n- Searching process memory dumps for injected code or in-memory-only payloads\n- Validating threat intelligence IOCs against a large corpus of collected samples\n- Triaging incident response artifacts to identify known malware families quickly\n- Building automated detection pipelines that scan new files on ingestion\n\n**Do not use** for real-time endpoint protection (use EDR agents instead); YARA scanning is best suited for batch hunting, triage, and post-collection analysis where scan latency is acceptable.\n\n## Prerequisites\n\n- YARA 4.x installed (`apt install yara` on Debian\u002FUbuntu, `brew install yara` on macOS)\n- Python 3.8+ with `yara-python` (`pip install yara-python`)\n- `yarGen` for automated rule generation (`git clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FyarGen`)\n- Sample malware corpus or suspicious files for scanning (from malware zoos, VT, or incident artifacts)\n- Optional: `pefile` for PE header analysis, `malduck` for memory carving\n- Threat intel YARA rule sets (e.g., YARA-Rules community repository, Florian Roth signature-base)\n\n## Workflow\n\n### Step 1: Install YARA and Python Bindings\n\n```bash\n# Linux\nsudo apt update && sudo apt install -y yara\n\n# Python bindings\npip install yara-python\n\n# Verify installation\nyara --version\npython3 -c \"import yara; print(yara.YARA_VERSION)\"\n```\n\n### Step 2: Write a Basic YARA Rule\n\nCreate rules that match on strings, hex patterns, and file metadata:\n\n```yara\n\u002F\u002F File: rules\u002Femotet_loader.yar\nrule Emotet_Loader_2026 {\n    meta:\n        author = \"Threat Intel Team\"\n        description = \"Detects Emotet first-stage loader DLL\"\n        date = \"2026-01-20\"\n        reference = \"https:\u002F\u002Fattack.mitre.org\u002Fsoftware\u002FS0367\u002F\"\n        mitre_attack = \"T1059.001, T1055.001\"\n        severity = \"critical\"\n\n    strings:\n        \u002F\u002F Emotet export function name patterns\n        $export1 = \"DllRegisterServer\" ascii\n        $export2 = \"RunDLL\" ascii nocase\n\n        \u002F\u002F Obfuscated string decryption routine\n        $decrypt_loop = { 8B 45 ?? 33 45 ?? 89 45 ?? 8B 4D ?? 03 4D ?? }\n\n        \u002F\u002F PowerShell download cradle in embedded script\n        $ps_cradle = \u002Fpowershell[^\\n]{0,50}-e(nc|ncodedcommand)\u002Fi\n\n        \u002F\u002F Known C2 URI patterns\n        $uri1 = \"\u002Fwp-content\u002Fuploads\u002F\" ascii\n        $uri2 = \"\u002Fwp-admin\u002Fcss\u002F\" ascii\n        $uri3 = \"\u002Fwp-includes\u002F\" ascii\n\n        \u002F\u002F PE characteristics\n        $mz = \"MZ\" at 0\n\n    condition:\n        $mz and\n        filesize \u003C 2MB and\n        (\n            ($export1 and $decrypt_loop) or\n            ($ps_cradle and any of ($uri*)) or\n            (2 of ($uri*) and $decrypt_loop)\n        )\n}\n```\n\n### Step 3: Write Advanced Rules with Modules\n\nUse YARA modules for PE header inspection and math-based entropy checks:\n\n```yara\nimport \"pe\"\nimport \"math\"\n\nrule Suspicious_Packed_Executable {\n    meta:\n        author = \"Threat Hunting Team\"\n        description = \"Detects PE files with high entropy sections indicating packing or encryption\"\n        severity = \"medium\"\n\n    condition:\n        pe.is_pe and\n        pe.number_of_sections > 0 and\n        for any section in pe.sections : (\n            math.entropy(section.offset, section.size) > 7.2 and\n            section.size > 1024\n        ) and\n        pe.imports(\"kernel32.dll\", \"VirtualAlloc\") and\n        pe.imports(\"kernel32.dll\", \"VirtualProtect\")\n}\n\nrule Suspicious_UPX_Modified {\n    meta:\n        description = \"Detects UPX-packed binaries with tampered section names\"\n        severity = \"medium\"\n\n    strings:\n        $upx_magic = { 55 50 58 21 }  \u002F\u002F UPX!\n\n    condition:\n        pe.is_pe and\n        $upx_magic and\n        not (\n            pe.sections[0].name == \"UPX0\" and\n            pe.sections[1].name == \"UPX1\"\n        )\n}\n```\n\n### Step 4: Scan Files and Directories with yara-python\n\n```python\nimport yara\nimport os\nimport json\nfrom datetime import datetime\nfrom pathlib import Path\n\ndef compile_rules(rule_paths):\n    \"\"\"Compile YARA rules from one or more .yar files.\"\"\"\n    rule_files = {}\n    for i, path in enumerate(rule_paths):\n        namespace = Path(path).stem\n        rule_files[namespace] = path\n    return yara.compile(filepaths=rule_files)\n\ndef scan_directory(rules, target_dir, recursive=True):\n    \"\"\"Scan a directory for matches and return structured results.\"\"\"\n    results = []\n    scan_count = 0\n    error_count = 0\n\n    for root, dirs, files in os.walk(target_dir):\n        for filename in files:\n            filepath = os.path.join(root, filename)\n            scan_count += 1\n            try:\n                matches = rules.match(filepath, timeout=60)\n                if matches:\n                    for match in matches:\n                        result = {\n                            \"file\": filepath,\n                            \"rule\": match.rule,\n                            \"namespace\": match.namespace,\n                            \"tags\": match.tags,\n                            \"meta\": match.meta,\n                            \"strings\": [],\n                            \"scan_time\": datetime.utcnow().isoformat()\n                        }\n                        for offset, identifier, data in match.strings:\n                            result[\"strings\"].append({\n                                \"offset\": hex(offset),\n                                \"identifier\": identifier,\n                                \"data\": data.hex() if isinstance(data, bytes) else data\n                            })\n                        results.append(result)\n                        print(f\"  MATCH: {match.rule} -> {filepath}\")\n            except yara.TimeoutError:\n                error_count += 1\n                print(f\"  TIMEOUT scanning {filepath}\")\n            except yara.Error as e:\n                error_count += 1\n\n        if not recursive:\n            break\n\n    print(f\"\\nScan complete: {scan_count} files scanned, \"\n          f\"{len(results)} matches, {error_count} errors\")\n    return results\n\n# Compile and scan\nrules = compile_rules([\n    \"rules\u002Femotet_loader.yar\",\n    \"rules\u002Fsuspicious_packed.yar\"\n])\n\nmatches = scan_directory(rules, \"\u002Fmnt\u002Fevidence\u002Fcollected_samples\u002F\")\n\n# Export results\nwith open(\"yara_scan_results.json\", \"w\") as f:\n    json.dump(matches, f, indent=2)\n```\n\n### Step 5: Scan Process Memory Dumps\n\nHunt for in-memory indicators that only exist in running processes:\n\n```python\nimport yara\n\ndef scan_memory_dump(rules, dump_path):\n    \"\"\"Scan a process memory dump for YARA matches.\"\"\"\n    matches = rules.match(dump_path, timeout=120)\n\n    for match in matches:\n        print(f\"Rule: {match.rule}\")\n        print(f\"  Severity: {match.meta.get('severity', 'unknown')}\")\n        for offset, identifier, data in match.strings:\n            # Show context around the match\n            print(f\"  String {identifier} at offset {hex(offset)}\")\n            if len(data) \u003C= 64:\n                print(f\"    Data: {data.hex()}\")\n\n    return matches\n\n# Rules targeting in-memory artifacts\nmemory_rules = yara.compile(source=\"\"\"\nrule Cobalt_Strike_Beacon_Memory {\n    meta:\n        description = \"Detects Cobalt Strike beacon in process memory\"\n        severity = \"critical\"\n    strings:\n        $config_start = { 2E 2F 2E 2F 2E 2C }\n        $sleep_mask = { 48 8B 44 24 ?? 48 89 44 24 ?? 48 8B 44 24 }\n        $named_pipe = \"\\\\\\\\\\\\\\\\.\\\\\\\\pipe\\\\\\\\msagent_\" ascii\n        $watermark = { 00 00 00 00 00 00 ?? ?? 00 00 }\n    condition:\n        2 of them\n}\n\"\"\")\n\nscan_memory_dump(memory_rules, \"\u002Fmnt\u002Fevidence\u002Flsass_dump.dmp\")\n```\n\n### Step 6: Generate Rules Automatically with yarGen\n\nUse yarGen to create rules from malware samples by extracting unique strings:\n\n```bash\n# Clone and set up yarGen\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FyarGen.git\ncd yarGen\npip install -r requirements.txt\n\n# Download the string databases (run once)\npython3 yarGen.py --update\n\n# Generate rules from a directory of malware samples\npython3 yarGen.py \\\n    -m \u002Fmnt\u002Fevidence\u002Fmalware_samples\u002F \\\n    -o generated_rules.yar \\\n    --excludegood \\\n    -p \"AutoGen\" \\\n    -a \"Threat Hunting Team\" \\\n    --score 50\n\n# Generate rules for a single sample with maximum detail\npython3 yarGen.py \\\n    -m \u002Fmnt\u002Fevidence\u002Fmalware_samples\u002Fsuspicious.exe \\\n    -o single_sample_rule.yar \\\n    --opcodes \\\n    --debug\n```\n\n### Step 7: Integrate Community Rule Sets\n\nDownload and combine rules from public threat intelligence repositories:\n\n```bash\n# Clone Florian Roth's signature-base (large community rule set)\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base.git\n\n# Clone YARA-Rules community repository\ngit clone https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules.git yara-community-rules\n\n# Clone ReversingLabs YARA rules\ngit clone https:\u002F\u002Fgithub.com\u002Freversinglabs\u002Freversinglabs-yara-rules.git\n```\n\n```python\nimport yara\nfrom pathlib import Path\n\ndef load_rule_directory(rule_dir, extensions=(\".yar\", \".yara\")):\n    \"\"\"Load all YARA rules from a directory tree.\"\"\"\n    rule_files = {}\n    for ext in extensions:\n        for rule_file in Path(rule_dir).rglob(f\"*{ext}\"):\n            namespace = rule_file.stem\n            # Avoid namespace collisions\n            if namespace in rule_files:\n                namespace = f\"{rule_file.parent.name}_{namespace}\"\n            rule_files[namespace] = str(rule_file)\n\n    print(f\"Loading {len(rule_files)} rule files from {rule_dir}\")\n    try:\n        compiled = yara.compile(filepaths=rule_files)\n        return compiled\n    except yara.SyntaxError as e:\n        print(f\"Syntax error in rules: {e}\")\n        # Fall back to loading rules one by one, skipping broken ones\n        valid_rules = {}\n        for ns, path in rule_files.items():\n            try:\n                yara.compile(filepath=path)\n                valid_rules[ns] = path\n            except yara.SyntaxError:\n                print(f\"  Skipping broken rule: {path}\")\n        return yara.compile(filepaths=valid_rules)\n\n# Load and scan with community rules\ncommunity_rules = load_rule_directory(\"signature-base\u002Fyara\u002F\")\nmatches = community_rules.match(\"\u002Fmnt\u002Fevidence\u002Fsuspicious_file.exe\", timeout=120)\n\nfor m in matches:\n    print(f\"Matched: {m.rule} (namespace: {m.namespace})\")\n```\n\n### Step 8: Build a Continuous Hunting Pipeline\n\nAutomate scanning of new files as they arrive using filesystem monitoring:\n\n```python\nimport yara\nimport time\nimport json\nimport hashlib\nfrom pathlib import Path\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nclass YaraHuntingHandler(FileSystemEventHandler):\n    def __init__(self, rules, alert_file=\"yara_alerts.jsonl\"):\n        self.rules = rules\n        self.alert_file = alert_file\n        self.scanned_hashes = set()\n\n    def on_created(self, event):\n        if event.is_directory:\n            return\n        self._scan_file(event.src_path)\n\n    def _scan_file(self, filepath):\n        # Deduplicate by file hash\n        try:\n            file_hash = hashlib.sha256(Path(filepath).read_bytes()).hexdigest()\n        except (PermissionError, FileNotFoundError):\n            return\n\n        if file_hash in self.scanned_hashes:\n            return\n        self.scanned_hashes.add(file_hash)\n\n        matches = self.rules.match(filepath, timeout=60)\n        if matches:\n            alert = {\n                \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n                \"file\": filepath,\n                \"sha256\": file_hash,\n                \"matches\": [\n                    {\"rule\": m.rule, \"severity\": m.meta.get(\"severity\", \"unknown\")}\n                    for m in matches\n                ]\n            }\n            with open(self.alert_file, \"a\") as f:\n                f.write(json.dumps(alert) + \"\\n\")\n            print(f\"ALERT: {filepath} matched {len(matches)} rules\")\n\n# Set up continuous monitoring\nrules = yara.compile(filepaths={\"hunting\": \"rules\u002Fall_hunting_rules.yar\"})\nhandler = YaraHuntingHandler(rules)\nobserver = Observer()\nobserver.schedule(handler, path=\"\u002Fmnt\u002Fquarantine\u002F\", recursive=True)\nobserver.start()\nprint(\"YARA hunting pipeline active. Monitoring \u002Fmnt\u002Fquarantine\u002F ...\")\n```\n\n## Verification\n\n- Compile all custom rules without syntax errors: `yara -w rules\u002F*.yar \u002Fdev\u002Fnull`\n- Confirm rules match known-good malware samples from your test corpus (true positive validation)\n- Verify rules do NOT match a goodware corpus of common system files (false positive testing)\n- Test scanning performance: single file scan should complete within timeout threshold\n- Validate yarGen output rules compile and produce meaningful matches against the input samples\n- Check that community rule sets load without critical syntax errors after filtering\n- Confirm the continuous hunting pipeline generates alerts in JSONL format when test files are dropped\n- Cross-reference YARA matches against VirusTotal or sandbox results to validate detection accuracy\n","# Performing Threat Hunting with YARA Rules\n\nScan files, directories, and memory dumps using YARA rules to identify\nmalware families, suspicious patterns, and IOC matches.\n\n## When to Use\n\n- Proactively hunting for unknown malware variants across network shares, endpoints, and email attachments\n- Scanning quarantine directories or sandbox outputs for malware family classification\n- Searching process memory dumps for injected code or in-memory-only payloads\n- Validating threat intelligence IOCs against a large corpus of collected samples\n- Triaging incident response artifacts to identify known malware families quickly\n- Building automated detection pipelines that scan new files on ingestion\n\n**Do not use** for real-time endpoint protection (use EDR agents instead); YARA scanning is best suited for batch hunting, triage, and post-collection analysis where scan latency is acceptable.\n\n## Prerequisites\n\n- YARA 4.x installed (`apt install yara` on Debian\u002FUbuntu, `brew install yara` on macOS)\n- Python 3.8+ with `yara-python` (`pip install yara-python`)\n- `yarGen` for automated rule generation (`git clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FyarGen`)\n- Sample malware corpus or suspicious files for scanning (from malware zoos, VT, or incident artifacts)\n- Optional: `pefile` for PE header analysis, `malduck` for memory carving\n- Threat intel YARA rule sets (e.g., YARA-Rules community repository, Florian Roth signature-base)\n\n## Workflow\n\n### Step 1: Install YARA and Python Bindings\n\n```bash\n# Linux\nsudo apt update && sudo apt install -y yara\n\n# Python bindings\npip install yara-python\n\n# Verify installation\nyara --version\npython3 -c \"import yara; print(yara.YARA_VERSION)\"\n```\n\n### Step 2: Write a Basic YARA Rule\n\nCreate rules that match on strings, hex patterns, and file metadata:\n\n```yara\n\u002F\u002F File: rules\u002Femotet_loader.yar\nrule Emotet_Loader_2026 {\n    meta:\n        author = \"Threat Intel Team\"\n        description = \"Detects Emotet first-stage loader DLL\"\n        date = \"2026-01-20\"\n        reference = \"https:\u002F\u002Fattack.mitre.org\u002Fsoftware\u002FS0367\u002F\"\n        mitre_attack = \"T1059.001, T1055.001\"\n        severity = \"critical\"\n\n    strings:\n        \u002F\u002F Emotet export function name patterns\n        $export1 = \"DllRegisterServer\" ascii\n        $export2 = \"RunDLL\" ascii nocase\n\n        \u002F\u002F Obfuscated string decryption routine\n        $decrypt_loop = { 8B 45 ?? 33 45 ?? 89 45 ?? 8B 4D ?? 03 4D ?? }\n\n        \u002F\u002F PowerShell download cradle in embedded script\n        $ps_cradle = \u002Fpowershell[^\\n]{0,50}-e(nc|ncodedcommand)\u002Fi\n\n        \u002F\u002F Known C2 URI patterns\n        $uri1 = \"\u002Fwp-content\u002Fuploads\u002F\" ascii\n        $uri2 = \"\u002Fwp-admin\u002Fcss\u002F\" ascii\n        $uri3 = \"\u002Fwp-includes\u002F\" ascii\n\n        \u002F\u002F PE characteristics\n        $mz = \"MZ\" at 0\n\n    condition:\n        $mz and\n        filesize \u003C 2MB and\n        (\n            ($export1 and $decrypt_loop) or\n            ($ps_cradle and any of ($uri*)) or\n            (2 of ($uri*) and $decrypt_loop)\n        )\n}\n```\n\n### Step 3: Write Advanced Rules with Modules\n\nUse YARA modules for PE header inspection and math-based entropy checks:\n\n```yara\nimport \"pe\"\nimport \"math\"\n\nrule Suspicious_Packed_Executable {\n    meta:\n        author = \"Threat Hunting Team\"\n        description = \"Detects PE files with high entropy sections indicating packing or encryption\"\n        severity = \"medium\"\n\n    condition:\n        pe.is_pe and\n        pe.number_of_sections > 0 and\n        for any section in pe.sections : (\n            math.entropy(section.offset, section.size) > 7.2 and\n            section.size > 1024\n        ) and\n        pe.imports(\"kernel32.dll\", \"VirtualAlloc\") and\n        pe.imports(\"kernel32.dll\", \"VirtualProtect\")\n}\n\nrule Suspicious_UPX_Modified {\n    meta:\n        description = \"Detects UPX-packed binaries with tampered section names\"\n        severity = \"medium\"\n\n    strings:\n        $upx_magic = { 55 50 58 21 }  \u002F\u002F UPX!\n\n    condition:\n        pe.is_pe and\n        $upx_magic and\n        not (\n            pe.sections[0].name == \"UPX0\" and\n            pe.sections[1].name == \"UPX1\"\n        )\n}\n```\n\n### Step 4: Scan Files and Directories with yara-python\n\n```python\nimport yara\nimport os\nimport json\nfrom datetime import datetime\nfrom pathlib import Path\n\ndef compile_rules(rule_paths):\n    \"\"\"Compile YARA rules from one or more .yar files.\"\"\"\n    rule_files = {}\n    for i, path in enumerate(rule_paths):\n        namespace = Path(path).stem\n        rule_files[namespace] = path\n    return yara.compile(filepaths=rule_files)\n\ndef scan_directory(rules, target_dir, recursive=True):\n    \"\"\"Scan a directory for matches and return structured results.\"\"\"\n    results = []\n    scan_count = 0\n    error_count = 0\n\n    for root, dirs, files in os.walk(target_dir):\n        for filename in files:\n            filepath = os.path.join(root, filename)\n            scan_count += 1\n            try:\n                matches = rules.match(filepath, timeout=60)\n                if matches:\n                    for match in matches:\n                        result = {\n                            \"file\": filepath,\n                            \"rule\": match.rule,\n                            \"namespace\": match.namespace,\n                            \"tags\": match.tags,\n                            \"meta\": match.meta,\n                            \"strings\": [],\n                            \"scan_time\": datetime.utcnow().isoformat()\n                        }\n                        for offset, identifier, data in match.strings:\n                            result[\"strings\"].append({\n                                \"offset\": hex(offset),\n                                \"identifier\": identifier,\n                                \"data\": data.hex() if isinstance(data, bytes) else data\n                            })\n                        results.append(result)\n                        print(f\"  MATCH: {match.rule} -> {filepath}\")\n            except yara.TimeoutError:\n                error_count += 1\n                print(f\"  TIMEOUT scanning {filepath}\")\n            except yara.Error as e:\n                error_count += 1\n\n        if not recursive:\n            break\n\n    print(f\"\\nScan complete: {scan_count} files scanned, \"\n          f\"{len(results)} matches, {error_count} errors\")\n    return results\n\n# Compile and scan\nrules = compile_rules([\n    \"rules\u002Femotet_loader.yar\",\n    \"rules\u002Fsuspicious_packed.yar\"\n])\n\nmatches = scan_directory(rules, \"\u002Fmnt\u002Fevidence\u002Fcollected_samples\u002F\")\n\n# Export results\nwith open(\"yara_scan_results.json\", \"w\") as f:\n    json.dump(matches, f, indent=2)\n```\n\n### Step 5: Scan Process Memory Dumps\n\nHunt for in-memory indicators that only exist in running processes:\n\n```python\nimport yara\n\ndef scan_memory_dump(rules, dump_path):\n    \"\"\"Scan a process memory dump for YARA matches.\"\"\"\n    matches = rules.match(dump_path, timeout=120)\n\n    for match in matches:\n        print(f\"Rule: {match.rule}\")\n        print(f\"  Severity: {match.meta.get('severity', 'unknown')}\")\n        for offset, identifier, data in match.strings:\n            # Show context around the match\n            print(f\"  String {identifier} at offset {hex(offset)}\")\n            if len(data) \u003C= 64:\n                print(f\"    Data: {data.hex()}\")\n\n    return matches\n\n# Rules targeting in-memory artifacts\nmemory_rules = yara.compile(source=\"\"\"\nrule Cobalt_Strike_Beacon_Memory {\n    meta:\n        description = \"Detects Cobalt Strike beacon in process memory\"\n        severity = \"critical\"\n    strings:\n        $config_start = { 2E 2F 2E 2F 2E 2C }\n        $sleep_mask = { 48 8B 44 24 ?? 48 89 44 24 ?? 48 8B 44 24 }\n        $named_pipe = \"\\\\\\\\\\\\\\\\.\\\\\\\\pipe\\\\\\\\msagent_\" ascii\n        $watermark = { 00 00 00 00 00 00 ?? ?? 00 00 }\n    condition:\n        2 of them\n}\n\"\"\")\n\nscan_memory_dump(memory_rules, \"\u002Fmnt\u002Fevidence\u002Flsass_dump.dmp\")\n```\n\n### Step 6: Generate Rules Automatically with yarGen\n\nUse yarGen to create rules from malware samples by extracting unique strings:\n\n```bash\n# Clone and set up yarGen\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FyarGen.git\ncd yarGen\npip install -r requirements.txt\n\n# Download the string databases (run once)\npython3 yarGen.py --update\n\n# Generate rules from a directory of malware samples\npython3 yarGen.py \\\n    -m \u002Fmnt\u002Fevidence\u002Fmalware_samples\u002F \\\n    -o generated_rules.yar \\\n    --excludegood \\\n    -p \"AutoGen\" \\\n    -a \"Threat Hunting Team\" \\\n    --score 50\n\n# Generate rules for a single sample with maximum detail\npython3 yarGen.py \\\n    -m \u002Fmnt\u002Fevidence\u002Fmalware_samples\u002Fsuspicious.exe \\\n    -o single_sample_rule.yar \\\n    --opcodes \\\n    --debug\n```\n\n### Step 7: Integrate Community Rule Sets\n\nDownload and combine rules from public threat intelligence repositories:\n\n```bash\n# Clone Florian Roth's signature-base (large community rule set)\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base.git\n\n# Clone YARA-Rules community repository\ngit clone https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules.git yara-community-rules\n\n# Clone ReversingLabs YARA rules\ngit clone https:\u002F\u002Fgithub.com\u002Freversinglabs\u002Freversinglabs-yara-rules.git\n```\n\n```python\nimport yara\nfrom pathlib import Path\n\ndef load_rule_directory(rule_dir, extensions=(\".yar\", \".yara\")):\n    \"\"\"Load all YARA rules from a directory tree.\"\"\"\n    rule_files = {}\n    for ext in extensions:\n        for rule_file in Path(rule_dir).rglob(f\"*{ext}\"):\n            namespace = rule_file.stem\n            # Avoid namespace collisions\n            if namespace in rule_files:\n                namespace = f\"{rule_file.parent.name}_{namespace}\"\n            rule_files[namespace] = str(rule_file)\n\n    print(f\"Loading {len(rule_files)} rule files from {rule_dir}\")\n    try:\n        compiled = yara.compile(filepaths=rule_files)\n        return compiled\n    except yara.SyntaxError as e:\n        print(f\"Syntax error in rules: {e}\")\n        # Fall back to loading rules one by one, skipping broken ones\n        valid_rules = {}\n        for ns, path in rule_files.items():\n            try:\n                yara.compile(filepath=path)\n                valid_rules[ns] = path\n            except yara.SyntaxError:\n                print(f\"  Skipping broken rule: {path}\")\n        return yara.compile(filepaths=valid_rules)\n\n# Load and scan with community rules\ncommunity_rules = load_rule_directory(\"signature-base\u002Fyara\u002F\")\nmatches = community_rules.match(\"\u002Fmnt\u002Fevidence\u002Fsuspicious_file.exe\", timeout=120)\n\nfor m in matches:\n    print(f\"Matched: {m.rule} (namespace: {m.namespace})\")\n```\n\n### Step 8: Build a Continuous Hunting Pipeline\n\nAutomate scanning of new files as they arrive using filesystem monitoring:\n\n```python\nimport yara\nimport time\nimport json\nimport hashlib\nfrom pathlib import Path\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nclass YaraHuntingHandler(FileSystemEventHandler):\n    def __init__(self, rules, alert_file=\"yara_alerts.jsonl\"):\n        self.rules = rules\n        self.alert_file = alert_file\n        self.scanned_hashes = set()\n\n    def on_created(self, event):\n        if event.is_directory:\n            return\n        self._scan_file(event.src_path)\n\n    def _scan_file(self, filepath):\n        # Deduplicate by file hash\n        try:\n            file_hash = hashlib.sha256(Path(filepath).read_bytes()).hexdigest()\n        except (PermissionError, FileNotFoundError):\n            return\n\n        if file_hash in self.scanned_hashes:\n            return\n        self.scanned_hashes.add(file_hash)\n\n        matches = self.rules.match(filepath, timeout=60)\n        if matches:\n            alert = {\n                \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n                \"file\": filepath,\n                \"sha256\": file_hash,\n                \"matches\": [\n                    {\"rule\": m.rule, \"severity\": m.meta.get(\"severity\", \"unknown\")}\n                    for m in matches\n                ]\n            }\n            with open(self.alert_file, \"a\") as f:\n                f.write(json.dumps(alert) + \"\\n\")\n            print(f\"ALERT: {filepath} matched {len(matches)} rules\")\n\n# Set up continuous monitoring\nrules = yara.compile(filepaths={\"hunting\": \"rules\u002Fall_hunting_rules.yar\"})\nhandler = YaraHuntingHandler(rules)\nobserver = Observer()\nobserver.schedule(handler, path=\"\u002Fmnt\u002Fquarantine\u002F\", recursive=True)\nobserver.start()\nprint(\"YARA hunting pipeline active. Monitoring \u002Fmnt\u002Fquarantine\u002F ...\")\n```\n\n## Verification\n\n- Compile all custom rules without syntax errors: `yara -w rules\u002F*.yar \u002Fdev\u002Fnull`\n- Confirm rules match known-good malware samples from your test corpus (true positive validation)\n- Verify rules do NOT match a goodware corpus of common system files (false positive testing)\n- Test scanning performance: single file scan should complete within timeout threshold\n- Validate yarGen output rules compile and produce meaningful matches against the input samples\n- Check that community rule sets load without critical syntax errors after filtering\n- Confirm the continuous hunting pipeline generates alerts in JSONL format when test files are dropped\n- Cross-reference YARA matches against VirusTotal or sandbox results to validate detection accuracy\n",{"name":5,"domain":23,"description":7},"main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fmalware-tools-yara","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":42,"prompt":52,"zipAvailable":53},[43,46,49],{"tool":44,"command":45},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill malware-tools-yara",{"tool":47,"command":48},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill malware-tools-yara",{"tool":50,"command":51},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill malware-tools-yara","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-tools-yara\u002FSKILL.md",true,[55],{"path":56,"resourceType":57,"resourceTypeDesc":58,"sizeBytes":59,"sourceHtmlUrl":60},"index.json","REFERENCE","参考文档",520,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-tools-yara\u002Findex.json",[62,87,110,132,154,170],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":29},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,23,86],"services","detect","services wmi persistence detect","wmi","persistence","de","cm","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":29},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[94,69,95,72,96,97,98,23,99,100,101,102,103,104,74,105,106,107,108,109],"exploit","services wmi exec exploit","exec","remote","traffic","Bash","analysis","team","across","crackmapexec","native","command","lateral movement","read","lateral-movement","Impacket",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":29},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[117,118,119,120,121,122,23,99,123,100,124,125,74,107,126,127,128,129,130,131],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper","sonnet",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":29},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[70,139,140,141,142,143,144,75,145,23,86,146,147,148,149,150,151,152,153,74],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":155,"name":156,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":160,"publishedAt":29},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[161,162,70,163,141,143,164,75,165,145,23,86,100,166,167,168,169,153,74,76],"thread","processes thread injection detect","injection","memory","process-injection","api","apc-injection","thread-injection","nt-api",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":29},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[177,70,141,178,164,75,179,180,23,86,181,182,183,184,185,186,74,76,187,188],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]