Sigma
Sigma Cheatsheet
# Install via pip
pip install sigma-cli
# Install with all dependencies
pip install sigma-cli[all]
# Install development version
pip install git+https://github.com/SigmaHQ/sigma.git
# Verify installation
sigma --version
# Clone repository
git clone https://github.com/SigmaHQ/sigma.git
cd sigma
# Install in development mode
pip install -e .
# Install with optional dependencies
pip install -e .[test,dev]
# Pull Sigma Docker image
docker pull sigmahq/sigma
# Run Sigma in container
docker run --rm -v $(pwd):/data sigmahq/sigma convert -t splunk /data/rules/
# Create alias for convenience
alias sigma='docker run --rm -v $(pwd):/data sigmahq/sigma'
title: Suspicious PowerShell Execution
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detects suspicious PowerShell command execution
author: Security Team
date: 2023/01/15
modified: 2023/01/20
tags:
- attack.execution
- attack.t1059.001
logsource:
category: process_creation
product: windows
detection:
selection:
Image|endswith: '\powershell.exe'
CommandLine|contains:
- '-EncodedCommand'
- '-WindowStyle Hidden'
- 'DownloadString'
condition: selection
falsepositives:
- Legitimate administrative scripts
level: medium
# Required fields
title: "Rule Title"
id: "unique-uuid-here"
status: experimental|test|stable
description: "Detailed description"
# Optional metadata
author: "Author Name"
date: 2023/01/15
modified: 2023/01/20
references:
- https://attack.mitre.org/techniques/T1059/001/
tags:
- attack.execution
- attack.t1059.001
level: low|medium|high|critical
logsource:
category: process_creation
product: windows
service: sysmon
definition: "Sysmon Event ID 1"
detection:
selection1:
EventID: 1
Image|endswith: '\cmd.exe'
selection2:
CommandLine|contains:
- 'whoami'
- 'net user'
condition: selection1 and selection2
detection:
selection:
EventID: 4624
LogonType: 3
TargetUserName: 'administrator'
condition: selection
detection:
sel_process:
Image|endswith: '\powershell.exe'
sel_command:
CommandLine|contains:
- 'Invoke-Expression'
- 'IEX'
condition: sel_process and sel_command
detection:
selection:
# Contains substring
CommandLine|contains: 'malware'
# Starts with
Image|startswith: 'C:\Temp\'
# Ends with
FileName|endswith: '.exe'
# Case insensitive
ProcessName|contains|all:
- 'cmd'
- 'powershell'
# Regular expression
CommandLine|re: '.*\.(exe|bat|cmd)
**Numeric Modifiers:**
```yaml
detección:
selección:
Menos que
ProcessId habitlt: 1000
# Más grande que
FileSize intimidadgt: 1048576
# Mayor o igual
EventID habitgte: 4624
Menos o igual
Logon Tipo intimidad: 10
__CODE_BLOCK_11_yaml
detección:
sel_suspicious_process:
Image WordPressendswith:
- '\powershell.exe '
- '\cmd.exe '
Sel_suspicious_args:
CommandLine habitcontains:
- EncodedCommand '
- 'DownloadString '
sel_network:
Destino Puerto:
- 80
- 443
condición: sel_suspicious_process y sel_suspicious_args y sel_network
detección:
selección:
EventID: 4625
Meta Usuario: '*
condición: selección válidacount(TargetUserName) por SourceNetworkAddress 10
__CODE_BLOCK_13_yaml
detección:
selección:
EventID: 4624
LogonType: 3
condición: selección válidacount() por TargetUserName ⇩ 5 tiempo 5m
__CODE_BLOCK_14_yaml
Título: Proceso sospechoso en el directorio de temperatura
logsource:
categoría: process_creation
producto: ventanas
detección:
selección:
Image arreststartswith:
- 'C:\Temp\ '
- 'C:\Users\*\AppData\Local\Temp\ '
Imagen eternaendswith: '.exe'
condición: selección
nivel: medio
Título: Potencia codificada Shell Command
logsource:
categoría: process_creation
producto: ventanas
detección:
selección:
Image sometidain: '\powershell.exe '
CommandLine invisiblecontains: '-EncodedCommand '
condición: selección
nivel: alto
Título: Conexión a dominio sospechoso
logsource:
categoría: red_conexión
producto: ventanas
detección:
selección:
Iniciado: 'verdad '
DestinationApodo de emergenciascon:
- '.tk'
- 'ml '
- '.ga '
condición: selección
nivel: medio
__CODE_BLOCK_17_yaml
Título: Executable in Startup Folder
logsource:
categoría: archivo_event
producto: ventanas
detección:
selección:
TargetApodo de vida contiene: '\Startup\ '
TargetApodo de vidafinescon: '.exe'
condición: selección
nivel: alto
__CODE_BLOCK_18_yaml
Título: Registro Run Key Modification
logsource:
categoría: registro_event
producto: ventanas
detección:
selección:
Meta Objeción permanente contiene:
- '\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ '
- '\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\ '
condición: selección
nivel: medio
__CODE_BLOCK_19_bash
# Convertir una sola regla
sigma convertido -t splunk regla.yml
# Convertir múltiples reglas
sigma convert -t splunk rules/*.yml
# Convertir con configuración personalizada
sigma convert -t splunk -c splunk-windows.yml rule.yml
# Producto del archivo
sigma convert -t splunk rule.yml -o splunk_query.txt
# Convertir to Elasticsearch Query DSL
sigma convertido -t elasticsearch rule.yml
# Convertir to ECS format
sigma convertido -t elasticsearch -c ecs-cloudtrail.yml rule.yml
# Convertir to Kibana
sigma convert -t kibana rule.yml
# Convertir to QRadar AQL
sigma convert -t qradar rule.yml
# Convertir con mapeo de campo
sigma convert -t qradar -c qradar-fields.yml rule.yml
# Convertir to KQL
sigma convert -t microsoft365defender rule.yml
# Convertir to Azure Sentinel
sigma convert -t azure-sentinel rule.yml
__CODE_BLOCK_23_yaml
# splunk-custom.yml
Título: Configuración Splunk personalizada
orden: 20
backends:
- ¿Qué?
logsources:
ventanas:
categoría: process_creation
condiciones:
EventID: 1
reescribir:
producto: ventanas
servicio: sísmon
mapas de campo:
Imagen: process_name
CommandLine: process_command_line
ProcessId: process_id
# Field-mapping. Yml
Título: Custom Field Mapping
mapas de campo:
Eventos de seguridad de Windows
EventID: event_id
Meta UserName: user_name
FuenteNetwork Dirección: src_ip
DestinationPort: dest_port
# Sysmon Events
Imagen: process_path
CommandLine: command_line
ProcessId: pid
ParentProcess Id: ppid
# Sintaxis de regla validada
sigma check rule.yml
# Validar múltiples reglas
sigma check rules/*.yml
# Check with specific backend
sigma check -t splunk rule. Yml
# Validación de verbosa
sigma check -v rule.yml
# Conversión de pruebas
sigma convertido -t splunk regla.yml - Dirigido
# Prueba con datos de muestra
sigma test rule.yml --data sample_logs.json
# Debug lógica regla
sigma convertido -t splunk regla.yml - Debug
# Use partidos de campo específicos en lugar de comodines
detección:
selección:
# Good - specific match
EventID: 4624
LogonType: 3
Evitar - demasiado amplio
# EventData sostiene: 'logon'
condición: selección
__CODE_BLOCK_28_yaml
detección:
selección:
Image sometidain: '\powershell.exe '
CommandLine habitcontains: 'DownloadString '
filtro:
El usuario sostiene: 'SYSTEM'
ParentImage sometidaendswith: '\services.exe '
condición: selección y no filtro
reglas/
- Ventanas
- proceso de creación
- red/conexión
.
- Registro_evento/
- No.
- proceso de creación
- red/conexión
Nube/nube
- Aws/
- Azure/
- Sí.
# Uso de etiquetas consistentes
tags:
- ataque. ejecución
- ataque.t1059.001
- Detección.
- plataforma.ventanas
- data_source.process_monitoring
# Crear rama de función para nueva regla
git checkout -b característica / nueva detección-rule
# Agregar archivo de regla
git add rules/windows/process_creation/suspicious_powershell.yml
# Commit with descriptive message
git commit -m "Añadir detección para la ejecución sospechosa de PowerShell"
# Push and create pull request
git push origin feature/new-detection-rule
__CODE_BLOCK_32_bash
# Validar antes de comprometerse
verificación de sigma reglas/ventanas/process_creation/*.yml
# Conversión de pruebas para alcanzar SIEM
sigma convert -t splunk reglas/ventanas/process_creation/new_rule.yml
# Compruebe los duplicados
grep -r "título:" reglas/resistentes "Suspicious PowerShell"
__CODE_BLOCK_33_yaml
nombre: Sigma Rule Validation
[push, pull_request]
empleo:
validar:
ubuntu-latest
pasos:
- usos: acciones/checkout@v2
- nombre: Setup Python
usos: acciones/setup-python@v2
con:
python-version: '3.9'
- nombre: Install Sigma
run: pip install sigma-cli
- nombre: Reglas de validación
run:
encontrar reglas/ -nombre "*.yml" -exec sigma check \{\} \;
- nombre: Test Conversions
run:
sigma convert -t splunk reglas/ventanas/process_creation/*.yml
sigma convertido -t elasticsearch rules/linux/process_creation/*.yml
#/bin/bash
# Despliegue a la luz. #
RULES_DIR="rules/ventanas"
SPLUNK_CONFIG="configs/splunk-windows.yml"
OUTPUT_DIR="splunk_searches"
# Convertir reglas en Splunk
para la regla en $RULES_DIR/*.yml
rule_name=$(basename "$rule" .yml)
sigma convert -t splunk -c $SPLUNK_CONFIG "$rule"
hecho
# Deploy to Splunk via REST API
buscar en $OUTPUT_DIR/*.spl; do
search_name=$(basename "$search" .spl)
curl -k -u admin:password \
-d "name=$search_name" \
-d "search=$(cat $search)" \
https://splunk:8089/services/saved/searches
hecho
importaciones o
importa yaml
de la importación de la investigación elástica
de sigma.cli.convert importación convert_rule
def deployed_sigma_rules_to_elasticsearch():
""Deploy Sigma gobierna como alertas Elasticsearch Watcher"""
es = Elasticsearch(['localhost:9200'])
rules_dir = 'rules/linux '
for rule_file in os.listdir(rules_dir):
si rule_file.endswith('.yml'):
rule_path = os.path.join(rules_dir, rule_file)
# Convertir Sigma rule to Elasticsearch query
es_query = convert_rule(rule_path, 'elásticosearch')
# Create Watcher alert
con open(rule_path, 'r) como f:
rule_data = yaml.safe_load(f)
watcher_config = \{
"trigger":
"schedule": \{"interval": "5m"\}
\}
"input": \{
"busca": \{
"request": \{
"search_type": "query_then_fetch",
"indices": ["logs-*],
"body": \{
"query": es_query
{\cHFF}
{\cHFF}
{\cHFF}
\}
"condición": \{
"compare": \{
"ctx.payload.hits.total": \{"gt": 0\}
{\cHFF}
\}
"acciones": \{
"log_alert": \{
"logging": \{
"texto": f"Sigma rule triggered: \{rule_data['title']\}"
{\cHFF}
{\cHFF}
{\cHFF}
{\cHFF}
# Deploy to Elasticsearch
rule_id = rule_data['id']
es.watcher.put_watch(id=rule_id, body=watcher_config)
Título: Multiple Failed Logons
logsource:
categoría: autenticación
producto: ventanas
detección:
selección:
EventID: 4625
Meta Usuario: '*
condición: selección válidacount(TargetUserName) por SourceNetworkAddress 5
tiempo: 5m
nivel: medio
Título: Volumen de ejecución del proceso inusual
logsource:
categoría: process_creation
producto: ventanas
detección:
selección:
Image sometidain: '\powershell.exe '
condición: selección válidacount() por Computer > avg(count()) * 3
plazo: 1h
nivel: medio
Título: Credential Dumping Followed by Lateral Movement
logsource:
categoría: process_creation
producto: ventanas
detección:
etapa 1:
Imagen eternaendswith: '\mimikatz.exe '
CommandLine habitcontain: 'sekurlsa::logonpasswords '
etapa2:
Image WordPressendswith: '\psexec.exe '
CommandLine impertines: '\\\*
condición: etapa1 seguida por etapa2
tiempo: 30m
nivel: alto
Título: Entropy-based Suspicious String Detection
logsource:
categoría: process_creation
producto: ventanas
detección:
selección:
CommandLine: '*
condición: selección perpetuaentropy(CommandLine) ≤ 6.5
nivel: medio
# Verificación de la sintaxis YAML
python -c "import yaml; yaml.safe_load(open('rule.yml'))"
# Validate Sigma rule structure
sigma check rule.yml -v
# Verificar mapas de campo
sigma convertido -t splunk regla.yml - Debug
# Lista de backends disponibles
sigma lista backends
# Configuración de backend
modificadores de la lista de sigma -t splunk
# Prueba con regla mínima
sigma convert -t splunk -e 'detección: \{selection: \{EventID: 1\}, condición: selección\} '
# Conversión de reglas de perfil
tiempo sigma convertido -t splunk reglas/*.yml
# Comprobar la complejidad de la regla
grep -c "condición:" regla.yml
grep -c "vivir" regla.yml # Modificadores de cuenta
# Optimize rule structure
sigma convertido -t splunk regla.yml - optimización
This comprehensive Sigma cheatsheet covers rule development, conversion, deployment, and advanced features for effective threat detection across multiple SIEM platforms.
# Base64 encoded
CommandLine|base64offset|contains: 'powershell'
** Modificadores numéricos:**
Advanced Conditions¶
Complex Logic:
Aggregation Conditions:
Time-based Conditions:
Rule Categories¶
Process Creation Rules¶
Suspicious Process Execution:
Command Line Analysis:
Network Connection Rules¶
Suspicious Outbound Connections:
File System Rules¶
Suspicious File Creation:
Registry Rules¶
Registry Persistence:
Conversion and Deployment¶
Convert Rules to SIEM Formats¶
Splunk Conversion:
Elastic/ECS Conversion:
QRadar Conversion:
Microsoft Sentinel Conversion:
Backend Configurations¶
Custom Backend Config:
Field Mapping:
Rule Development¶
Testing Rules¶
Rule Validation:
Rule Testing:
Rule Optimization¶
Performance Optimization:
Reduce False Positives:
Rule Management¶
Rule Collections¶
Organize Rules by Category:
Rule Metadata Management:
Version Control¶
Git Workflow:
Rule Review Process:
Integration Examples¶
CI/CD Pipeline¶
GitHub Actions Workflow:
SIEM Integration¶
Splunk Integration:
Elasticsearch Integration:
Advanced Features¶
Aggregation Rules¶
Count-based Detection:
Statistical Analysis:
Correlation Rules¶
Multi-stage Attack Detection:
Custom Functions¶
Custom Detection Logic:
Troubleshooting¶
Common Issues¶
Rule Validation Errors:
Conversion Problems:
Performance Issues:
Debugging¶
Debug Mode:
Rule Analysis: