[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EQAC4JW7YT6H87HASMMJAN":3,"skill-same:01M7EQAC4JW7YT6H87HASMMJAN":78},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M7EQAC4JW7YT6H87HASMMJAN","performing-threat-hunting-with-yara-rules",null,"Use YARA pattern-matching rules to hunt for malware, suspicious files, and indicators of compromise across filesystems and memory dumps. Covers rule authoring, yara-python scanning, and integration with threat intel feeds.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fperforming-threat-hunting-with-yara-rules\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: performing-threat-hunting-with-yara-rules\ndescription: 'Use YARA pattern-matching rules to hunt for malware, suspicious files,\n  and indicators of compromise across filesystems and memory dumps. Covers rule authoring,\n  yara-python scanning, and integration with threat intel feeds.\n\n  '\ndomain: cybersecurity\nsubdomain: threat-hunting\ntags:\n- yara\n- malware-detection\n- threat-hunting\n- pattern-matching\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\nd3fend_techniques:\n- Executable Denylisting\n- Execution Isolation\n- File Metadata Consistency Validation\n- Content Format Conversion\n- File Content Analysis\nnist_csf:\n- DE.CM-01\n- DE.AE-02\n- DE.AE-07\n- ID.RA-05\nmitre_attack:\n- T1046\n- T1057\n- T1082\n- T1083\n- T1005\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,"tags":24,"author":29,"domain":30,"license":15,"version":31,"nist_csf":32,"subdomain":27,"description":37,"mitre_attack":38,"d3fend_techniques":44},[25,26,27,28],"yara","malware-detection","threat-hunting","pattern-matching","mahipal","cybersecurity","1.0",[33,34,35,36],"DE.CM-01","DE.AE-02","DE.AE-07","ID.RA-05","Use YARA pattern-matching rules to hunt for malware, suspicious files, and indicators of compromise across filesystems and memory dumps. Covers rule authoring, yara-python scanning, and integration with threat intel feeds.\n",[39,40,41,42,43],"T1046","T1057","T1082","T1083","T1005",[45,46,47,48,49],"Executable Denylisting","Execution Isolation","File Metadata Consistency Validation","Content Format Conversion","File Content Analysis","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fperforming-threat-hunting-with-yara-rules",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill performing-threat-hunting-with-yara-rules",{"tool":64,"command":65},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill performing-threat-hunting-with-yara-rules",{"tool":67,"command":68},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill performing-threat-hunting-with-yara-rules","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fperforming-threat-hunting-with-yara-rules\u002FSKILL.md",true,[72],{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Fapi-reference.md","REFERENCE","参考文档",2176,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fperforming-threat-hunting-with-yara-rules\u002Freferences\u002Fapi-reference.md",[79,88,93,100,107,114],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":87},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":89,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":87},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":87},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":87},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":87},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":87},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]