[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B91XCPMHGEQSQKWG9TYTX8":3,"skill-same:01M7B91XCPMHGEQSQKWG9TYTX8":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":13,"repositoryHtmlUrl":53,"repositoryHomepageUrl":6,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":55,"install":56,"resources":69},"01M7B91XCPMHGEQSQKWG9TYTX8","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.","vikasvardhanv\u002Fjerry_skills","vikasvardhanv","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99010657?v=4","01M7B2B0VN78W7529RQX5BR6DZ","01M7B2B0WDNTXJHRK3QNPNWRP6",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fperforming-threat-hunting-with-yara-rules\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\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":14,"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","1eb986d0b0ecc180291597e08eb5a58288843536","skills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fperforming-threat-hunting-with-yara-rules","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv","2026-08-25 13:16:33",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add vikasvardhanv\u002Fjerry_skills --skill performing-threat-hunting-with-yara-rules",{"tool":62,"command":63},"bunx","bunx skills add vikasvardhanv\u002Fjerry_skills --skill performing-threat-hunting-with-yara-rules",{"tool":65,"command":66},"pnpm","pnpm dlx skills add vikasvardhanv\u002Fjerry_skills --skill performing-threat-hunting-with-yara-rules","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fperforming-threat-hunting-with-yara-rules\u002FSKILL.md",true,[70,74,80],{"path":71,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":15},"LICENSE","许可证",11255,{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fapi-reference.md","REFERENCE","参考文档",2176,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fperforming-threat-hunting-with-yara-rules\u002Freferences\u002Fapi-reference.md",{"path":81,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":84,"sourceHtmlUrl":85},"scripts\u002Fagent.py","SCRIPT","脚本",5743,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fperforming-threat-hunting-with-yara-rules\u002Fscripts\u002Fagent.py",[87,95,102,109,116,123],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7BESR1CJ3H5SP9XM8KYJZ9W","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Use when the user uploads a syllabus, course outline, or curriculum document and wants supplementary readings (e.g., 'create a reading list from this syllabus', 'find recent papers for my course') — even casual mentions with a syllabus attached should trigger this skill.","MIT","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7BES1YA6R97W7QPMFFM1PED","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Use when the user requests multi-source recency intelligence on a topic (e.g., 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]'), and for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7BERNHYGY035AR00VRT03KE","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Use when the user asks for patent searching or analysis (e.g., 'prior art search for [invention]', 'freedom to operate analysis for [product]'). Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M7BERCK1EAKTWW7R436WAR0J","notebooklm","Browser automation skill for controlling Google's NotebookLM. Use when the user wants anything done in NotebookLM (e.g., 'open NotebookLM', 'check my [name] notebook', 'ask my notebook about X', 'add [source] to NotebookLM', 'generate a Video Overview from my notebook', 'use NotebookLM Studio'). Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio\u002FVideo Overviews, Mind Maps, Reports incl. Briefing Doc\u002FStudy Guide\u002FFAQ, Flashcards, Quiz, slide decks, infographics — discover the exact set from the live Studio panel; the UI evolves fast), and creating new notebooks. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":19},"01M7BEQZAZAQRTXFJRY7RHV3TY","litreview","Academic literature orientation skill that searches papers via free keyless APIs (PubMed E-utilities + OpenAlex) by default — with the Consensus MCP as an optional enhancement lane when connected — builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a formatted Word (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — an orientation guide that lets a researcher dive in confidently, not a finished review. Use when the user starts literature-oriented research (e.g., 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'). Do NOT use for single one-off paper searches wanting a quick list — that's a plain PubMed\u002FOpenAlex (or Consensus) query.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[],{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":91,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":19},"01M7BEQKJ45K31QK5VRAQSVJCJ","grants","NIH grant research skill for clinical researchers. Grill-me intake (research idea + career stage + preliminary data + environment + submission posture + known institute targets) locks down the funding strategy before any search runs. Runs a 5-facet Consensus positioning analysis (with draft Significance\u002FInnovation language), maps the research to the right NIH institutes and study sections via RePORTER, finds NOSIs and funded overlap, and produces an editable Word document (.docx) with budget\u002Fscope-aware mechanism recommendations, submission timelines, and a mandatory program officer recommendation. Use when the user asks about research funding or makes any grant-related request (e.g., 'grants for [topic]', 'find grants for my research idea', 'what grants match my research', 'help me find NIH funding', 'grant opportunities for my research'). NIH-only scope — non-NIH funders (PCORI, DOD CDMRP, VA, foundations) are out of scope and flagged at intake.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fgrants\u002Fskills\u002Fgrants\u002FSKILL.md",[],[]]