Aller au contenu

Sigma Cheatsheet

Sigma is a generic and open signature format that allows you to describe log events in a straightforward manner. It enables security analysts to write detection rules once and convert them to various SIEM formats, making threat detection portable across different security platforms. ## Installation and Setup ### Python Installation **Install Sigma Tools:**
# 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
**Install from Source:**
# 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]
### Docker Installation **Docker Setup:**
# 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'
## Sigma Rule Structure ### Basic Rule Format **Standard Sigma Rule:**
title: Suspicious PowerShell Execution
id: 12345678-1234-1234-1234-123456789012
status: experimental
Description: Detects suspicious PowerShell commande execution
author: Security Team
date: 2023/01/15
modified: 2023/01/20
tags:
    - attack.execution
    - attack.t1059.001
logsource:
    category: processus_creation
    product: windows
detection:
    selection:
        Image|endswith: '\powershell.exe'
        commandeLine|contains:
            - '-Encodedcommande'
            - '-WindowStyle Hidden'
            - 'DownloadString'
    condition: selection
falsepositives:
    - Legitimate administrative scripts
level: medium
### Rule Components **Metadata Fields:**
# 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
références:
    - https: //attack.mitre.org/techniques/T1059/001/
tags:
    - attack.execution
    - attack.t1059.001
| level: low | medium | high | critical |
**Log Source Definition:**
logsource:
    category: processus_creation
    product: windows
    service: sysmon
    definition: "Sysmon Event ID 1"
**Detection Logic:**
detection:
    selection1:
        EventID: 1
        Image|endswith: '\cmd.exe'
    selection2:
        commandeLine|contains:
            - 'whoami'
            - 'net user'
    condition: selection1 and selection2
## Detection Patterns ### Selection Patterns **Basic Selection:**
detection:
    selection:
        EventID: 4624
        LogonType: 3
        ciblenom d'utilisateur: 'administrator'
    condition: selection
**Multiple Selections:**
detection:
    sel_processus:
        Image|endswith: '\powershell.exe'
    sel_commande:
        commandeLine|contains:
            - 'Invoke-Expression'
            - 'IEX'
    condition: sel_processus and sel_commande
**cléword Lists:**
detection:
    cléwords:
        - 'mimikatz'
        - 'sekurlsa'
        - 'kerberos'
    condition: cléwords
### Field Modifiers **String Modifiers:**
detection:
    selection:
        # Contains substring
        commandeLine|contains: 'logiciel malveillant'

        # Starts with
        Image|startswith: 'C:\Temp\'

        # Ends with
        FileName|endswith: '.exe'

        # Case insensitive
| processusName | contains | all: |
            - 'cmd'
            - 'powershell'

        # Regular expression
| commandeLine | re: '.*\.(exe | bat | cmd) |

