[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AFX7RDZSFW2BCSEC9DC2Z5":3,"skill-same:01M6AFX7RDZSFW2BCSEC9DC2Z5":103},{"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":23,"publishedAt":41,"linkOnly":42,"markdownContent":43,"markdownBody":44,"frontMatter":45,"refName":62,"commitSha":63,"skillDirectory":64,"forksCount":65,"repositoryHtmlUrl":66,"repositoryHomepageUrl":67,"ownerHtmlUrl":68,"ownerBlogUrl":69,"ownerDescription":70,"updatedAt":71,"install":72,"resources":85},"01M6AFX7RDZSFW2BCSEC9DC2Z5","performing-malware-triage-with-yara",null,"Performs rapid malware triage and classification using YARA rules that match file patterns, strings, byte sequences, and structural characteristics against known malware families and suspicious indicators, covering rule writing, scanning, and integration into analysis pipelines. Use when classifying a batch of malware samples against known family signatures, writing detection rules for a newly analyzed malware family, or performing signature-based malware triage.","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",35990,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fperforming-malware-triage-with-yara\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40],"performing malware triage with yara","triage","malware","yara","malware-analysis","pattern-matching","classification","analysis","indicators","t1055","detection","writing","integration","file","batch","cybersecurity","suspicious","2026-11-10 10:12:30",false,"---\nname: performing-malware-triage-with-yara\ndescription: 'Performs rapid malware triage and classification using YARA rules that\n  match file patterns, strings, byte sequences, and structural characteristics against\n  known malware families and suspicious indicators, covering rule writing, scanning,\n  and integration into analysis pipelines. Use when classifying a batch of malware\n  samples against known family signatures, writing detection rules for a newly\n  analyzed malware family, or performing signature-based malware triage.\n\n  '\ndomain: cybersecurity\nsubdomain: malware-analysis\ntags:\n- malware\n- YARA\n- triage\n- classification\n- pattern-matching\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- DE.AE-02\n- RS.AN-03\n- ID.RA-01\n- DE.CM-01\nmitre_attack:\n- T1027\n- T1055\n- T1140\n- T1497\n- T0816\n---\n\n# Performing Malware Triage with YARA\n\n## When to Use\n\n- Rapidly classifying a large batch of malware samples against known family signatures\n- Writing detection rules for a newly analyzed malware family based on unique byte patterns\n- Scanning file shares, endpoints, or memory dumps for indicators of a specific threat\n- Building automated triage pipelines that classify samples before manual analysis\n- Hunting for variants of a known threat across an enterprise using YARA scans\n\n**Do not use** as the sole analysis method; YARA triage identifies known patterns but does not reveal new or unknown malware behaviors.\n\n## Prerequisites\n\n- YARA 4.x installed (`apt install yara` or `pip install yara-python`)\n- YARA rule repositories (YARA-Rules, awesome-yara, Malpedia rules, Florian Roth's signature-base)\n- Python 3.8+ with `yara-python` for scripted scanning\n- Sample collection organized in a directory structure for batch scanning\n- Understanding of PE file format, hex patterns, and regular expressions for rule writing\n\n## Workflow\n\n### Step 1: Scan Samples with Existing Rule Sets\n\nApply community and commercial YARA rules to classify samples:\n\n```bash\n# Scan a single file\nyara -s malware_rules.yar suspect.exe\n\n# Scan a directory of samples\nyara -r malware_rules.yar \u002Fpath\u002Fto\u002Fsamples\u002F\n\n# Scan with multiple rule files\nyara -r rules\u002Fapt_rules.yar rules\u002Fransomware_rules.yar rules\u002Ftrojan_rules.yar suspect.exe\n\n# Scan with timeout (prevent hanging on large files)\nyara -t 30 malware_rules.yar suspect.exe\n\n# Scan and show matching strings\nyara -s -r malware_rules.yar suspect.exe\n\n# Scan with compiled rules (faster for repeated scans)\nyarac malware_rules.yar compiled_rules.yarc\nyara compiled_rules.yarc suspect.exe\n```\n\n```bash\n# Download community rule sets\ngit clone https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules.git yara-community-rules\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base.git signature-base\n\n# Scan with signature-base\nyara -r signature-base\u002Fyara\u002F*.yar suspect.exe\n```\n\n### Step 2: Write Rules for Unique String Patterns\n\nCreate YARA rules based on strings extracted during malware analysis:\n\n```\nrule MalwareX_Strings {\n    meta:\n        description = \"Detects MalwareX based on unique strings\"\n        author = \"analyst\"\n        date = \"2025-09-15\"\n        reference = \"Internal Analysis Report #1547\"\n        hash = \"e3b0c44298fc1c149afbf4c8996fb924\"\n        tlp = \"WHITE\"\n\n    strings:\n        \u002F\u002F C2 URL pattern\n        $url1 = \"\u002Fgate.php?id=\" ascii\n        $url2 = \"\u002Fpanel\u002Fconnect.php\" ascii\n\n        \u002F\u002F Unique mutex name\n        $mutex = \"Global\\\\CryptLocker_2025\" ascii wide\n\n        \u002F\u002F User-Agent string\n        $ua = \"Mozilla\u002F5.0 (compatible; MSIE 10.0)\" ascii\n\n        \u002F\u002F Registry persistence path\n        $reg = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\\\\WindowsUpdate\" ascii\n\n        \u002F\u002F Campaign identifier\n        $campaign = \"campaign_2025_q3\" ascii\n\n    condition:\n        uint16(0) == 0x5A4D and      \u002F\u002F PE file (MZ header)\n        filesize \u003C 500KB and          \u002F\u002F Size constraint\n        ($url1 or $url2) and          \u002F\u002F At least one C2 URL\n        ($mutex or $campaign) and     \u002F\u002F Campaign identifier\n        $ua                           \u002F\u002F Specific User-Agent\n}\n```\n\n### Step 3: Write Rules for Byte Patterns\n\nCreate rules matching specific code sequences:\n\n```\nrule MalwareX_Decryptor {\n    meta:\n        description = \"Detects MalwareX XOR decryption routine\"\n        author = \"analyst\"\n        date = \"2025-09-15\"\n\n    strings:\n        \u002F\u002F XOR decryption loop (x86 assembly)\n        \u002F\u002F mov al, [esi+ecx]\n        \u002F\u002F xor al, [edi+ecx]\n        \u002F\u002F mov [esi+ecx], al\n        \u002F\u002F inc ecx\n        \u002F\u002F cmp ecx, edx\n        \u002F\u002F jl loop\n        $xor_loop = { 8A 04 0E 32 04 0F 88 04 0E 41 3B CA 7C F3 }\n\n        \u002F\u002F RC4 KSA initialization (256-byte loop)\n        $rc4_ksa = { 33 C0 88 04 ?8 40 3D 00 01 00 00 7? }\n\n        \u002F\u002F Embedded RSA public key marker\n        $rsa_key = { 06 02 00 00 00 A4 00 00 52 53 41 31 }  \u002F\u002F PUBLICKEYBLOB\n\n    condition:\n        uint16(0) == 0x5A4D and\n        ($xor_loop or $rc4_ksa) and\n        $rsa_key\n}\n```\n\n### Step 4: Write Rules with PE Module\n\nLeverage YARA's PE module for structural detection:\n\n```\nimport \"pe\"\nimport \"hash\"\nimport \"math\"\n\nrule MalwareX_PE_Characteristics {\n    meta:\n        description = \"Detects MalwareX by PE structure and imports\"\n        author = \"analyst\"\n\n    condition:\n        pe.is_pe and\n\n        \u002F\u002F Compiled within specific timeframe\n        pe.timestamp > 1693526400 and   \u002F\u002F After 2023-09-01\n        pe.timestamp \u003C 1727740800 and   \u002F\u002F Before 2024-10-01\n\n        \u002F\u002F Specific import hash\n        pe.imphash() == \"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6\" or\n\n        \u002F\u002F Suspicious import combination\n        (\n            pe.imports(\"kernel32.dll\", \"VirtualAllocEx\") and\n            pe.imports(\"kernel32.dll\", \"WriteProcessMemory\") and\n            pe.imports(\"kernel32.dll\", \"CreateRemoteThread\") and\n            pe.imports(\"wininet.dll\", \"InternetOpenA\")\n        ) or\n\n        \u002F\u002F High entropy .text section (packed)\n        (\n            for any section in pe.sections : (\n                section.name == \".text\" and\n                math.entropy(section.raw_data_offset, section.raw_data_size) > 7.0\n            )\n        )\n}\n\nrule MalwareX_Rich_Header {\n    meta:\n        description = \"Detects MalwareX by Rich header hash\"\n\n    condition:\n        pe.is_pe and\n        hash.md5(pe.rich_signature.clear_data) == \"abc123def456abc123def456abc123de\"\n}\n```\n\n### Step 5: Batch Triage with Python\n\nAutomate scanning of sample collections:\n\n```python\nimport yara\nimport os\nimport json\nimport hashlib\nfrom datetime import datetime\n\n# Compile all rule files\nrule_files = {\n    \"apt\": \"rules\u002Fapt_rules.yar\",\n    \"ransomware\": \"rules\u002Fransomware_rules.yar\",\n    \"trojan\": \"rules\u002Ftrojan_rules.yar\",\n    \"custom\": \"rules\u002Fcustom_rules.yar\",\n}\nrules = yara.compile(filepaths=rule_files)\n\n# Scan sample directory\nresults = []\nsample_dir = \"\u002Fpath\u002Fto\u002Fsamples\"\n\nfor filename in os.listdir(sample_dir):\n    filepath = os.path.join(sample_dir, filename)\n    if not os.path.isfile(filepath):\n        continue\n\n    with open(filepath, \"rb\") as f:\n        data = f.read()\n        sha256 = hashlib.sha256(data).hexdigest()\n\n    matches = rules.match(filepath)\n\n    result = {\n        \"filename\": filename,\n        \"sha256\": sha256,\n        \"size\": len(data),\n        \"matches\": [],\n        \"classification\": \"UNKNOWN\",\n    }\n\n    for match in matches:\n        result[\"matches\"].append({\n            \"rule\": match.rule,\n            \"namespace\": match.namespace,\n            \"tags\": match.tags,\n            \"strings\": [(hex(s[0]), s[1], s[2].decode(\"utf-8\", errors=\"replace\")[:100])\n                       for s in match.strings] if match.strings else []\n        })\n\n    if result[\"matches\"]:\n        result[\"classification\"] = result[\"matches\"][0][\"namespace\"].upper()\n\n    results.append(result)\n\n# Summary\nclassified = sum(1 for r in results if r[\"classification\"] != \"UNKNOWN\")\nprint(f\"Scanned: {len(results)} samples\")\nprint(f\"Classified: {classified} ({classified\u002Flen(results)*100:.1f}%)\")\nprint(f\"Unknown: {len(results)-classified}\")\n\n# Export results\nwith open(\"triage_results.json\", \"w\") as f:\n    json.dump(results, f, indent=2)\n```\n\n### Step 6: Validate and Optimize Rules\n\nTest rules for false positives and performance:\n\n```bash\n# Test rule syntax\nyara -C custom_rules.yar\n\n# Scan known-clean directory to check false positives\nyara -r custom_rules.yar \u002Fpath\u002Fto\u002Fclean_files\u002F > false_positives.txt\nwc -l false_positives.txt\n\n# Benchmark rule performance\ntime yara -r custom_rules.yar \u002Fpath\u002Fto\u002Flarge_sample_collection\u002F\n\n# Profile individual rule performance\nyara -p custom_rules.yar suspect.exe\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **YARA Rule** | Pattern matching rule defining strings, byte sequences, and conditions that identify a specific file or malware family |\n| **Condition** | Boolean expression combining string matches, file properties, and module functions to determine if a rule matches |\n| **Hex String** | Byte pattern with optional wildcards (??) and jumps ([N-M]) for matching machine code or binary data |\n| **PE Module** | YARA module providing access to PE file properties (imports, sections, timestamps, resources) for structural matching |\n| **Imphash** | MD5 hash of a PE file's import table; samples from the same family often share import hashes |\n| **Rich Header** | Undocumented PE structure containing compiler\u002Flinker metadata; consistent within malware build environments |\n| **YARA-C** | Compiled YARA rule format enabling faster scanning by pre-compiling rules for repeated use |\n\n## Tools & Systems\n\n- **YARA**: Pattern matching engine for identifying and classifying malware based on text, hex, and structural patterns\n- **yara-python**: Python bindings for YARA enabling scripted scanning, rule compilation, and integration with analysis pipelines\n- **yarGen**: Automatic YARA rule generator that creates rules from malware samples by identifying unique strings and opcodes\n- **YARA-Rules (GitHub)**: Community-maintained repository of YARA rules covering malware families, exploits, and suspicious indicators\n- **Malpedia YARA**: Curated YARA rules from the Malpedia malware encyclopedia with high-quality family-specific rules\n\n## Common Scenarios\n\n### Scenario: Creating Detection Rules for a New Malware Family\n\n**Context**: Reverse engineering of a new malware sample has identified unique strings, byte patterns, and PE characteristics. YARA rules are needed for enterprise-wide hunting and ongoing detection.\n\n**Approach**:\n1. Extract unique strings from the unpacked binary (C2 URLs, mutex names, registry paths)\n2. Identify unique byte sequences from the encryption routine or C2 protocol (from Ghidra analysis)\n3. Record PE characteristics (imphash, Rich header hash, section names, compilation timestamp range)\n4. Write a YARA rule combining string, byte pattern, and PE module conditions\n5. Test against the known malware samples to confirm true positive detection\n6. Test against a clean file corpus (Windows system files, common applications) to verify zero false positives\n7. Deploy to enterprise scanning infrastructure and threat intelligence platform\n\n**Pitfalls**:\n- Writing rules too specific to a single sample (will not detect variants with minor changes)\n- Writing rules too generic (matching legitimate software, causing false positives)\n- Using strings that appear in common libraries or frameworks (e.g., OpenSSL strings)\n- Not testing on a sufficiently large clean corpus before deployment\n\n## Output Format\n\n```\nYARA TRIAGE RESULTS\n=====================\nScan Date:        2025-09-15\nRule Sets:        apt_rules (847 rules), ransomware_rules (312 rules),\n                  trojan_rules (1,204 rules), custom_rules (45 rules)\nSamples Scanned:  2,500\nProcessing Time:  47 seconds\n\nCLASSIFICATION SUMMARY\nAPT:              12 samples (0.5%)\nRansomware:       187 samples (7.5%)\nTrojan:           423 samples (16.9%)\nUnknown:          1,878 samples (75.1%)\n\nTOP MATCHING RULES\nRule                         Matches  Family\nMalwareX_C2_Beacon           45       MalwareX\nLockBit3_Ransom_Note         38       LockBit 3.0\nEmotet_Epoch5_Loader         32       Emotet\nCobaltStrike_Beacon_Config   28       Cobalt Strike\nQakBot_DLL_Loader            25       QakBot\n\nSAMPLE DETAIL\nFile:    suspect.exe\nSHA-256: e3b0c44298fc1c149afbf4c8996fb924...\nMatches:\n  [1] MalwareX_Strings (custom)\n      - $url1 at 0x4A20: \"\u002Fgate.php?id=\"\n      - $mutex at 0x5100: \"Global\\\\CryptLocker_2025\"\n  [2] MalwareX_Decryptor (custom)\n      - $xor_loop at 0x401200: { 8A 04 0E 32 04 0F ... }\n  [3] MalwareX_PE_Characteristics (custom)\n      - PE import combination matched\nClassification: MALWAREX (HIGH CONFIDENCE)\n```\n","# Performing Malware Triage with YARA\n\n## When to Use\n\n- Rapidly classifying a large batch of malware samples against known family signatures\n- Writing detection rules for a newly analyzed malware family based on unique byte patterns\n- Scanning file shares, endpoints, or memory dumps for indicators of a specific threat\n- Building automated triage pipelines that classify samples before manual analysis\n- Hunting for variants of a known threat across an enterprise using YARA scans\n\n**Do not use** as the sole analysis method; YARA triage identifies known patterns but does not reveal new or unknown malware behaviors.\n\n## Prerequisites\n\n- YARA 4.x installed (`apt install yara` or `pip install yara-python`)\n- YARA rule repositories (YARA-Rules, awesome-yara, Malpedia rules, Florian Roth's signature-base)\n- Python 3.8+ with `yara-python` for scripted scanning\n- Sample collection organized in a directory structure for batch scanning\n- Understanding of PE file format, hex patterns, and regular expressions for rule writing\n\n## Workflow\n\n### Step 1: Scan Samples with Existing Rule Sets\n\nApply community and commercial YARA rules to classify samples:\n\n```bash\n# Scan a single file\nyara -s malware_rules.yar suspect.exe\n\n# Scan a directory of samples\nyara -r malware_rules.yar \u002Fpath\u002Fto\u002Fsamples\u002F\n\n# Scan with multiple rule files\nyara -r rules\u002Fapt_rules.yar rules\u002Fransomware_rules.yar rules\u002Ftrojan_rules.yar suspect.exe\n\n# Scan with timeout (prevent hanging on large files)\nyara -t 30 malware_rules.yar suspect.exe\n\n# Scan and show matching strings\nyara -s -r malware_rules.yar suspect.exe\n\n# Scan with compiled rules (faster for repeated scans)\nyarac malware_rules.yar compiled_rules.yarc\nyara compiled_rules.yarc suspect.exe\n```\n\n```bash\n# Download community rule sets\ngit clone https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules.git yara-community-rules\ngit clone https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base.git signature-base\n\n# Scan with signature-base\nyara -r signature-base\u002Fyara\u002F*.yar suspect.exe\n```\n\n### Step 2: Write Rules for Unique String Patterns\n\nCreate YARA rules based on strings extracted during malware analysis:\n\n```\nrule MalwareX_Strings {\n    meta:\n        description = \"Detects MalwareX based on unique strings\"\n        author = \"analyst\"\n        date = \"2025-09-15\"\n        reference = \"Internal Analysis Report #1547\"\n        hash = \"e3b0c44298fc1c149afbf4c8996fb924\"\n        tlp = \"WHITE\"\n\n    strings:\n        \u002F\u002F C2 URL pattern\n        $url1 = \"\u002Fgate.php?id=\" ascii\n        $url2 = \"\u002Fpanel\u002Fconnect.php\" ascii\n\n        \u002F\u002F Unique mutex name\n        $mutex = \"Global\\\\CryptLocker_2025\" ascii wide\n\n        \u002F\u002F User-Agent string\n        $ua = \"Mozilla\u002F5.0 (compatible; MSIE 10.0)\" ascii\n\n        \u002F\u002F Registry persistence path\n        $reg = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\\\\WindowsUpdate\" ascii\n\n        \u002F\u002F Campaign identifier\n        $campaign = \"campaign_2025_q3\" ascii\n\n    condition:\n        uint16(0) == 0x5A4D and      \u002F\u002F PE file (MZ header)\n        filesize \u003C 500KB and          \u002F\u002F Size constraint\n        ($url1 or $url2) and          \u002F\u002F At least one C2 URL\n        ($mutex or $campaign) and     \u002F\u002F Campaign identifier\n        $ua                           \u002F\u002F Specific User-Agent\n}\n```\n\n### Step 3: Write Rules for Byte Patterns\n\nCreate rules matching specific code sequences:\n\n```\nrule MalwareX_Decryptor {\n    meta:\n        description = \"Detects MalwareX XOR decryption routine\"\n        author = \"analyst\"\n        date = \"2025-09-15\"\n\n    strings:\n        \u002F\u002F XOR decryption loop (x86 assembly)\n        \u002F\u002F mov al, [esi+ecx]\n        \u002F\u002F xor al, [edi+ecx]\n        \u002F\u002F mov [esi+ecx], al\n        \u002F\u002F inc ecx\n        \u002F\u002F cmp ecx, edx\n        \u002F\u002F jl loop\n        $xor_loop = { 8A 04 0E 32 04 0F 88 04 0E 41 3B CA 7C F3 }\n\n        \u002F\u002F RC4 KSA initialization (256-byte loop)\n        $rc4_ksa = { 33 C0 88 04 ?8 40 3D 00 01 00 00 7? }\n\n        \u002F\u002F Embedded RSA public key marker\n        $rsa_key = { 06 02 00 00 00 A4 00 00 52 53 41 31 }  \u002F\u002F PUBLICKEYBLOB\n\n    condition:\n        uint16(0) == 0x5A4D and\n        ($xor_loop or $rc4_ksa) and\n        $rsa_key\n}\n```\n\n### Step 4: Write Rules with PE Module\n\nLeverage YARA's PE module for structural detection:\n\n```\nimport \"pe\"\nimport \"hash\"\nimport \"math\"\n\nrule MalwareX_PE_Characteristics {\n    meta:\n        description = \"Detects MalwareX by PE structure and imports\"\n        author = \"analyst\"\n\n    condition:\n        pe.is_pe and\n\n        \u002F\u002F Compiled within specific timeframe\n        pe.timestamp > 1693526400 and   \u002F\u002F After 2023-09-01\n        pe.timestamp \u003C 1727740800 and   \u002F\u002F Before 2024-10-01\n\n        \u002F\u002F Specific import hash\n        pe.imphash() == \"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6\" or\n\n        \u002F\u002F Suspicious import combination\n        (\n            pe.imports(\"kernel32.dll\", \"VirtualAllocEx\") and\n            pe.imports(\"kernel32.dll\", \"WriteProcessMemory\") and\n            pe.imports(\"kernel32.dll\", \"CreateRemoteThread\") and\n            pe.imports(\"wininet.dll\", \"InternetOpenA\")\n        ) or\n\n        \u002F\u002F High entropy .text section (packed)\n        (\n            for any section in pe.sections : (\n                section.name == \".text\" and\n                math.entropy(section.raw_data_offset, section.raw_data_size) > 7.0\n            )\n        )\n}\n\nrule MalwareX_Rich_Header {\n    meta:\n        description = \"Detects MalwareX by Rich header hash\"\n\n    condition:\n        pe.is_pe and\n        hash.md5(pe.rich_signature.clear_data) == \"abc123def456abc123def456abc123de\"\n}\n```\n\n### Step 5: Batch Triage with Python\n\nAutomate scanning of sample collections:\n\n```python\nimport yara\nimport os\nimport json\nimport hashlib\nfrom datetime import datetime\n\n# Compile all rule files\nrule_files = {\n    \"apt\": \"rules\u002Fapt_rules.yar\",\n    \"ransomware\": \"rules\u002Fransomware_rules.yar\",\n    \"trojan\": \"rules\u002Ftrojan_rules.yar\",\n    \"custom\": \"rules\u002Fcustom_rules.yar\",\n}\nrules = yara.compile(filepaths=rule_files)\n\n# Scan sample directory\nresults = []\nsample_dir = \"\u002Fpath\u002Fto\u002Fsamples\"\n\nfor filename in os.listdir(sample_dir):\n    filepath = os.path.join(sample_dir, filename)\n    if not os.path.isfile(filepath):\n        continue\n\n    with open(filepath, \"rb\") as f:\n        data = f.read()\n        sha256 = hashlib.sha256(data).hexdigest()\n\n    matches = rules.match(filepath)\n\n    result = {\n        \"filename\": filename,\n        \"sha256\": sha256,\n        \"size\": len(data),\n        \"matches\": [],\n        \"classification\": \"UNKNOWN\",\n    }\n\n    for match in matches:\n        result[\"matches\"].append({\n            \"rule\": match.rule,\n            \"namespace\": match.namespace,\n            \"tags\": match.tags,\n            \"strings\": [(hex(s[0]), s[1], s[2].decode(\"utf-8\", errors=\"replace\")[:100])\n                       for s in match.strings] if match.strings else []\n        })\n\n    if result[\"matches\"]:\n        result[\"classification\"] = result[\"matches\"][0][\"namespace\"].upper()\n\n    results.append(result)\n\n# Summary\nclassified = sum(1 for r in results if r[\"classification\"] != \"UNKNOWN\")\nprint(f\"Scanned: {len(results)} samples\")\nprint(f\"Classified: {classified} ({classified\u002Flen(results)*100:.1f}%)\")\nprint(f\"Unknown: {len(results)-classified}\")\n\n# Export results\nwith open(\"triage_results.json\", \"w\") as f:\n    json.dump(results, f, indent=2)\n```\n\n### Step 6: Validate and Optimize Rules\n\nTest rules for false positives and performance:\n\n```bash\n# Test rule syntax\nyara -C custom_rules.yar\n\n# Scan known-clean directory to check false positives\nyara -r custom_rules.yar \u002Fpath\u002Fto\u002Fclean_files\u002F > false_positives.txt\nwc -l false_positives.txt\n\n# Benchmark rule performance\ntime yara -r custom_rules.yar \u002Fpath\u002Fto\u002Flarge_sample_collection\u002F\n\n# Profile individual rule performance\nyara -p custom_rules.yar suspect.exe\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **YARA Rule** | Pattern matching rule defining strings, byte sequences, and conditions that identify a specific file or malware family |\n| **Condition** | Boolean expression combining string matches, file properties, and module functions to determine if a rule matches |\n| **Hex String** | Byte pattern with optional wildcards (??) and jumps ([N-M]) for matching machine code or binary data |\n| **PE Module** | YARA module providing access to PE file properties (imports, sections, timestamps, resources) for structural matching |\n| **Imphash** | MD5 hash of a PE file's import table; samples from the same family often share import hashes |\n| **Rich Header** | Undocumented PE structure containing compiler\u002Flinker metadata; consistent within malware build environments |\n| **YARA-C** | Compiled YARA rule format enabling faster scanning by pre-compiling rules for repeated use |\n\n## Tools & Systems\n\n- **YARA**: Pattern matching engine for identifying and classifying malware based on text, hex, and structural patterns\n- **yara-python**: Python bindings for YARA enabling scripted scanning, rule compilation, and integration with analysis pipelines\n- **yarGen**: Automatic YARA rule generator that creates rules from malware samples by identifying unique strings and opcodes\n- **YARA-Rules (GitHub)**: Community-maintained repository of YARA rules covering malware families, exploits, and suspicious indicators\n- **Malpedia YARA**: Curated YARA rules from the Malpedia malware encyclopedia with high-quality family-specific rules\n\n## Common Scenarios\n\n### Scenario: Creating Detection Rules for a New Malware Family\n\n**Context**: Reverse engineering of a new malware sample has identified unique strings, byte patterns, and PE characteristics. YARA rules are needed for enterprise-wide hunting and ongoing detection.\n\n**Approach**:\n1. Extract unique strings from the unpacked binary (C2 URLs, mutex names, registry paths)\n2. Identify unique byte sequences from the encryption routine or C2 protocol (from Ghidra analysis)\n3. Record PE characteristics (imphash, Rich header hash, section names, compilation timestamp range)\n4. Write a YARA rule combining string, byte pattern, and PE module conditions\n5. Test against the known malware samples to confirm true positive detection\n6. Test against a clean file corpus (Windows system files, common applications) to verify zero false positives\n7. Deploy to enterprise scanning infrastructure and threat intelligence platform\n\n**Pitfalls**:\n- Writing rules too specific to a single sample (will not detect variants with minor changes)\n- Writing rules too generic (matching legitimate software, causing false positives)\n- Using strings that appear in common libraries or frameworks (e.g., OpenSSL strings)\n- Not testing on a sufficiently large clean corpus before deployment\n\n## Output Format\n\n```\nYARA TRIAGE RESULTS\n=====================\nScan Date:        2025-09-15\nRule Sets:        apt_rules (847 rules), ransomware_rules (312 rules),\n                  trojan_rules (1,204 rules), custom_rules (45 rules)\nSamples Scanned:  2,500\nProcessing Time:  47 seconds\n\nCLASSIFICATION SUMMARY\nAPT:              12 samples (0.5%)\nRansomware:       187 samples (7.5%)\nTrojan:           423 samples (16.9%)\nUnknown:          1,878 samples (75.1%)\n\nTOP MATCHING RULES\nRule                         Matches  Family\nMalwareX_C2_Beacon           45       MalwareX\nLockBit3_Ransom_Note         38       LockBit 3.0\nEmotet_Epoch5_Loader         32       Emotet\nCobaltStrike_Beacon_Config   28       Cobalt Strike\nQakBot_DLL_Loader            25       QakBot\n\nSAMPLE DETAIL\nFile:    suspect.exe\nSHA-256: e3b0c44298fc1c149afbf4c8996fb924...\nMatches:\n  [1] MalwareX_Strings (custom)\n      - $url1 at 0x4A20: \"\u002Fgate.php?id=\"\n      - $mutex at 0x5100: \"Global\\\\CryptLocker_2025\"\n  [2] MalwareX_Decryptor (custom)\n      - $xor_loop at 0x401200: { 8A 04 0E 32 04 0F ... }\n  [3] MalwareX_PE_Characteristics (custom)\n      - PE import combination matched\nClassification: MALWAREX (HIGH CONFIDENCE)\n```\n",{"name":5,"tags":46,"author":48,"domain":39,"license":15,"version":49,"nist_csf":50,"subdomain":28,"description":55,"mitre_attack":56},[26,47,25,30,29],"YARA","mahipal","1.0.0",[51,52,53,54],"DE.AE-02","RS.AN-03","ID.RA-01","DE.CM-01","Performs rapid malware triage and classification using YARA rules that match file patterns, strings, byte sequences, and structural characteristics against known malware families and suspicious indicators, covering rule writing, scanning, and integration into analysis pipelines. Use when classifying a batch of malware samples against known family signatures, writing detection rules for a newly analyzed malware family, or performing signature-based malware triage.\n",[57,58,59,60,61],"T1027","T1055","T1140","T1497","T0816","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fperforming-malware-triage-with-yara",4395,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","https:\u002F\u002Fmahipal.engineer\u002FAnthropic-Cybersecurity-Skills\u002F","https:\u002F\u002Fgithub.com\u002Fmukul975","Mahipal.engineer","🔐 Cybersecurity | 💻 Dev | 📷 Street Photographer\r\n🎓 MSc | 📚 Research & AI Security","2026-08-31 12:32:44",{"source":8,"skillName":5,"commands":73,"prompt":83,"zipAvailable":84},[74,77,80],{"tool":75,"command":76},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill performing-malware-triage-with-yara",{"tool":78,"command":79},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill performing-malware-triage-with-yara",{"tool":81,"command":82},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill performing-malware-triage-with-yara","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fperforming-malware-triage-with-yara\u002FSKILL.md",true,[86,91,97],{"path":87,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fperforming-malware-triage-with-yara\u002FLICENSE",{"path":92,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Fapi-reference.md","REFERENCE","参考文档",1628,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fperforming-malware-triage-with-yara\u002Freferences\u002Fapi-reference.md",{"path":98,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":101,"sourceHtmlUrl":102},"scripts\u002Fagent.py","SCRIPT","脚本",6433,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fperforming-malware-triage-with-yara\u002Fscripts\u002Fagent.py",[104,131,155,182,208,235],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":111,"publishedAt":41},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","Verifies artifact signatures and SLSA provenance using Sigstore's cosign (verify, verify-attestation, verify-blob-attestation) and slsa-verifier (verify-artifact), enforcing keyless OIDC builder identity and source repo against SLSA Build levels. Use in CI\u002FCD before deploying artifacts, when consuming third-party attestations, establishing a SLSA Build L3 pipeline, or confirming provenance during incident response or admission control.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[110],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[112,113,114,115,116,39,117,118,119,120,121,122,123,124,125,126,127,128,129,130],"sigstore","provenance","slsa","verifying build provenance with slsa sigstore","security","incident response","identity","pr","code","artifacts","ci","supply-chain","pipeline","supply-chain-security","t1195","attestation","code-signing","cosign","keyless",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":138,"publishedAt":41},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","Verifies TPM 2.0 measured-boot integrity and remote attestation with tpm2-tools -- reading PCRs (tpm2_pcrread), replaying the boot event log, generating and checking signed quotes (tpm2_quote\u002Ftpm2_checkquote), and sealing secrets to a PCR policy. Use to confirm a system booted trusted firmware\u002Fkernel for Zero Trust device posture, detect boot-chain tampering via PCR drift, or build a golden-value baseline for fleet attestation.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[137],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[139,127,140,141,116,142,39,119,143,144,145,146,147,148,149,150,151,152,153,154],"boot","TPM","validating tpm measured boot attestation","policy","verification","ZeRO","firmware","Tools","measured-boot","PCR","integrity","secrets","remote-attestation","tpm2-tools","integrity-verification","trusted-computing",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":165,"publishedAt":41},"01M6AGDCW0Y4FXZ3362GT1941M","validating-backup-integrity-for-recovery","Validates backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to confirm backups are reliable for disaster recovery and ransomware response. Use before relying on backups for recovery, when building post-backup validation pipelines, auditing backup infrastructure for compliance, or checking immutable\u002Fair-gapped backups for silent corruption or tampering.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[161,164],{"categoryNo":162,"categoryName":163,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[149,166,167,168,169,39,170,171,143,172,173,174,175,176,34,177,178,179,180,181],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","validation","compliance","hash-verification","incident-response","ransomware","cryptocurrency","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":183,"name":184,"nameZh":6,"description":185,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":186,"categories":187,"keywords":189,"publishedAt":41},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","Runs KAPE (Kroll Artifact Parser and Extractor) to collect targeted forensic artifacts (registry hives, $MFT, event logs, prefetch, browser data) via Targets and parse them with Modules wrapping Eric Zimmerman's EZ Tools (PECmd, MFTECmd, RECmd). Use during early incident containment\u002Ftriage when full disk imaging is impractical but a defensible, parseable Windows artifact set is needed quickly, including at-scale remote collection.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[188],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[190,191,192,39,193,194,195,196,197,198,199,200,201,202,203,204,146,205,206,207],"windows","kape","triaging windows with kape","registry","browser","logs","windows-forensics","dfir","mft","mftecmd","data","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":209,"name":210,"nameZh":6,"description":211,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":212,"categories":213,"keywords":215,"publishedAt":41},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","Triages and prioritizes vulnerabilities with CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree, weighing exploitation status (via the CISA KEV catalog and FIRST EPSS API), technical impact, automatability, and mission prevalence to output Track\u002FTrack*\u002FAttend\u002FAct decisions. Use when prioritizing vulnerability scan results (OpenVAS, Nessus, Qualys) for remediation planning beyond raw CVSS scores.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[214],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[216,217,218,39,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234],"vulnerabilities","framework","triaging vulnerabilities with ssvc framework","status","planning","CISA","vulnerability-management","risk-management","nessus","qualys","openvas","cvss","remediation","risk","vulnerability","api","prioritization","ssvc","decision-tree",{"skillNo":236,"name":237,"nameZh":6,"description":238,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":239,"categories":240,"keywords":242,"publishedAt":41},"01M6AGD24TTQQM4CXG69E3B9TJ","triaging-security-incident","Performs initial triage of security incidents using the NIST SP 800-61r3 and SANS PICERL frameworks, classifying incident type, assigning priority by business impact, and routing to the appropriate response team. Use when a SIEM\u002FEDR alert needs human classification, concurrent alerts must be prioritized, or a user report or threat-intel IOC match requires initial incident categorization.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[241],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[116,243,39,244,37,245,246,247,248,249,250,177,251,178,31,30,252,253,254,255],"triaging security incident","siem","ioc","soc","NIST-800-61","NIST","severity","edr","execution","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]