Performs rapid malware triage and classification using YARA rules to match file patterns, strings, byte sequences, and structural characteristics against known malware families and suspicious indicators. Covers rule writing, scanning, and integration with analysis pipelines. Activates for requests involving YARA rule creation, malware classification, pattern matching, sample triage, or signature-based detection.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Instruções da origem · Visualização somente leitura
name
performing-malware-triage-with-yara
description
Performs rapid malware triage and classification using YARA rules to match file patterns, strings, byte sequences, and structural characteristics against known malware families and suspicious indicators. Covers rule writing, scanning, and integration with analysis pipelines. Activates for requests involving YARA rule creation, malware classification, pattern matching, sample triage, or signature-based detection.
Rapidly classifying a large batch of malware samples against known family signatures
Writing detection rules for a newly analyzed malware family based on unique byte patterns
Scanning file shares, endpoints, or memory dumps for indicators of a specific threat
Building automated triage pipelines that classify samples before manual analysis
Hunting for variants of a known threat across an enterprise using YARA scans
Do not use as the sole analysis method; YARA triage identifies known patterns but does not reveal new or unknown malware behaviors.
Common Misconfigurations & Verification
Over-fitting to the packer stub. Rules built from a UPX/Themida-packed sample match the packer, not the family — they fire on unrelated packed goodware and miss unpacked variants. Write strings/hex from the unpacked payload (mutexes, C2 templates, decryption constants), not the loader.
Weak or missing anchors make rules slow and noisy. A condition that is just 2 of ($s*) with no uint16(0) == 0x5A4D / filesize < N gate forces YARA to scan every file fully. Always lead with a cheap discriminator ($mz at 0, pe.is_pe, filesize bound) so the expensive string matching short-circuits.
Atom problems and regex cost. Short hex atoms ({ 00 00 }), fully-wildcarded patterns ({ ?? ?? ?? ?? }), and unbounded regex (/.*/) trigger YARA's "slowing down scanning" warning and cause timeouts. Use yara -p rule.yar sample (atom profiling) and keep ≥4 fixed contiguous bytes per pattern.
False positives from shared library strings. Strings from OpenSSL, the VC++ runtime, Go/Rust std, or common installers will match clean files. Never use them as sole anchors.
Verify it actually fires AND stays quiet: confirm true positive with yara -s family.yar known_sample (the -s output must show your intended strings hit at sane offsets, not a coincidental match). Then run against a goodware corpus — yara -r family.yar /clean/ | wc -l must be 0. In Python: yara.compile(...).match(path) over a labeled set to measure FP/FN before deployment.
Test variant resilience: match against multiple samples of the family, not one hash, so the rule survives recompilation and minor string changes.
Prerequisites
YARA 4.x installed (apt install yara or pip install yara-python)
Leverage YARA's PE module for structural detection:
import "pe"
import "hash"
import "math"
rule MalwareX_PE_Characteristics {
meta:
description = "Detects MalwareX by PE structure and imports"
author = "analyst"
condition:
pe.is_pe and
// Compiled within specific timeframe
pe.timestamp > 1693526400 and // After 2023-09-01
pe.timestamp < 1727740800 and // Before 2024-10-01
// Specific import hash
pe.imphash() == "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" or
// Suspicious import combination
(
pe.imports("kernel32.dll", "VirtualAllocEx") and
pe.imports("kernel32.dll", "WriteProcessMemory") and
pe.imports("kernel32.dll", "CreateRemoteThread") and
pe.imports("wininet.dll", "InternetOpenA")
) or
// High entropy .text section (packed)
(
for any section in pe.sections : (
section.name == ".text" and
math.entropy(section.raw_data_offset, section.raw_data_size) > 7.0
)
)
}
rule MalwareX_Rich_Header {
meta:
description = "Detects MalwareX by Rich header hash"
condition:
pe.is_pe and
hash.md5(pe.rich_signature.clear_data) == "abc123def456abc123def456abc123de"
}
Step 5: Batch Triage with Python
Automate scanning of sample collections:
import yara
import os
import json
import hashlib
from datetime import datetime
# Compile all rule files
rule_files = {
"apt": "rules/apt_rules.yar",
"ransomware": "rules/ransomware_rules.yar",
"trojan": "rules/trojan_rules.yar",
"custom": "rules/custom_rules.yar",
}
rules = yara.compile(filepaths=rule_files)
# Scan sample directory
results = []
sample_dir = "/path/to/samples"for filename in os.listdir(sample_dir):
filepath = os.path.join(sample_dir, filename)
ifnot os.path.isfile(filepath):
continuewithopen(filepath, "rb") as f:
data = f.read()
sha256 = hashlib.sha256(data).hexdigest()
matches = rules.match(filepath)
result = {
"filename": filename,
"sha256": sha256,
"size": len(data),
"matches": [],
"classification": "UNKNOWN",
}
formatchin matches:
result["matches"].append({
"rule": match.rule,
"namespace": match.namespace,
"tags": match.tags,
"strings": [(hex(s[0]), s[1], s[2].decode("utf-8", errors="replace")[:100])
for s inmatch.strings] ifmatch.strings else []
})
if result["matches"]:
result["classification"] = result["matches"][0]["namespace"].upper()
results.append(result)
# Summary
classified = sum(1for r in results if r["classification"] != "UNKNOWN")
print(f"Scanned: {len(results)} samples")
print(f"Classified: {classified} ({classified/len(results)*100:.1f}%)")
print(f"Unknown: {len(results)-classified}")
# Export resultswithopen("triage_results.json", "w") as f:
json.dump(results, f, indent=2)
Pattern matching rule defining strings, byte sequences, and conditions that identify a specific file or malware family
Condition
Boolean expression combining string matches, file properties, and module functions to determine if a rule matches
Hex String
Byte pattern with optional wildcards (??) and jumps ([N-M]) for matching machine code or binary data
PE Module
YARA module providing access to PE file properties (imports, sections, timestamps, resources) for structural matching
Imphash
MD5 hash of a PE file's import table; samples from the same family often share import hashes
Rich Header
Undocumented PE structure containing compiler/linker metadata; consistent within malware build environments
YARA-C
Compiled YARA rule format enabling faster scanning by pre-compiling rules for repeated use
Tools & Systems
YARA: Pattern matching engine for identifying and classifying malware based on text, hex, and structural patterns
yara-python: Python bindings for YARA enabling scripted scanning, rule compilation, and integration with analysis pipelines
yarGen: Automatic YARA rule generator that creates rules from malware samples by identifying unique strings and opcodes
YARA-Rules (GitHub): Community-maintained repository of YARA rules covering malware families, exploits, and suspicious indicators
Malpedia YARA: Curated YARA rules from the Malpedia malware encyclopedia with high-quality family-specific rules
Common Scenarios
Scenario: Creating Detection Rules for a New Malware Family
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.
Approach:
Extract unique strings from the unpacked binary (C2 URLs, mutex names, registry paths)
Identify unique byte sequences from the encryption routine or C2 protocol (from Ghidra analysis)
Record PE characteristics (imphash, Rich header hash, section names, compilation timestamp range)
Write a YARA rule combining string, byte pattern, and PE module conditions
Test against the known malware samples to confirm true positive detection
Test against a clean file corpus (Windows system files, common applications) to verify zero false positives
Deploy to enterprise scanning infrastructure and threat intelligence platform
Pitfalls:
Writing rules too specific to a single sample (will not detect variants with minor changes)
Writing rules too generic (matching legitimate software, causing false positives)
Using strings that appear in common libraries or frameworks (e.g., OpenSSL strings)
Not testing on a sufficiently large clean corpus before deployment