[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HNKYQZ05MMNREXMJMP2KE5":3,"skill-same:01M6HNKYQZ05MMNREXMJMP2KE5":117},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":60,"commitSha":61,"skillDirectory":62,"forksCount":63,"repositoryHtmlUrl":64,"repositoryHomepageUrl":6,"ownerHtmlUrl":65,"ownerBlogUrl":6,"ownerDescription":66,"updatedAt":67,"install":68,"resources":81},"01M6HNKYQZ05MMNREXMJMP2KE5","performing-yara-rule-development-for-detection",null,"Develop precise YARA rules for malware detection by identifying unique byte patterns, strings, and behavioral indicators in executable files while minimizing false positives.","HenriqueMC17\u002Fagente-core","HenriqueMC17","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F206460478?v=4","01M6HB63HBBF18AC4H09XTB549","Henrique Monteiro Cardoso","01M6HB63NGSQXWKWCFWW2B20W0",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"development","performing","for","rule","performing yara rule development for detection","detection","yara","analysis","signature-development","yara-x","indicator-development","cm","files","malware detection","false","de","hunting","strings","threat-hunting","cybersecurity","2026-11-10 10:12:30",false,"---\nname: performing-yara-rule-development-for-detection\ndescription: Develop precise YARA rules for malware detection by identifying unique byte patterns, strings, and behavioral indicators in executable files while minimizing false positives.\ndomain: cybersecurity\nsubdomain: malware-analysis\ntags:\n- yara\n- malware-detection\n- signature-development\n- threat-hunting\n- pattern-matching\n- yara-x\n- indicator-development\nversion: '1.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\ncategory: performing-yara-rule-development-for-detection\n---\n# Performing YARA Rule Development for Detection\n\n## Overview\n\nYARA is the pattern matching swiss knife for malware researchers, enabling identification and classification of malware based on textual or binary patterns. Effective YARA rules combine unique string patterns, byte sequences, PE header characteristics, import table analysis, and conditional logic to detect malware families while avoiding false positives. Modern YARA-X (rewritten in Rust, stable since June 2025) brings improved performance and new modules. Rules should target unpacked malware artifacts like hardcoded stack strings, C2 URLs, mutex names, encryption constants, and unique code sequences rather than packer signatures.\n\n\n## When to Use\n\n- When conducting security assessments that involve performing yara rule development for detection\n- When following incident response procedures for related security events\n- When performing scheduled security testing or auditing activities\n- When validating security controls through hands-on testing\n\n## Prerequisites\n\n- Python 3.9+ with `yara-python` library\n- YARA 4.5+ or YARA-X 0.10+\n- PE analysis tools (`pefile`, `pestudio`)\n- Hex editor for identifying unique byte patterns\n- Access to malware samples (VirusTotal, MalwareBazaar)\n- Understanding of PE file format, strings, and import tables\n\n## Key Concepts\n\n### Rule Structure\n\nEvery YARA rule consists of three sections: `meta` (optional descriptive metadata), `strings` (pattern definitions), and `condition` (matching logic). String types include text strings (ASCII\u002Fwide\u002Fnocase), hex patterns with wildcards and jumps, and regular expressions. Conditions combine string matches with file properties using boolean operators.\n\n### String Selection Strategy\n\nEffective rules target patterns that are unique to the malware family and survive recompilation. Hardcoded stack strings are excellent choices because compilers embed them consistently. C2 domain patterns, custom encryption routines, unique error messages, and specific API call sequences provide stable detection anchors. Avoid compiler-generated boilerplate and common library strings.\n\n### Performance Optimization\n\nYARA evaluates conditions short-circuit style. Place the most discriminating and cheapest-to-evaluate conditions first. Use `filesize` limits to skip irrelevant files quickly. Minimize regex usage in favor of hex patterns. Use `private` rules as building blocks for complex detection logic without generating standalone matches.\n\n## Workflow\n\n### Step 1: Analyze Sample for Unique Patterns\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Extract candidate strings and byte patterns for YARA rule creation.\"\"\"\nimport pefile\nimport re\nimport sys\nfrom collections import Counter\n\n\ndef extract_strings(filepath, min_length=6):\n    \"\"\"Extract ASCII and wide strings from binary.\"\"\"\n    with open(filepath, 'rb') as f:\n        data = f.read()\n\n    # ASCII strings\n    ascii_strings = re.findall(\n        rb'[\\x20-\\x7e]{' + str(min_length).encode() + rb',}', data\n    )\n\n    # Wide (UTF-16LE) strings\n    wide_strings = re.findall(\n        rb'(?:[\\x20-\\x7e]\\x00){' + str(min_length).encode() + rb',}', data\n    )\n\n    return {\n        'ascii': [s.decode('ascii') for s in ascii_strings],\n        'wide': [s.decode('utf-16-le') for s in wide_strings],\n    }\n\n\ndef analyze_pe_imports(filepath):\n    \"\"\"Extract import table for API-based detection.\"\"\"\n    try:\n        pe = pefile.PE(filepath)\n    except pefile.PEFormatError:\n        return []\n\n    imports = []\n    if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):\n        for entry in pe.DIRECTORY_ENTRY_IMPORT:\n            dll_name = entry.dll.decode('utf-8', errors='replace')\n            for imp in entry.imports:\n                if imp.name:\n                    func_name = imp.name.decode('utf-8', errors='replace')\n                    imports.append(f\"{dll_name}!{func_name}\")\n    return imports\n\n\ndef find_unique_byte_patterns(filepath, pattern_length=16):\n    \"\"\"Find unique byte sequences suitable for YARA hex patterns.\"\"\"\n    with open(filepath, 'rb') as f:\n        data = f.read()\n\n    try:\n        pe = pefile.PE(filepath)\n        # Focus on code section\n        for section in pe.sections:\n            if section.Characteristics & 0x20000000:  # IMAGE_SCN_MEM_EXECUTE\n                code_start = section.PointerToRawData\n                code_end = code_start + section.SizeOfRawData\n                code_data = data[code_start:code_end]\n                break\n        else:\n            code_data = data\n    except Exception:\n        code_data = data\n\n    # Find byte patterns that appear exactly once\n    patterns = []\n    for i in range(0, len(code_data) - pattern_length, 4):\n        pattern = code_data[i:i+pattern_length]\n        if pattern.count(b'\\x00') \u003C pattern_length \u002F\u002F 3:  # Skip null-heavy\n            hex_pattern = ' '.join(f'{b:02X}' for b in pattern)\n            patterns.append(hex_pattern)\n\n    # Count frequency and return unique ones\n    freq = Counter(patterns)\n    unique = [p for p, count in freq.items() if count == 1]\n\n    return unique[:20]  # Top 20 candidates\n\n\ndef suggest_rule_strings(filepath):\n    \"\"\"Suggest strings and patterns for YARA rule.\"\"\"\n    print(f\"[+] Analyzing: {filepath}\")\n\n    # Extract strings\n    strings = extract_strings(filepath)\n\n    # Filter for suspicious\u002Funique strings\n    suspicious_keywords = [\n        'http', 'https', 'cmd', 'powershell', 'mutex', 'pipe',\n        'password', 'credential', 'inject', 'hook', 'debug',\n        'sandbox', 'virtual', 'vmware', 'vbox',\n    ]\n\n    print(\"\\n[+] Suspicious ASCII strings:\")\n    for s in strings['ascii']:\n        if any(kw in s.lower() for kw in suspicious_keywords):\n            print(f\"  $ = \\\"{s}\\\" ascii\")\n\n    print(\"\\n[+] Suspicious wide strings:\")\n    for s in strings['wide']:\n        if any(kw in s.lower() for kw in suspicious_keywords):\n            print(f\"  $ = \\\"{s}\\\" wide\")\n\n    # Import analysis\n    imports = analyze_pe_imports(filepath)\n    suspicious_apis = [\n        'VirtualAlloc', 'VirtualProtect', 'WriteProcessMemory',\n        'CreateRemoteThread', 'NtUnmapViewOfSection', 'RtlMoveMemory',\n        'OpenProcess', 'CreateToolhelp32Snapshot',\n        'InternetOpenA', 'HttpSendRequestA',\n        'CryptEncrypt', 'CryptDecrypt',\n    ]\n\n    print(\"\\n[+] Suspicious imports:\")\n    for imp in imports:\n        func = imp.split('!')[-1]\n        if func in suspicious_apis:\n            print(f\"  {imp}\")\n\n    # Byte patterns\n    print(\"\\n[+] Candidate hex patterns:\")\n    patterns = find_unique_byte_patterns(filepath)\n    for p in patterns[:5]:\n        print(f\"  $hex = {{ {p} }}\")\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(f\"Usage: {sys.argv[0]} \u003Csample_path>\")\n        sys.exit(1)\n    suggest_rule_strings(sys.argv[1])\n```\n\n### Step 2: Write and Test YARA Rules\n\n```python\nimport yara\nimport os\n\ndef create_yara_rule(rule_name, meta, strings, condition):\n    \"\"\"Generate a YARA rule from components.\"\"\"\n    meta_str = \"\\n\".join(f'        {k} = \"{v}\"' for k, v in meta.items())\n    strings_str = \"\\n\".join(f\"        {s}\" for s in strings)\n\n    rule = f\"\"\"rule {rule_name} {{\n    meta:\n{meta_str}\n\n    strings:\n{strings_str}\n\n    condition:\n        {condition}\n}}\"\"\"\n    return rule\n\n\ndef test_yara_rule(rule_text, test_dir):\n    \"\"\"Compile and test YARA rule against sample directory.\"\"\"\n    try:\n        rules = yara.compile(source=rule_text)\n    except yara.SyntaxError as e:\n        print(f\"[-] YARA syntax error: {e}\")\n        return None\n\n    results = {\"matches\": [], \"no_match\": []}\n\n    for filename in os.listdir(test_dir):\n        filepath = os.path.join(test_dir, filename)\n        if not os.path.isfile(filepath):\n            continue\n\n        matches = rules.match(filepath)\n        if matches:\n            results[\"matches\"].append({\n                \"file\": filename,\n                \"rules\": [m.rule for m in matches],\n            })\n        else:\n            results[\"no_match\"].append(filename)\n\n    print(f\"[+] Matches: {len(results['matches'])}\")\n    print(f\"[-] No match: {len(results['no_match'])}\")\n    return results\n\n\n# Example: Create a rule for a hypothetical malware family\nexample_rule = create_yara_rule(\n    rule_name=\"MalwareFamily_Variant_A\",\n    meta={\n        \"description\": \"Detects MalwareFamily Variant A\",\n        \"author\": \"Malware Analysis Team\",\n        \"date\": \"2025-01-01\",\n        \"hash\": \"abc123...\",\n        \"tlp\": \"WHITE\",\n    },\n    strings=[\n        '$mutex = \"Global\\\\\\\\UniqueM4lwareMutex\" ascii wide',\n        '$c2_pattern = \u002Fhttps?:\\\\\u002F\\\\\u002F[a-z]{5,10}\\\\.(xyz|top|buzz)\\\\\u002Fgate\\\\.php\u002F',\n        '$api1 = \"VirtualAllocEx\" ascii',\n        '$api2 = \"WriteProcessMemory\" ascii',\n        '$api3 = \"CreateRemoteThread\" ascii',\n        '$hex_decrypt = { 8B 45 ?? 33 C1 89 45 ?? 83 C1 04 }',\n        '$pdb = \"C:\\\\\\\\Users\\\\\\\\\" ascii',\n    ],\n    condition=(\n        'uint16(0) == 0x5A4D and filesize \u003C 2MB and '\n        '($mutex or $c2_pattern) and '\n        '2 of ($api*) and '\n        '$hex_decrypt'\n    ),\n)\n\nprint(example_rule)\n```\n\n### Step 3: Performance Testing and Optimization\n\n```python\nimport time\n\ndef benchmark_rule(rule_text, scan_directory, iterations=3):\n    \"\"\"Benchmark YARA rule scan performance.\"\"\"\n    rules = yara.compile(source=rule_text)\n\n    files = []\n    for root, _, filenames in os.walk(scan_directory):\n        for f in filenames:\n            files.append(os.path.join(root, f))\n\n    print(f\"[+] Benchmarking against {len(files)} files \"\n          f\"({iterations} iterations)\")\n\n    times = []\n    for i in range(iterations):\n        start = time.perf_counter()\n        matches = 0\n        for filepath in files:\n            try:\n                result = rules.match(filepath)\n                if result:\n                    matches += 1\n            except Exception:\n                pass\n        elapsed = time.perf_counter() - start\n        times.append(elapsed)\n        print(f\"  Iteration {i+1}: {elapsed:.3f}s ({matches} matches)\")\n\n    avg_time = sum(times) \u002F len(times)\n    files_per_sec = len(files) \u002F avg_time\n    print(f\"\\n[+] Average: {avg_time:.3f}s ({files_per_sec:.0f} files\u002Fsec)\")\n    return avg_time\n```\n\n## Validation Criteria\n\n- YARA rules compile without syntax errors\n- Rules detect target malware family samples with zero false negatives\n- False positive rate below 0.1% when scanned against clean file corpus\n- Rule performance allows scanning 1000+ files per second\n- Rules survive minor malware modifications (recompilation, string changes)\n- Metadata includes hash, author, date, description, and TLP marking\n\n## References\n\n- [YARA Official Documentation](https:\u002F\u002Fvirustotal.github.io\u002Fyara\u002F)\n- [YARA-X Rewrite in Rust](https:\u002F\u002Fgithub.com\u002FVirusTotal\u002Fyara-x)\n- [Yara-Rules Community Repository](https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules)\n- [ReversingLabs - Writing Detailed YARA Rules](https:\u002F\u002Fwww.reversinglabs.com\u002Fblog\u002Fwriting-detailed-yara-rules-for-malware-detection)\n- [YARA Rule Crafting Deep Dive](https:\u002F\u002Fcyberthreatintelligencenetwork.com\u002Findex.php\u002F2024\u002F09\u002F11\u002Fyara-rule-crafting-a-deep-dive-into-signature-based-threat-hunting-strategies\u002F)\n","# Performing YARA Rule Development for Detection\n\n## Overview\n\nYARA is the pattern matching swiss knife for malware researchers, enabling identification and classification of malware based on textual or binary patterns. Effective YARA rules combine unique string patterns, byte sequences, PE header characteristics, import table analysis, and conditional logic to detect malware families while avoiding false positives. Modern YARA-X (rewritten in Rust, stable since June 2025) brings improved performance and new modules. Rules should target unpacked malware artifacts like hardcoded stack strings, C2 URLs, mutex names, encryption constants, and unique code sequences rather than packer signatures.\n\n\n## When to Use\n\n- When conducting security assessments that involve performing yara rule development for detection\n- When following incident response procedures for related security events\n- When performing scheduled security testing or auditing activities\n- When validating security controls through hands-on testing\n\n## Prerequisites\n\n- Python 3.9+ with `yara-python` library\n- YARA 4.5+ or YARA-X 0.10+\n- PE analysis tools (`pefile`, `pestudio`)\n- Hex editor for identifying unique byte patterns\n- Access to malware samples (VirusTotal, MalwareBazaar)\n- Understanding of PE file format, strings, and import tables\n\n## Key Concepts\n\n### Rule Structure\n\nEvery YARA rule consists of three sections: `meta` (optional descriptive metadata), `strings` (pattern definitions), and `condition` (matching logic). String types include text strings (ASCII\u002Fwide\u002Fnocase), hex patterns with wildcards and jumps, and regular expressions. Conditions combine string matches with file properties using boolean operators.\n\n### String Selection Strategy\n\nEffective rules target patterns that are unique to the malware family and survive recompilation. Hardcoded stack strings are excellent choices because compilers embed them consistently. C2 domain patterns, custom encryption routines, unique error messages, and specific API call sequences provide stable detection anchors. Avoid compiler-generated boilerplate and common library strings.\n\n### Performance Optimization\n\nYARA evaluates conditions short-circuit style. Place the most discriminating and cheapest-to-evaluate conditions first. Use `filesize` limits to skip irrelevant files quickly. Minimize regex usage in favor of hex patterns. Use `private` rules as building blocks for complex detection logic without generating standalone matches.\n\n## Workflow\n\n### Step 1: Analyze Sample for Unique Patterns\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Extract candidate strings and byte patterns for YARA rule creation.\"\"\"\nimport pefile\nimport re\nimport sys\nfrom collections import Counter\n\n\ndef extract_strings(filepath, min_length=6):\n    \"\"\"Extract ASCII and wide strings from binary.\"\"\"\n    with open(filepath, 'rb') as f:\n        data = f.read()\n\n    # ASCII strings\n    ascii_strings = re.findall(\n        rb'[\\x20-\\x7e]{' + str(min_length).encode() + rb',}', data\n    )\n\n    # Wide (UTF-16LE) strings\n    wide_strings = re.findall(\n        rb'(?:[\\x20-\\x7e]\\x00){' + str(min_length).encode() + rb',}', data\n    )\n\n    return {\n        'ascii': [s.decode('ascii') for s in ascii_strings],\n        'wide': [s.decode('utf-16-le') for s in wide_strings],\n    }\n\n\ndef analyze_pe_imports(filepath):\n    \"\"\"Extract import table for API-based detection.\"\"\"\n    try:\n        pe = pefile.PE(filepath)\n    except pefile.PEFormatError:\n        return []\n\n    imports = []\n    if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):\n        for entry in pe.DIRECTORY_ENTRY_IMPORT:\n            dll_name = entry.dll.decode('utf-8', errors='replace')\n            for imp in entry.imports:\n                if imp.name:\n                    func_name = imp.name.decode('utf-8', errors='replace')\n                    imports.append(f\"{dll_name}!{func_name}\")\n    return imports\n\n\ndef find_unique_byte_patterns(filepath, pattern_length=16):\n    \"\"\"Find unique byte sequences suitable for YARA hex patterns.\"\"\"\n    with open(filepath, 'rb') as f:\n        data = f.read()\n\n    try:\n        pe = pefile.PE(filepath)\n        # Focus on code section\n        for section in pe.sections:\n            if section.Characteristics & 0x20000000:  # IMAGE_SCN_MEM_EXECUTE\n                code_start = section.PointerToRawData\n                code_end = code_start + section.SizeOfRawData\n                code_data = data[code_start:code_end]\n                break\n        else:\n            code_data = data\n    except Exception:\n        code_data = data\n\n    # Find byte patterns that appear exactly once\n    patterns = []\n    for i in range(0, len(code_data) - pattern_length, 4):\n        pattern = code_data[i:i+pattern_length]\n        if pattern.count(b'\\x00') \u003C pattern_length \u002F\u002F 3:  # Skip null-heavy\n            hex_pattern = ' '.join(f'{b:02X}' for b in pattern)\n            patterns.append(hex_pattern)\n\n    # Count frequency and return unique ones\n    freq = Counter(patterns)\n    unique = [p for p, count in freq.items() if count == 1]\n\n    return unique[:20]  # Top 20 candidates\n\n\ndef suggest_rule_strings(filepath):\n    \"\"\"Suggest strings and patterns for YARA rule.\"\"\"\n    print(f\"[+] Analyzing: {filepath}\")\n\n    # Extract strings\n    strings = extract_strings(filepath)\n\n    # Filter for suspicious\u002Funique strings\n    suspicious_keywords = [\n        'http', 'https', 'cmd', 'powershell', 'mutex', 'pipe',\n        'password', 'credential', 'inject', 'hook', 'debug',\n        'sandbox', 'virtual', 'vmware', 'vbox',\n    ]\n\n    print(\"\\n[+] Suspicious ASCII strings:\")\n    for s in strings['ascii']:\n        if any(kw in s.lower() for kw in suspicious_keywords):\n            print(f\"  $ = \\\"{s}\\\" ascii\")\n\n    print(\"\\n[+] Suspicious wide strings:\")\n    for s in strings['wide']:\n        if any(kw in s.lower() for kw in suspicious_keywords):\n            print(f\"  $ = \\\"{s}\\\" wide\")\n\n    # Import analysis\n    imports = analyze_pe_imports(filepath)\n    suspicious_apis = [\n        'VirtualAlloc', 'VirtualProtect', 'WriteProcessMemory',\n        'CreateRemoteThread', 'NtUnmapViewOfSection', 'RtlMoveMemory',\n        'OpenProcess', 'CreateToolhelp32Snapshot',\n        'InternetOpenA', 'HttpSendRequestA',\n        'CryptEncrypt', 'CryptDecrypt',\n    ]\n\n    print(\"\\n[+] Suspicious imports:\")\n    for imp in imports:\n        func = imp.split('!')[-1]\n        if func in suspicious_apis:\n            print(f\"  {imp}\")\n\n    # Byte patterns\n    print(\"\\n[+] Candidate hex patterns:\")\n    patterns = find_unique_byte_patterns(filepath)\n    for p in patterns[:5]:\n        print(f\"  $hex = {{ {p} }}\")\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(f\"Usage: {sys.argv[0]} \u003Csample_path>\")\n        sys.exit(1)\n    suggest_rule_strings(sys.argv[1])\n```\n\n### Step 2: Write and Test YARA Rules\n\n```python\nimport yara\nimport os\n\ndef create_yara_rule(rule_name, meta, strings, condition):\n    \"\"\"Generate a YARA rule from components.\"\"\"\n    meta_str = \"\\n\".join(f'        {k} = \"{v}\"' for k, v in meta.items())\n    strings_str = \"\\n\".join(f\"        {s}\" for s in strings)\n\n    rule = f\"\"\"rule {rule_name} {{\n    meta:\n{meta_str}\n\n    strings:\n{strings_str}\n\n    condition:\n        {condition}\n}}\"\"\"\n    return rule\n\n\ndef test_yara_rule(rule_text, test_dir):\n    \"\"\"Compile and test YARA rule against sample directory.\"\"\"\n    try:\n        rules = yara.compile(source=rule_text)\n    except yara.SyntaxError as e:\n        print(f\"[-] YARA syntax error: {e}\")\n        return None\n\n    results = {\"matches\": [], \"no_match\": []}\n\n    for filename in os.listdir(test_dir):\n        filepath = os.path.join(test_dir, filename)\n        if not os.path.isfile(filepath):\n            continue\n\n        matches = rules.match(filepath)\n        if matches:\n            results[\"matches\"].append({\n                \"file\": filename,\n                \"rules\": [m.rule for m in matches],\n            })\n        else:\n            results[\"no_match\"].append(filename)\n\n    print(f\"[+] Matches: {len(results['matches'])}\")\n    print(f\"[-] No match: {len(results['no_match'])}\")\n    return results\n\n\n# Example: Create a rule for a hypothetical malware family\nexample_rule = create_yara_rule(\n    rule_name=\"MalwareFamily_Variant_A\",\n    meta={\n        \"description\": \"Detects MalwareFamily Variant A\",\n        \"author\": \"Malware Analysis Team\",\n        \"date\": \"2025-01-01\",\n        \"hash\": \"abc123...\",\n        \"tlp\": \"WHITE\",\n    },\n    strings=[\n        '$mutex = \"Global\\\\\\\\UniqueM4lwareMutex\" ascii wide',\n        '$c2_pattern = \u002Fhttps?:\\\\\u002F\\\\\u002F[a-z]{5,10}\\\\.(xyz|top|buzz)\\\\\u002Fgate\\\\.php\u002F',\n        '$api1 = \"VirtualAllocEx\" ascii',\n        '$api2 = \"WriteProcessMemory\" ascii',\n        '$api3 = \"CreateRemoteThread\" ascii',\n        '$hex_decrypt = { 8B 45 ?? 33 C1 89 45 ?? 83 C1 04 }',\n        '$pdb = \"C:\\\\\\\\Users\\\\\\\\\" ascii',\n    ],\n    condition=(\n        'uint16(0) == 0x5A4D and filesize \u003C 2MB and '\n        '($mutex or $c2_pattern) and '\n        '2 of ($api*) and '\n        '$hex_decrypt'\n    ),\n)\n\nprint(example_rule)\n```\n\n### Step 3: Performance Testing and Optimization\n\n```python\nimport time\n\ndef benchmark_rule(rule_text, scan_directory, iterations=3):\n    \"\"\"Benchmark YARA rule scan performance.\"\"\"\n    rules = yara.compile(source=rule_text)\n\n    files = []\n    for root, _, filenames in os.walk(scan_directory):\n        for f in filenames:\n            files.append(os.path.join(root, f))\n\n    print(f\"[+] Benchmarking against {len(files)} files \"\n          f\"({iterations} iterations)\")\n\n    times = []\n    for i in range(iterations):\n        start = time.perf_counter()\n        matches = 0\n        for filepath in files:\n            try:\n                result = rules.match(filepath)\n                if result:\n                    matches += 1\n            except Exception:\n                pass\n        elapsed = time.perf_counter() - start\n        times.append(elapsed)\n        print(f\"  Iteration {i+1}: {elapsed:.3f}s ({matches} matches)\")\n\n    avg_time = sum(times) \u002F len(times)\n    files_per_sec = len(files) \u002F avg_time\n    print(f\"\\n[+] Average: {avg_time:.3f}s ({files_per_sec:.0f} files\u002Fsec)\")\n    return avg_time\n```\n\n## Validation Criteria\n\n- YARA rules compile without syntax errors\n- Rules detect target malware family samples with zero false negatives\n- False positive rate below 0.1% when scanned against clean file corpus\n- Rule performance allows scanning 1000+ files per second\n- Rules survive minor malware modifications (recompilation, string changes)\n- Metadata includes hash, author, date, description, and TLP marking\n\n## References\n\n- [YARA Official Documentation](https:\u002F\u002Fvirustotal.github.io\u002Fyara\u002F)\n- [YARA-X Rewrite in Rust](https:\u002F\u002Fgithub.com\u002FVirusTotal\u002Fyara-x)\n- [Yara-Rules Community Repository](https:\u002F\u002Fgithub.com\u002FYara-Rules\u002Frules)\n- [ReversingLabs - Writing Detailed YARA Rules](https:\u002F\u002Fwww.reversinglabs.com\u002Fblog\u002Fwriting-detailed-yara-rules-for-malware-detection)\n- [YARA Rule Crafting Deep Dive](https:\u002F\u002Fcyberthreatintelligencenetwork.com\u002Findex.php\u002F2024\u002F09\u002F11\u002Fyara-rule-crafting-a-deep-dive-into-signature-based-threat-hunting-strategies\u002F)\n",{"name":5,"tags":44,"author":47,"domain":38,"license":15,"version":48,"category":5,"nist_csf":49,"subdomain":54,"description":7,"mitre_attack":55},[25,45,27,37,46,28,29],"malware-detection","pattern-matching","mahipal","1.0",[50,51,52,53],"DE.AE-02","RS.AN-03","ID.RA-01","DE.CM-01","malware-analysis",[56,57,58,59],"T1027","T1055","T1140","T1497","main","5eea5b3296f4673b5f481e8bcc1ba76281149f16","modules\u002Fperforming-yara-rule-development-for-detection",0,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core","https:\u002F\u002Fgithub.com\u002FHenriqueMC17","Qualquer tecnologia suficientemente avançada é indistinguível da mágica.","2026-09-28 22:40:38",{"source":8,"skillName":5,"commands":69,"prompt":79,"zipAvailable":80},[70,73,76],{"tool":71,"command":72},"npx","npx skills add HenriqueMC17\u002Fagente-core --skill performing-yara-rule-development-for-detection",{"tool":74,"command":75},"bunx","bunx skills add HenriqueMC17\u002Fagente-core --skill performing-yara-rule-development-for-detection",{"tool":77,"command":78},"pnpm","pnpm dlx skills add HenriqueMC17\u002Fagente-core --skill performing-yara-rule-development-for-detection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002FSKILL.md",true,[82,88,93,99,103,107,113],{"path":83,"resourceType":84,"resourceTypeDesc":85,"sizeBytes":86,"sourceHtmlUrl":87},"assets\u002Ftemplate.md","ASSET","资产文件",633,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Fassets\u002Ftemplate.md",{"path":89,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002FLICENSE",{"path":94,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":97,"sourceHtmlUrl":98},"references\u002Fapi-reference.md","REFERENCE","参考文档",1947,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Freferences\u002Fapi-reference.md",{"path":100,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fstandards.md",1424,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Freferences\u002Fstandards.md",{"path":104,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":105,"sourceHtmlUrl":106},"references\u002Fworkflows.md",1764,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Freferences\u002Fworkflows.md",{"path":108,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":111,"sourceHtmlUrl":112},"scripts\u002Fagent.py","SCRIPT","脚本",5704,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Fscripts\u002Fagent.py",{"path":114,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":115,"sourceHtmlUrl":116},"scripts\u002Fprocess.py",8731,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fperforming-yara-rule-development-for-detection\u002Fscripts\u002Fprocess.py",[118,142,168,190,206,225],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":39},"01M6HPFF0RCN0X6WT5EBSV71GY","validating-backup-integrity-for-recovery","Validate backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to ensure backups are reliable for disaster recovery and ransomware response scenarios.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[],[125,126,127,128,21,129,38,130,131,132,133,134,24,135,136,137,138,139,140,141],"integrity","backup","recovery","validating backup integrity for recovery","testing","validate","verification","hash-verification","incident-response","ransomware","t1078","t1490","disaster-recovery","restore","incident","disaster recovery","ransomware response",{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":146,"categories":147,"keywords":148,"publishedAt":39},"01M6HPFAWJVFK25Q33K3T7WQ8G","triaging-vulnerabilities-with-ssvc-framework","Triage and prioritize vulnerabilities using CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree framework to produce actionable remediation priorities.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[],[149,150,151,152,153,38,154,155,156,157,158,159,160,161,162,163,164,165,166,167],"vulnerabilities","framework","ssvc","triaging vulnerabilities with ssvc framework","with","triage and prioritize","CISA","vulnerability-management","risk-management","cvss","remediation","vulnerability","prioritization","decision-tree","prioritize","decision","priorities","actionable","tree",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":39},"01M6HPF6JS9X72WP59094H3ASQ","triaging-security-incident","Performs initial triage of security incidents to determine severity, scope, and required response actions using the NIST SP 800-61r3 and SANS PICERL frameworks. Classifies incidents by type, assigns priority based on business impact, and routes...","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-incident\u002FSKILL.md",[],[175,176,139,38,177,178,179,135,136,26,180,181,182,183,184,185,186,187,188,189],"security","triaging security incident","actions","soc","NIST","severity-classification","incident-triage","SANS-PICERL","SOC-operations","picerl","conversion","isolation","scope","impact","consistency",{"skillNo":191,"name":192,"nameZh":6,"description":193,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":196,"publishedAt":39},"01M6HPF2EX6ZYNYYHKBRJN7GEF","triaging-security-incident-with-ir-playbook","Classify and prioritize security incidents using structured IR playbooks to determine severity, assign response teams, and initiate appropriate response procedures.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-incident-with-ir-playbook\u002FSKILL.md",[],[175,197,198,176,139,153,38,199,178,133,200,201,135,136,202,180,163,203,204,205],"playbook","triaging security incident with ir playbook","teams","IR-playbook","severity","classification","classify","incidents","initiate",{"skillNo":207,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":210,"categories":211,"keywords":212,"publishedAt":39},"01M6HPEY9XPGE7X95AG4XJFQAW","triaging-security-alerts-in-splunk","Triages security alerts in Splunk Enterprise Security by classifying severity, investigating notable events, correlating related telemetry, and making escalation or closure decisions using SPL queries and the Incident Review dashboard. Use when...","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-alerts-in-splunk\u002FSKILL.md",[],[175,213,214,215,216,217,38,218,219,220,178,221,135,222,223,224,183,30,139,34],"security alerts","splunk","triaging security alerts in splunk","alerts","review","siem","dashboard","search","correlation-search","t1566","notable-events","incident-review",{"skillNo":226,"name":227,"nameZh":6,"description":228,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":229,"categories":230,"keywords":231,"publishedAt":39},"01M6HPET6XGEPEJPN7V032JGZ0","tracking-threat-actor-infrastructure","Threat actor infrastructure tracking involves monitoring and mapping adversary-controlled assets including command-and-control (C2) servers, phishing domains, exploit kit hosts, bulletproof hosting, a","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftracking-threat-actor-infrastructure\u002FSKILL.md",[],[232,233,234,235,38,236,237,238,239,240,241,222,242,243,30,244,34,245,246,247],"infrastructure","tracking threat actor infrastructure","tracking","threat","monitoring","mitre-attack","threat-actor","threat-intelligence","command-and-control","dns","command","exploit","intelligence","domains","kit","hosts"]