performing-yara-rule-development-for-detection
Что он делает
Этот инструмент помогает создавать правила для выявления вредоносного ПО. Он анализирует файлы, чтобы найти уникальные шаблоны, например текстовые или байтовые последовательности, характерные для конкретной вредоносной программы. Это помогает её обнаруживать и избегать ложных срабатываний.
Когда использовать
- ✓При создании защиты от цифровых угроз.
- ✓При классификации разных типов вредоносного ПО.
- ✓Когда нужно превратить данные об угрозах (threat intelligence) в правила обнаружения.
Ссылка на скилл
https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/performing-yara-rule-development-for-detection/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Создай YARA правило для обнаружения вредоносного ПО, которое использует строку 'evil_command' и подключается к IP-адресу '192.168.1.100'.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Инструмент изучает код программы и ищет в нём характерные текстовые или байтовые последовательности. На их основе строится «сигнатура» (YARA правило), по которой можно найти эту программу на других компьютерах.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
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-pythonlibrary - 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
#!/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
…
Частые вопросы
Что такое YARA правила?
YARA правила похожи на цифровые отпечатки: они описывают шаблоны, которые встречаются в файлах. Их используют, чтобы находить и классифицировать вредоносное ПО.
Что такое «ложные срабатывания»?
Ложные срабатывания возникают, когда правило безопасности ошибочно считает что-то вредоносным, хотя на самом деле это безобидная программа.
Почему важен анализ «распакованных артефактов» вредоносного ПО?
Вредоносное ПО часто маскирует себя, то есть «упаковывает». Анализ кода после распаковки показывает его настоящие уникальные признаки, и обнаружение становится точнее.
Подробности
Оригинальное описание автора
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.
Популярность
- Звёзды на GitHub
- 35k
- Место в рейтинге
- #8340
- Лицензия
- Apache-2.0
- Обновлён
- 31.08.2026
Комментарии
- …
Другие скиллы из этого репозитория
abusing-dpapi-for-credential-access
35kДаёт ИИ-агенту готовые инструкции для конкретной задачи, чтобы он делал её лучше и быстрее.
abusing-shadow-credentials-for-privesc
35kУчит ИИ-агента писать ясные структурированные тексты.
achieving-cmmc-level-2-compliance
35kПомогает агенту подготовить среду к соответствию CMMC уровня 2.
acquiring-disk-image-with-dd-and-dcfldd
35kПомогает агенту создавать точные копии дисков для расследований.
Похожие скиллы
add-model-provider
394kПомогает агенту подключить нового провайдера ИИ-моделей к OpenClaw безопасными командами, хранить ключи API не в открытом виде и провести живой тест.
acp-router
394kПомогает агенту передать задачу инструменту для программирования, например Claude Code или Cursor, через OpenClaw, чтобы работа шла в этом инструменте.
browser-automation
394kУчит агента пошагово управлять веб-страницами: входить в аккаунты, работать с вкладками и восстанавливаться, если страница перестала отвечать.