El patrón perfecto para la detección de malware
YARA es una herramienta diseñada para ayudar a los investigadores de malware a identificar y clasificar muestras de malware mediante la creación de descripciones de familias de malware basadas en patrones textuales o binarios.
En términos simples: YARA te permite crear "reglas" que describen patrones específicos. Cuando escaneas archivos con estas reglas, YARA te dice si encuentra esos patrones.
¿Por qué YARA es genial?
sudo apt update
sudo apt install yara
sudo yum install epel-release
sudo yum install yara
brew install yara
Descarga el ejecutable desde: github.com/VirusTotal/yara/releases
yara --version
Una regla YARA tiene la siguiente estructura básica:
rule NombreDeLaRegla
{
meta:
description = "Descripción de la regla"
author = "Tu nombre"
date = "2024-01-01"
strings:
$cadena1 = "texto a buscar"
$cadena2 = { 48 65 6C 6C 6F } // bytes en hexadecimal
condition:
$cadena1 or $cadena2
}
Importante:
condition es obligatoriastrings:
$texto1 = "Hola mundo"
$texto2 = "password"
$texto3 = "malware" nocase // insensible a mayúsculas
$texto4 = "test" wide // formato Unicode
strings:
$hex1 = { 4D 5A } // "MZ" en hexadecimal
$hex2 = { 4D 5A ?? ?? 50 45 } // ?? = cualquier byte
$hex3 = { 4D 5A [0-100] 50 45} // salto de 0-100 bytes
strings:
$regex1 = /http:\/\/[a-z]+\.com/
$regex2 = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ // IP
$regex3 = /[a-zA-Z0-9]{32}/ nocase // MD5 hash
nocase: Ignora mayúsculas/minúsculaswide: Búsqueda en formato Unicodeascii: Solo caracteres ASCIIfullword: Palabra completaxor: Búsqueda con XORbase64: Decodifica Base64base64wide: Base64 + wideConsejo Pro: Combina modificadores para mayor flexibilidad: $string = "password" nocase wide ascii
condition:
$string1 and $string2 // Ambos deben existir
$string1 or $string2 // Al menos uno debe existir
not $string1 // No debe existir
($string1 and $string2) or $string3
condition:
#string1 > 5 // Más de 5 ocurrencias
#string1 in (1..10) // Entre 1 y 10 ocurrencias
any of ($string*) // Cualquier string que empiece con "string"
all of them // Todos los strings definidos
2 of ($a, $b, $c) // Al menos 2 de los 3 strings
condition:
$string1 at 0 // String en el byte 0 (inicio)
$string1 at entrypoint // String en el punto de entrada
filesize > 1MB // Archivo mayor a 1 MB
filesize < 10KB // Archivo menor a 10 KB
Información PE:
pe.number_of_sections > 3
pe.imports("kernel32.dll")
Hash del archivo:
hash.md5(0, filesize) == "abc123..."
Matemáticas:
math.entropy(0, filesize) > 7.5
Tiempo:
pe.timestamp > 1577836800
condition:
(filesize > 10KB and filesize < 1MB) and
(any of ($malware*) or #suspicious > 3) and
pe.number_of_sections between 3 and 8
Los metadatos proporcionan información adicional sobre la regla sin afectar la lógica de detección:
rule MiReglaDetallada
{
meta:
description = "Detecta la familia de malware XYZ"
author = "Tu Nombre "
date = "2024-08-15"
version = "1.2"
severity = "high"
family = "trojan"
sample = "abc123def456..."
reference = "https://blog.security.com/analysis"
tags = "trojan,banking,stealer"
tlp = "white"
strings:
// ... definiciones de strings
condition:
// ... condiciones
}
Buenas prácticas:
description, author y datetags para facilitar la organizaciónreference para análisis detalladosversion cuando modifiques la reglarule Suspicious_PE_File
{
meta:
description = "Detecta ejecutables PE con strings sospechosos"
author = "Security Analyst"
date = "2024-08-15"
strings:
$mz = { 4D 5A } // Firma MZ
$pe = "PE"
$sus1 = "keylogger" nocase
$sus2 = "password" nocase
$sus3 = "backdoor" nocase
$sus4 = "rootkit" nocase
condition:
$mz at 0 and $pe and any of ($sus*)
}
rule Ransomware_Generic
{
meta:
description = "Detecta comportamientos típicos de ransomware"
author = "Malware Hunter"
severity = "high"
family = "ransomware"
strings:
$ransom1 = "Your files have been encrypted" nocase
$ransom2 = "pay bitcoin" nocase
$ransom3 = "decrypt" nocase
$ransom4 = "ransom" nocase
$ext1 = ".locked"
$ext2 = ".encrypted"
$ext3 = ".crypto"
condition:
(2 of ($ransom*)) or
(any of ($ransom*) and any of ($ext*))
}
rule Malicious_URLs
{
meta:
description = "Detecta URLs con patrones sospechosos"
author = "Web Security Team"
strings:
$url1 = /https?:\/\/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/
$url2 = /bit\.ly\/[a-zA-Z0-9]{6,}/
$url3 = /tinyurl\.com\/[a-zA-Z0-9]{6,}/
$phish1 = "paypal-secure" nocase
$phish2 = "bank-update" nocase
$phish3 = "account-verify" nocase
condition:
any of ($url*) or any of ($phish*)
}
rule Malicious_PDF
{
meta:
description = "Detecta PDFs con JavaScript sospechoso"
author = "Document Security"
strings:
$pdf_header = "%PDF-"
$js1 = "/JavaScript" nocase
$js2 = "/JS" nocase
$suspicious1 = "eval(" nocase
$suspicious2 = "unescape(" nocase
$suspicious3 = "String.fromCharCode(" nocase
$action = "/OpenAction" nocase
condition:
$pdf_header at 0 and
(any of ($js*)) and
(any of ($suspicious*) or $action)
}
1. Escanear un archivo:
yara mi_regla.yar archivo_sospechoso.exe
2. Escanear un directorio:
yara -r mi_regla.yar /ruta/del/directorio/
3. Usar múltiples reglas:
yara regla1.yar regla2.yar archivo.exe
Consejo: Para aprender más sobre YARA, consulta la documentación oficial.
rule Advanced_YARA_Rule
{
meta:
description = "Regla avanzada para detectar malware específico"
author = "Security Researcher"
date = "2024-08-15"
strings:
$header = { 4D 5A } // Firma MZ
$pe = "PE" // Firma PE
$signature1 = "malware_pattern_1" nocase
$signature2 = /http:\/\/[a-z]+\.com/ // URL con expresión regular
condition:
$header at 0 and $pe and
(any of ($signature*) or #suspicious > 5)
}
rule Complex_Analysis
{
meta:
description = "Análisis complejo de archivos"
author = "Security Analyst"
strings:
$pattern1 = "suspicious_string" nocase
$pattern2 = { 4D 5A [0-100] 50 45 } // Saltando bytes
condition:
(filesize > 1KB and filesize < 10MB) and
(pe.number_of_sections between 1 and 10) and
(any of ($pattern*) or math.entropy(0, filesize) > 7.0)
}
Recomendación: Combina diferentes técnicas para crear reglas más robustas y precisas.
Recomendación: Practica con herramientas como YARA-GUI para aprender mejor las reglas.