reverse-skills-max: initial public release (restored, redacted, hardened)

This commit is contained in:
baradok609hecl1pq6qi
2026-10-20 02:17:15 +03:00
commit da24c2bd20
2227 changed files with 443931 additions and 0 deletions

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,345 @@
---
name: performing-yara-rule-development-for-detection
description: Develops precise YARA and YARA-X rules for malware detection by identifying
unique strings, byte sequences, PE header traits, and behavioral indicators in
unpacked malware artifacts while minimizing false positives. Use when building
detection signatures for threat hunting, classifying malware families, or authoring
rules from IOCs such as C2 URLs, mutex names, and encryption constants.
domain: cybersecurity
subdomain: malware-analysis
tags:
- yara
- malware-detection
- signature-development
- threat-hunting
- pattern-matching
- yara-x
- indicator-development
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- DE.AE-02
- RS.AN-03
- ID.RA-01
- DE.CM-01
mitre_attack:
- T1027
- T1055
- T1140
- T1497
---
# Performing YARA Rule Development for Detection
## Overview
YARA 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.
## When to Use
- When conducting security assessments that involve performing yara rule development for detection
- When following incident response procedures for related security events
- When performing scheduled security testing or auditing activities
- When validating security controls through hands-on testing
## Prerequisites
- Python 3.9+ with `yara-python` library
- YARA 4.5+ or YARA-X 0.10+
- PE analysis tools (`pefile`, `pestudio`)
- Hex editor for identifying unique byte patterns
- Access to malware samples (VirusTotal, MalwareBazaar)
- Understanding of PE file format, strings, and import tables
## Key Concepts
### Rule Structure
Every YARA rule consists of three sections: `meta` (optional descriptive metadata), `strings` (pattern definitions), and `condition` (matching logic). String types include text strings (ASCII/wide/nocase), hex patterns with wildcards and jumps, and regular expressions. Conditions combine string matches with file properties using boolean operators.
### String Selection Strategy
Effective 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.
### Performance Optimization
YARA 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.
## Workflow
### Step 1: Analyze Sample for Unique Patterns
```python
#!/usr/bin/env python3
"""Extract candidate strings and byte patterns for YARA rule creation."""
import pefile
import re
import sys
from collections import Counter
def extract_strings(filepath, min_length=6):
"""Extract ASCII and wide strings from binary."""
with open(filepath, 'rb') as f:
data = f.read()
# ASCII strings
ascii_strings = re.findall(
rb'[\x20-\x7e]{' + str(min_length).encode() + rb',}', data
)
# Wide (UTF-16LE) strings
wide_strings = re.findall(
rb'(?:[\x20-\x7e]\x00){' + str(min_length).encode() + rb',}', data
)
return {
'ascii': [s.decode('ascii') for s in ascii_strings],
'wide': [s.decode('utf-16-le') for s in wide_strings],
}
def analyze_pe_imports(filepath):
"""Extract import table for API-based detection."""
try:
pe = pefile.PE(filepath)
except pefile.PEFormatError:
return []
imports = []
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
for entry in pe.DIRECTORY_ENTRY_IMPORT:
dll_name = entry.dll.decode('utf-8', errors='replace')
for imp in entry.imports:
if imp.name:
func_name = imp.name.decode('utf-8', errors='replace')
imports.append(f"{dll_name}!{func_name}")
return imports
def find_unique_byte_patterns(filepath, pattern_length=16):
"""Find unique byte sequences suitable for YARA hex patterns."""
with open(filepath, 'rb') as f:
data = f.read()
try:
pe = pefile.PE(filepath)
# Focus on code section
for section in pe.sections:
if section.Characteristics & 0x20000000: # IMAGE_SCN_MEM_EXECUTE
code_start = section.PointerToRawData
code_end = code_start + section.SizeOfRawData
code_data = data[code_start:code_end]
break
else:
code_data = data
except Exception:
code_data = data
# Find byte patterns that appear exactly once
patterns = []
for i in range(0, len(code_data) - pattern_length, 4):
pattern = code_data[i:i+pattern_length]
if pattern.count(b'\x00') < pattern_length // 3: # Skip null-heavy
hex_pattern = ' '.join(f'{b:02X}' for b in pattern)
patterns.append(hex_pattern)
# Count frequency and return unique ones
freq = Counter(patterns)
unique = [p for p, count in freq.items() if count == 1]
return unique[:20] # Top 20 candidates
def suggest_rule_strings(filepath):
"""Suggest strings and patterns for YARA rule."""
print(f"[+] Analyzing: {filepath}")
# Extract strings
strings = extract_strings(filepath)
# Filter for suspicious/unique strings
suspicious_keywords = [
'http', 'https', 'cmd', 'powershell', 'mutex', 'pipe',
'password', 'credential', 'inject', 'hook', 'debug',
'sandbox', 'virtual', 'vmware', 'vbox',
]
print("\n[+] Suspicious ASCII strings:")
for s in strings['ascii']:
if any(kw in s.lower() for kw in suspicious_keywords):
print(f" $ = \"{s}\" ascii")
print("\n[+] Suspicious wide strings:")
for s in strings['wide']:
if any(kw in s.lower() for kw in suspicious_keywords):
print(f" $ = \"{s}\" wide")
# Import analysis
imports = analyze_pe_imports(filepath)
suspicious_apis = [
'VirtualAlloc', 'VirtualProtect', 'WriteProcessMemory',
'CreateRemoteThread', 'NtUnmapViewOfSection', 'RtlMoveMemory',
'OpenProcess', 'CreateToolhelp32Snapshot',
'InternetOpenA', 'HttpSendRequestA',
'CryptEncrypt', 'CryptDecrypt',
]
print("\n[+] Suspicious imports:")
for imp in imports:
func = imp.split('!')[-1]
if func in suspicious_apis:
print(f" {imp}")
# Byte patterns
print("\n[+] Candidate hex patterns:")
patterns = find_unique_byte_patterns(filepath)
for p in patterns[:5]:
print(f" $hex = {{ {p} }}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <sample_path>")
sys.exit(1)
suggest_rule_strings(sys.argv[1])
```
### Step 2: Write and Test YARA Rules
```python
import yara
import os
def create_yara_rule(rule_name, meta, strings, condition):
"""Generate a YARA rule from components."""
meta_str = "\n".join(f' {k} = "{v}"' for k, v in meta.items())
strings_str = "\n".join(f" {s}" for s in strings)
rule = f"""rule {rule_name} {{
meta:
{meta_str}
strings:
{strings_str}
condition:
{condition}
}}"""
return rule
def test_yara_rule(rule_text, test_dir):
"""Compile and test YARA rule against sample directory."""
try:
rules = yara.compile(source=rule_text)
except yara.SyntaxError as e:
print(f"[-] YARA syntax error: {e}")
return None
results = {"matches": [], "no_match": []}
for filename in os.listdir(test_dir):
filepath = os.path.join(test_dir, filename)
if not os.path.isfile(filepath):
continue
matches = rules.match(filepath)
if matches:
results["matches"].append({
"file": filename,
"rules": [m.rule for m in matches],
})
else:
results["no_match"].append(filename)
print(f"[+] Matches: {len(results['matches'])}")
print(f"[-] No match: {len(results['no_match'])}")
return results
# Example: Create a rule for a hypothetical malware family
example_rule = create_yara_rule(
rule_name="MalwareFamily_Variant_A",
meta={
"description": "Detects MalwareFamily Variant A",
"author": "Malware Analysis Team",
"date": "2025-01-01",
"hash": "abc123...",
"tlp": "WHITE",
},
strings=[
'$mutex = "Global\\\\UniqueM4lwareMutex" ascii wide',
'$c2_pattern = /https?:\\/\\/[a-z]{5,10}\\.(xyz|top|buzz)\\/gate\\.php/',
'$api1 = "VirtualAllocEx" ascii',
'$api2 = "WriteProcessMemory" ascii',
'$api3 = "CreateRemoteThread" ascii',
'$hex_decrypt = { 8B 45 ?? 33 C1 89 45 ?? 83 C1 04 }',
'$pdb = "C:\\\\Users\\\\" ascii',
],
condition=(
'uint16(0) == 0x5A4D and filesize < 2MB and '
'($mutex or $c2_pattern) and '
'2 of ($api*) and '
'$hex_decrypt'
),
)
print(example_rule)
```
### Step 3: Performance Testing and Optimization
```python
import time
def benchmark_rule(rule_text, scan_directory, iterations=3):
"""Benchmark YARA rule scan performance."""
rules = yara.compile(source=rule_text)
files = []
for root, _, filenames in os.walk(scan_directory):
for f in filenames:
files.append(os.path.join(root, f))
print(f"[+] Benchmarking against {len(files)} files "
f"({iterations} iterations)")
times = []
for i in range(iterations):
start = time.perf_counter()
matches = 0
for filepath in files:
try:
result = rules.match(filepath)
if result:
matches += 1
except Exception:
pass
elapsed = time.perf_counter() - start
times.append(elapsed)
print(f" Iteration {i+1}: {elapsed:.3f}s ({matches} matches)")
avg_time = sum(times) / len(times)
files_per_sec = len(files) / avg_time
print(f"\n[+] Average: {avg_time:.3f}s ({files_per_sec:.0f} files/sec)")
return avg_time
```
## Validation Criteria
- YARA rules compile without syntax errors
- Rules detect target malware family samples with zero false negatives
- False positive rate below 0.1% when scanned against clean file corpus
- Rule performance allows scanning 1000+ files per second
- Rules survive minor malware modifications (recompilation, string changes)
- Metadata includes hash, author, date, description, and TLP marking
## References
- [YARA Official Documentation](https://virustotal.github.io/yara/)
- [YARA-X Rewrite in Rust](https://github.com/VirusTotal/yara-x)
- [Yara-Rules Community Repository](https://github.com/Yara-Rules/rules)
- [ReversingLabs - Writing Detailed YARA Rules](https://www.reversinglabs.com/blog/writing-detailed-yara-rules-for-malware-detection)
- [YARA Rule Crafting Deep Dive](https://cyberthreatintelligencenetwork.com/index.php/2024/09/11/yara-rule-crafting-a-deep-dive-into-signature-based-threat-hunting-strategies/)

View File

@@ -0,0 +1,31 @@
# YARA Rule Development Report
## Rule Metadata
| Field | Value |
|-------|-------|
| Rule Name | |
| Target Family | |
| Author | |
| Date Created | |
| TLP | WHITE |
## Detection Targets
| Pattern Type | Value | Rationale |
|-------------|-------|-----------|
| String | | |
| Hex Pattern | | |
| Import | | |
## Testing Results
| Metric | Value |
|--------|-------|
| True Positives | |
| False Negatives | |
| False Positives | |
| Detection Rate | % |
| FP Rate | % |
## Deployment Recommendations
1. Deploy to endpoint scanning infrastructure
2. Add to YARA retrohunt on VirusTotal
3. Integrate with SIEM alerting pipeline

View File

@@ -0,0 +1,66 @@
# API Reference: YARA Rule Development for Detection
## yara-python API
| Method | Description |
|--------|-------------|
| `yara.compile(filepath=path)` | Compile rule from file |
| `yara.compile(source=string)` | Compile rule from string |
| `yara.compile(filepaths={ns: path})` | Compile with namespaces |
| `rules.match(filepath=path)` | Scan file against compiled rules |
| `rules.match(data=bytes)` | Scan bytes in memory |
| `rules.match(filepath, timeout=30)` | Scan with timeout |
## Match Object Attributes
| Attribute | Description |
|-----------|-------------|
| `match.rule` | Name of matching rule |
| `match.namespace` | Rule namespace |
| `match.tags` | Rule tags list |
| `match.meta` | Rule metadata dict |
| `match.strings` | List of (offset, identifier, data) |
## YARA Rule Structure
```
rule RuleName : tag1 tag2 {
meta:
description = "..."
author = "..."
date = "2025-01-01"
hash = "sha256_of_sample"
strings:
$s1 = "string" ascii
$s2 = "wide_string" wide
$h1 = { 4D 5A 90 00 }
$r1 = /regex[0-9]+/
condition:
uint16(0) == 0x5A4D and 3 of ($s*)
}
```
## Condition Operators
| Operator | Description |
|----------|-------------|
| `X of ($s*)` | X or more strings match |
| `all of ($s*)` | All strings match |
| `any of ($s*)` | At least one matches |
| `uint16(0) == 0x5A4D` | PE file magic bytes |
| `filesize < 10MB` | File size constraint |
## Python Libraries
| Library | Version | Purpose |
|---------|---------|---------|
| `yara-python` | >=4.3 | Compile and scan YARA rules |
| `hashlib` | stdlib | SHA256 of samples |
| `re` | stdlib | String extraction |
## References
- YARA Documentation: https://yara.readthedocs.io/en/stable/
- yara-python: https://github.com/VirusTotal/yara-python
- YARA Rules Repository: https://github.com/Yara-Rules/rules
- VirusTotal Hunting: https://www.virustotal.com/gui/hunting-overview

View File

@@ -0,0 +1,35 @@
# YARA Rule Development Standards
## Rule Naming Convention
- `Malware_Family_Variant`: For specific malware variants
- `APT_Group_Tool`: For threat actor associated tools
- `Exploit_CVE_YYYY_NNNN`: For exploit payloads
- `Technique_Name`: For generic technique detection
## Rule Quality Metrics
| Metric | Target | Description |
|--------|--------|-------------|
| True Positive Rate | >99% | Detection of known samples |
| False Positive Rate | <0.1% | Matches on clean files |
| Scan Speed | >1000 files/s | Processing performance |
| Maintenance Burden | Low | Frequency of updates needed |
## String Types Reference
| Type | Syntax | Use Case |
|------|--------|----------|
| ASCII text | `"text" ascii` | Plain text strings |
| Wide text | `"text" wide` | UTF-16LE encoded strings |
| Case-insensitive | `"text" nocase` | Variable casing |
| Hex pattern | `{ AA BB CC }` | Byte sequences |
| Wildcard hex | `{ AA ?? CC }` | Single byte wildcard |
| Jump hex | `{ AA [2-4] CC }` | Variable length gap |
| Regex | `/pattern/` | Complex pattern matching |
## MITRE ATT&CK Relevance
- T1027 - Obfuscated Files: Rules detect packed/encoded malware
- T1036 - Masquerading: Rules identify file mimicry
- T1059 - Command Interpreter: Rules detect malicious scripts
## References
- [YARA Documentation](https://yara.readthedocs.io/)
- [YARA Performance Guidelines](https://yara.readthedocs.io/en/stable/writingrules.html)

View File

@@ -0,0 +1,34 @@
# YARA Rule Development Workflows
## Workflow 1: Sample-Driven Rule Creation
```
[Malware Sample] --> [Static Analysis] --> [Extract Unique Strings] --> [Draft Rule]
|
v
[Test Against Samples]
|
v
[Test Against Clean Files]
|
v
[Deploy to Production]
```
## Workflow 2: Family-Wide Detection
```
[Multiple Samples] --> [Cross-Sample Analysis] --> [Find Common Patterns]
|
v
[Build Generic Rule]
|
v
[Validate Coverage]
```
## Workflow 3: Threat Hunt Integration
```
[Intelligence Report] --> [Extract IOCs] --> [Convert to YARA] --> [Retrohunt]
|
v
[Triage New Matches]
```

View File

@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""Agent for YARA rule development and testing.
Creates YARA rules from malware samples by extracting unique strings
and byte patterns, validates rules for performance, tests against
sample sets, and generates detection coverage reports.
"""
import json
import sys
import os
import hashlib
import re
from datetime import datetime
from pathlib import Path
try:
import yara
HAS_YARA = True
except ImportError:
HAS_YARA = False
class YaraRuleDeveloper:
"""Develops, validates, and tests YARA rules."""
def __init__(self, output_dir="./yara_rules"):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.rules = []
def extract_strings(self, sample_path, min_length=8, max_strings=30):
"""Extract unique strings from a binary sample for rule creation."""
with open(sample_path, "rb") as f:
data = f.read()
ascii_strings = re.findall(rb'[\x20-\x7E]{%d,}' % min_length, data)
wide_strings = re.findall(
rb'(?:[\x20-\x7E]\x00){%d,}' % min_length, data)
unique_ascii = list(set(s.decode("ascii", errors="ignore")
for s in ascii_strings))
unique_wide = list(set(s.decode("utf-16-le", errors="ignore")
for s in wide_strings))
scored = []
generic_terms = {"http", "https", "www", "com", "dll", "exe",
"the", "this", "that", "error", "warning"}
for s in unique_ascii:
score = len(s)
if any(g in s.lower() for g in generic_terms):
score -= 5
if re.search(r'[A-Z][a-z]+[A-Z]', s):
score += 3
if "/" in s or "\\" in s:
score += 2
scored.append({"string": s, "type": "ascii", "score": score})
for s in unique_wide:
scored.append({"string": s, "type": "wide", "score": len(s) - 2})
scored.sort(key=lambda x: x["score"], reverse=True)
return scored[:max_strings]
def generate_rule(self, rule_name, sample_path, description="",
tags=None, author="auto"):
"""Generate a YARA rule from a malware sample."""
strings = self.extract_strings(sample_path)
sha256 = hashlib.sha256(Path(sample_path).read_bytes()).hexdigest()
rule_strings = []
for i, s in enumerate(strings[:15]):
if s["type"] == "ascii":
rule_strings.append(f' $s{i} = "{s["string"]}"')
else:
rule_strings.append(f' $s{i} = "{s["string"]}" wide')
tags_str = " : " + " ".join(tags) if tags else ""
rule_text = f"""rule {rule_name}{tags_str}
{{
meta:
description = "{description}"
author = "{author}"
date = "{datetime.utcnow().strftime('%Y-%m-%d')}"
hash = "{sha256}"
strings:
{chr(10).join(rule_strings)}
condition:
uint16(0) == 0x5A4D and filesize < 10MB and 5 of ($s*)
}}
"""
rule_path = self.output_dir / f"{rule_name}.yar"
rule_path.write_text(rule_text)
self.rules.append({"name": rule_name, "path": str(rule_path),
"strings_count": len(rule_strings)})
return {"rule_name": rule_name, "path": str(rule_path),
"strings": len(rule_strings), "hash": sha256}
def validate_rule(self, rule_path):
"""Compile and validate a YARA rule for syntax and performance."""
if not HAS_YARA:
return {"error": "yara-python not installed"}
try:
yara.compile(filepath=rule_path)
return {"valid": True, "path": rule_path}
except yara.SyntaxError as exc:
return {"valid": False, "error": str(exc)}
def test_rule(self, rule_path, sample_dir):
"""Test a YARA rule against a directory of samples."""
if not HAS_YARA:
return {"error": "yara-python not installed"}
try:
compiled = yara.compile(filepath=rule_path)
except yara.SyntaxError as exc:
return {"error": str(exc)}
results = {"matches": [], "no_match": [], "errors": []}
for root, dirs, files in os.walk(sample_dir):
for fname in files:
fpath = os.path.join(root, fname)
try:
matches = compiled.match(fpath, timeout=30)
if matches:
results["matches"].append({
"file": fpath, "rules": [m.rule for m in matches]})
else:
results["no_match"].append(fpath)
except yara.Error as exc:
results["errors"].append({"file": fpath, "error": str(exc)})
return results
def generate_report(self):
report = {
"report_date": datetime.utcnow().isoformat(),
"rules_created": len(self.rules),
"rules": self.rules,
}
print(json.dumps(report, indent=2))
return report
def main():
if len(sys.argv) < 3:
print("Usage: agent.py <rule_name> <sample_path> [test_dir]")
sys.exit(1)
agent = YaraRuleDeveloper()
rule_name = sys.argv[1]
sample = sys.argv[2]
result = agent.generate_rule(rule_name, sample)
validation = agent.validate_rule(result["path"])
print(json.dumps({"rule": result, "validation": validation}, indent=2))
if len(sys.argv) > 3:
test_results = agent.test_rule(result["path"], sys.argv[3])
print(json.dumps(test_results, indent=2))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""
YARA Rule Development and Testing Framework
Assists in creating, testing, and optimizing YARA rules
for malware detection.
Requirements:
pip install yara-python pefile
Usage:
python process.py --analyze sample.exe
python process.py --test rule.yar --samples ./malware --clean ./goodware
python process.py --generate --name MalwareX --strings strings.txt
"""
import argparse
import json
import os
import re
import sys
import time
from collections import Counter
from pathlib import Path
try:
import yara
except ImportError:
print("ERROR: yara-python not installed. Run: pip install yara-python")
sys.exit(1)
try:
import pefile
except ImportError:
pefile = None
class YaraRuleBuilder:
"""Build and test YARA rules."""
def __init__(self):
self.candidate_strings = []
self.candidate_hex = []
self.imports = []
def analyze_sample(self, filepath):
"""Extract candidate patterns from a malware sample."""
with open(filepath, 'rb') as f:
data = f.read()
# Extract ASCII strings (min 8 chars)
ascii_strings = [
s.decode('ascii')
for s in re.findall(rb'[\x20-\x7e]{8,}', data)
]
# Extract wide strings
wide_strings = [
s.decode('utf-16-le')
for s in re.findall(rb'(?:[\x20-\x7e]\x00){8,}', data)
]
# Score strings by uniqueness/suspiciousness
suspicious = [
'http', 'https', 'ftp', 'cmd.exe', 'powershell',
'mutex', 'pipe', 'password', 'encrypt', 'decrypt',
'inject', 'hook', 'shell', 'backdoor', 'keylog',
'screenshot', 'clipboard', 'download', 'upload',
'sandbox', 'vmware', 'virtualbox', 'debug',
]
scored = []
for s in ascii_strings + wide_strings:
score = 0
s_lower = s.lower()
for kw in suspicious:
if kw in s_lower:
score += 10
if len(s) > 20:
score += 5
if re.search(r'[A-Z][a-z]+[A-Z]', s): # CamelCase
score += 3
scored.append((s, score))
scored.sort(key=lambda x: -x[1])
self.candidate_strings = scored[:30]
# PE imports if available
if pefile:
try:
pe = pefile.PE(filepath)
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
for entry in pe.DIRECTORY_ENTRY_IMPORT:
for imp in entry.imports:
if imp.name:
self.imports.append(
imp.name.decode('utf-8', errors='replace')
)
except Exception:
pass
return {
"total_ascii": len(ascii_strings),
"total_wide": len(wide_strings),
"top_candidates": [(s, sc) for s, sc in scored[:10]],
"suspicious_imports": [
i for i in self.imports
if i in ['VirtualAlloc', 'VirtualAllocEx',
'WriteProcessMemory', 'CreateRemoteThread',
'NtUnmapViewOfSection', 'OpenProcess',
'CryptEncrypt', 'InternetOpenA']
],
}
def generate_rule(self, name, author="analyst", description=""):
"""Generate YARA rule from analyzed patterns."""
strings_section = []
conditions = []
# Add top candidate strings
for i, (s, score) in enumerate(self.candidate_strings[:8]):
if score > 0:
escaped = s.replace('\\', '\\\\').replace('"', '\\"')
strings_section.append(
f'$str{i} = "{escaped}" ascii wide'
)
# Add import-based strings
sus_imports = [
i for i in self.imports
if i in ['VirtualAlloc', 'VirtualAllocEx',
'WriteProcessMemory', 'CreateRemoteThread']
]
for i, imp in enumerate(sus_imports[:4]):
strings_section.append(f'$api{i} = "{imp}" ascii')
# Build condition
str_count = len([s for s in strings_section if s.startswith('$str')])
api_count = len([s for s in strings_section if s.startswith('$api')])
condition_parts = ['uint16(0) == 0x5A4D', 'filesize < 5MB']
if str_count > 0:
threshold = max(2, str_count // 2)
condition_parts.append(f'{threshold} of ($str*)')
if api_count > 0:
condition_parts.append(f'{max(1, api_count - 1)} of ($api*)')
rule = f"""rule {name} {{
meta:
description = "{description or f'Detects {name}'}"
author = "{author}"
date = "{time.strftime('%Y-%m-%d')}"
tlp = "WHITE"
strings:
{chr(10) + " ".join(strings_section)}
condition:
{" and ".join(condition_parts)}
}}"""
return rule
def test_rule(self, rule_path_or_text, sample_dir, clean_dir=None):
"""Test YARA rule for detection and false positive rates."""
if os.path.isfile(rule_path_or_text):
rules = yara.compile(filepath=rule_path_or_text)
else:
rules = yara.compile(source=rule_path_or_text)
results = {
"true_positives": 0,
"false_negatives": 0,
"false_positives": 0,
"true_negatives": 0,
"scan_time": 0,
"details": [],
}
# Scan malware samples
start = time.perf_counter()
for f in Path(sample_dir).rglob('*'):
if f.is_file():
try:
matches = rules.match(str(f))
if matches:
results["true_positives"] += 1
else:
results["false_negatives"] += 1
results["details"].append(
{"file": str(f), "result": "FALSE_NEGATIVE"}
)
except Exception:
pass
# Scan clean files
if clean_dir:
for f in Path(clean_dir).rglob('*'):
if f.is_file():
try:
matches = rules.match(str(f))
if matches:
results["false_positives"] += 1
results["details"].append(
{"file": str(f), "result": "FALSE_POSITIVE"}
)
else:
results["true_negatives"] += 1
except Exception:
pass
results["scan_time"] = time.perf_counter() - start
total_samples = results["true_positives"] + results["false_negatives"]
if total_samples > 0:
results["detection_rate"] = round(
results["true_positives"] / total_samples * 100, 2
)
total_clean = results["false_positives"] + results["true_negatives"]
if total_clean > 0:
results["fp_rate"] = round(
results["false_positives"] / total_clean * 100, 4
)
return results
def main():
parser = argparse.ArgumentParser(
description="YARA Rule Development Framework"
)
parser.add_argument("--analyze", help="Analyze sample for YARA patterns")
parser.add_argument("--generate", action="store_true",
help="Generate rule from analysis")
parser.add_argument("--name", default="MalwareDetection",
help="Rule name")
parser.add_argument("--test", help="Test YARA rule file")
parser.add_argument("--samples", help="Malware samples directory")
parser.add_argument("--clean", help="Clean files directory")
parser.add_argument("--output", help="Output rule file")
args = parser.parse_args()
builder = YaraRuleBuilder()
if args.analyze:
analysis = builder.analyze_sample(args.analyze)
print(json.dumps(analysis, indent=2, default=str))
if args.generate:
rule = builder.generate_rule(args.name)
print(f"\n{rule}")
if args.output:
with open(args.output, 'w') as f:
f.write(rule)
print(f"[+] Rule saved to {args.output}")
elif args.test and args.samples:
results = builder.test_rule(args.test, args.samples, args.clean)
print(json.dumps(results, indent=2))
else:
parser.print_help()
if __name__ == "__main__":
main()