**Numeric Modifiers: **
```yaml
detection:
    selection:
        # Less than
        processusId|lt: 1000

        # Greater than
        FileSize|gt: 1048576

        # Greater than or equal
        EventID|gte: 4624

        # Less than or equal
        LogonType|lte: 10
### Advanced Conditions **Complex Logic:**
detection:
    sel_suspicious_processus:
        Image|endswith:
            - '\powershell.exe'
            - '\cmd.exe'
    sel_suspicious_args:
        commandeLine|contains:
            - '-Encodedcommande'
            - 'DownloadString'
    sel_network:
        Destinationport:
            - 80
            - 443
    condition: sel_suspicious_processus and sel_suspicious_args and sel_network
**Aggregation Conditions:**
detection:
    selection:
        EventID: 4625
        ciblenom d'utilisateur: '*'
    condition: selection|count(ciblenom d'utilisateur) by SourceNetworkAddress > 10
**Time-based Conditions:**
detection:
    selection:
        EventID: 4624
        LogonType: 3
| condition: selection | count() by ciblenom d'utilisateur > 5 | timeframe 5m |
## Rule Categories ### processus Creation Rules **Suspicious processus Execution:**
title: Suspicious processus in Temp Directory
logsource:
    category: processus_creation
    product: windows
detection:
    selection:
        Image|startswith:
            - 'C:\Temp\'
            - 'C:\Users\*\AppData\Local\Temp\'
        Image|endswith: '.exe'
    condition: selection
level: medium
**commande Line Analysis:**
title: Encoded PowerShell commande
logsource:
    category: processus_creation
    product: windows
detection:
    selection:
        Image|endswith: '\powershell.exe'
        commandeLine|contains: '-Encodedcommande'
    condition: selection
level: high
### Network connexion Rules **Suspicious Outbound connexions:**
title: connexion to Suspicious Domain
logsource:
    category: network_connexion
    product: windows
detection:
    selection:
        Initiated: 'true'
        Destinationhôtename|endswith:
            - '.tk'
            - '.ml'
            - '.ga'
    condition: selection
level: medium
### File System Rules **Suspicious File Creation:**
title: Executable in Startup Folder
logsource:
    category: file_event
    product: windows
detection:
    selection:
        cibleFilename|contains: '\Startup\'
        cibleFilename|endswith: '.exe'
    condition: selection
level: high
### Registry Rules **Registry persistance:**
title: Registry Run clé Modification
logsource:
    category: registry_event
    product: windows
detection:
    selection:
        cibleObject|contains:
            - '\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\'
            - '\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\'
    condition: selection
level: medium
## Conversion and Deployment ### Convert Rules to SIEM Formats **Splunk Conversion:**
# Convert single rule
sigma convert -t splunk rule.yml

# Convert multiple rules
sigma convert -t splunk rules/*.yml

# Convert with custom config
sigma convert -t splunk -c splunk-windows.yml rule.yml

# Output to file
sigma convert -t splunk rule.yml -o splunk_query.txt
**Elastic/ECS Conversion:**
# Convert to Elasticsearch Query DSL
sigma convert -t elasticsearch rule.yml

# Convert to ECS format
sigma convert -t elasticsearch -c ecs-cloudtrail.yml rule.yml

# Convert to Kibana
sigma convert -t kibana rule.yml
**QRadar Conversion:**
# Convert to QRadar AQL
sigma convert -t qradar rule.yml

# Convert with field mapping
sigma convert -t qradar -c qradar-fields.yml rule.yml
**Microsoft Sentinel Conversion:**
# Convert to KQL
sigma convert -t microsoft365defender rule.yml

# Convert to Azure Sentinel
sigma convert -t azure-sentinel rule.yml
### Backend configurations **Custom Backend Config:**
# splunk-custom.yml
title: Custom Splunk configuration
order: 20
backends:
  - splunk
logsources:
  windows:
    category: processus_creation
    conditions:
      EventID: 1
    rewrite:
      product: windows
      service: sysmon
fieldmappings:
  Image: processus_name
  commandeLine: processus_commande_line
  processusId: processus_id
**Field Mapping:**
# field-mapping.yml
title: Custom Field Mapping
fieldmappings:
  # Windows Security Events
  EventID: event_id
  ciblenom d'utilisateur: user_name
  SourceNetworkAddress: src_ip
  Destinationport: dest_port

  # Sysmon Events
  Image: processus_path
  commandeLine: commande_line
  processusId: pid
  ParentprocessusId: ppid
## Rule Development ### Testing Rules **Rule Validation:**
# Validate rule syntaxe
sigma check rule.yml

# Validate multiple rules
sigma check rules/*.yml

# Check with specific backend
sigma check -t splunk rule.yml

# Verbose validation
sigma check -v rule.yml
**Rule Testing:**
# Test conversion
sigma convert -t splunk rule.yml --dry-run

# Test with sample data
sigma test rule.yml --data sample_logs.json

# Debug rule logic
sigma convert -t splunk rule.yml --debug
### Rule Optimization **Performance Optimization:**
# Use specific field matches instead of wildcards
detection:
    selection:
        # Good - specific match
        EventID: 4624
        LogonType: 3

        # Avoid - too broad
        # EventData|contains: 'logon'
    condition: selection
**Reduce False Positives:**
detection:
    selection:
        Image|endswith: '\powershell.exe'
        commandeLine|contains: 'DownloadString'
    filter:
        User|contains: 'SYSTEM'
        ParentImage|endswith: '\services.exe'
    condition: selection and not filter
## Rule Management ### Rule Collections **Organize Rules by Category:**
rules/
├── windows/
│   ├── processus_creation/
│   ├── network_connexion/
│   ├── file_event/
│   └── registry_event/
├── linux/
│   ├── processus_creation/
│   └── network_connexion/
└── cloud/
    ├── aws/
    ├── azure/
    └── gcp/
**Rule Metadata Management:**
# Use consistent tagging
tags:
    - attack.execution
    - attack.t1059.001
    - detection.emerging_threats
    - platform.windows
    - data_source.processus_monitoring
### Version Control **Git Workflow:**
# Create feature branch for new rule
git checkout -b feature/new-detection-rule

# Add rule file
git add rules/windows/processus_creation/suspicious_powershell.yml

# Commit with descriptive message
git commit -m "Add detection for suspicious PowerShell execution"

# Push and create pull request
git push origin feature/new-detection-rule
**Rule Review processus:**
# Validate before commit
sigma check rules/windows/processus_creation/*.yml

# Test conversion to cible SIEM
sigma convert -t splunk rules/windows/processus_creation/new_rule.yml

# Check for duplicates
grep -r "title:" rules/|grep "Suspicious PowerShell"
## Integration exemples ### CI/CD Pipeline **GitHub Actions Workflow:**
name: Sigma Rule Validation
on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.9'

      - name: Install Sigma
        run: pip install sigma-cli

      - name: Validate Rules
        run: |
          find rules/ -name "*.yml" -exec sigma check \{\} \;

      - name: Test Conversions
        run: |
          sigma convert -t splunk rules/windows/processus_creation/*.yml
          sigma convert -t elasticsearch rules/linux/processus_creation/*.yml
### SIEM Integration **Splunk Integration:**
#!/bin/bash
# deploy-to-splunk.sh

RULES_DIR="rules/windows"
SPLUNK_CONFIG="configs/splunk-windows.yml"
OUTPUT_DIR="splunk_searches"

# Convert rules to Splunk
for rule in $RULES_DIR/*.yml; do
    rule_name=$(basename "$rule" .yml)
    sigma convert -t splunk -c $SPLUNK_CONFIG "$rule" > "$OUTPUT_DIR/$\{rule_name\}.spl"
done

# Deploy to Splunk via REST API
for search in $OUTPUT_DIR/*.spl; do
    search_name=$(basename "$search" .spl)
    curl -k -u admin:mot de passe \
         -d "name=$search_name" \
         -d "search=$(cat $search)" \
         https://splunk:8089/services/saved/searches
done
**Elasticsearch Integration:**
import os
import yaml
from elasticsearch import Elasticsearch
from sigma.cli.convert import convert_rule

def deploy_sigma_rules_to_elasticsearch():
    """Deploy Sigma rules as Elasticsearch Watcher alerts"""
    es = Elasticsearch(['localhôte:9200'])

    rules_dir = 'rules/linux'
    for rule_file in os.listdir(rules_dir):
        if rule_file.endswith('.yml'):
            rule_path = os.path.join(rules_dir, rule_file)

            # Convert Sigma rule to Elasticsearch query
            es_query = convert_rule(rule_path, 'elasticsearch')

            # Create Watcher alert
            with open(rule_path, 'r') as f:
                rule_data = yaml.safe_load(f)

            watcher_config = \{
                "trigger": \{
                    "schedule": \{"interval": "5m"\}
                \},
                "input": \{
                    "search": \{
                        "request": \{
                            "search_type": "query_then_fetch",
                            "indices": ["logs-*"],
                            "body": \{
                                "query": es_query
                            \}
                        \}
                    \}
                \},
                "condition": \{
                    "compare": \{
                        "ctx.charge utile.hits.total": \{"gt": 0\}
                    \}
                \},
                "actions": \{
                    "log_alert": \{
                        "logging": \{
                            "text": f"Sigma rule triggered: \{rule_data['title']\}"
                        \}
                    \}
                \}
            \}

            # Deploy to Elasticsearch
            rule_id = rule_data['id']
            es.watcher.put_watch(id=rule_id, body=watcher_config)
## Advanced Features ### Aggregation Rules **Count-based Detection:**
title: Multiple Failed Logons
logsource:
    category: authentification
    product: windows
detection:
    selection:
        EventID: 4625
        ciblenom d'utilisateur: '*'
    condition: selection|count(ciblenom d'utilisateur) by SourceNetworkAddress > 5
timeframe: 5m
level: medium
**Statistical Analysis:**
title: Unusual processus Execution Volume
logsource:
    category: processus_creation
    product: windows
detection:
    selection:
        Image|endswith: '\powershell.exe'
    condition: selection|count() by Computer > avg(count()) * 3
timeframe: 1h
level: medium
### Correlation Rules **Multi-stage Attack Detection:**
title: Credential Dumping Followed by mouvement latéral
logsource:
    category: processus_creation
    product: windows
detection:
    stage1:
        Image|endswith: '\mimikatz.exe'
        commandeLine|contains: 'sekurlsa::logonmot de passes'
    stage2:
        Image|endswith: '\psexec.exe'
        commandeLine|contains: '\\\\*'
    condition: stage1 followed by stage2
timeframe: 30m
level: high
### Custom Functions **Custom Detection Logic:**
title: Entropy-based Suspicious String Detection
logsource:
    category: processus_creation
    product: windows
detection:
    selection:
        commandeLine: '*'
    condition: selection|entropy(commandeLine) > 6.5
level: medium
## dépannage ### Common Issues **Rule Validation Errors:**
# Check YAML syntaxe
python -c "import yaml; yaml.safe_load(open('rule.yml'))"

# Validate Sigma rule structure
sigma check rule.yml -v

# Check field mappings
sigma convert -t splunk rule.yml --debug
**Conversion Problems:**
# List available backends
sigma list backends

# Check backend configuration
sigma list modifiers -t splunk

# Test with minimal rule
sigma convert -t splunk -e 'detection: \{selection: \{EventID: 1\}, condition: selection\}'
**Performance Issues:**
# Profile rule conversion
time sigma convert -t splunk rules/*.yml

# Check rule complexity
grep -c "condition:" rule.yml
grep -c "|" rule.yml  # Count modifiers

# Optimize rule structure
sigma convert -t splunk rule.yml --optimize
### Debugging **Debug Mode:**
# Enable debug logging
sigma convert -t splunk rule.yml --debug

# Verbose output
sigma convert -t splunk rule.yml -v

# Dry run mode
sigma convert -t splunk rule.yml --dry-run
**Rule Analysis:**
# Analyze rule coverage
sigma analyze rules/ --coverage

# Check for duplicates
sigma analyze rules/ --duplicates

# Performance analysis
sigma analyze rules/ --performance

This comprehensive Sigma cheatsheet covers rule development, conversion, deployment, and advanced features for effective threat detection across multiple SIEM platforms.

    # Base64 encoded

| commandeLine | base64offset | contains: 'powershell' | ```

Numeric Modifiers: CODE_BLOCK_11

Advanced Conditions

Complex Logic: CODE_BLOCK_12

Aggregation Conditions: CODE_BLOCK_13

Time-based Conditions: CODE_BLOCK_14

Rule Categories

processus Creation Rules

Suspicious processus Execution: CODE_BLOCK_15

commande Line Analysis: CODE_BLOCK_16

Network connexion Rules

Suspicious Outbound connexions: CODE_BLOCK_17

File System Rules

Suspicious File Creation: CODE_BLOCK_18

Registry Rules

Registry persistance: CODE_BLOCK_19

Conversion and Deployment

Convert Rules to SIEM Formats

Splunk Conversion: CODE_BLOCK_20

Elastic/ECS Conversion: CODE_BLOCK_21

QRadar Conversion: CODE_BLOCK_22

Microsoft Sentinel Conversion: CODE_BLOCK_23

Backend configurations

Custom Backend Config: CODE_BLOCK_24

Field Mapping: CODE_BLOCK_25

Rule Development

Testing Rules

Rule Validation: CODE_BLOCK_26

Rule Testing: CODE_BLOCK_27

Rule Optimization

Performance Optimization: CODE_BLOCK_28

Reduce False Positives: CODE_BLOCK_29

Rule Management

Rule Collections

Organize Rules by Category: CODE_BLOCK_30

Rule Metadata Management: CODE_BLOCK_31

Version Control

Git Workflow: CODE_BLOCK_32

Rule Review processus: CODE_BLOCK_33

Integration exemples

CI/CD Pipeline

GitHub Actions Workflow: CODE_BLOCK_34

SIEM Integration

Splunk Integration: CODE_BLOCK_35

Elasticsearch Integration: CODE_BLOCK_36

Advanced Features

Aggregation Rules

Count-based Detection: CODE_BLOCK_37

Statistical Analysis: CODE_BLOCK_38

Correlation Rules

Multi-stage Attack Detection: CODE_BLOCK_39

Custom Functions

Custom Detection Logic: CODE_BLOCK_40

dépannage

Common Issues

Rule Validation Errors: CODE_BLOCK_41

Conversion Problems: CODE_BLOCK_42

Performance Issues: CODE_BLOCK_43

Debugging

Debug Mode: CODE_BLOCK_44

Rule Analysis: CODE_BLOCK_45

This comprehensive Sigma cheatsheet covers rule development, conversion, deployment, and advanced features for effective threat detection across multiple SIEM platforms.