Lab 8.2: AMSI et Detection PowerShell
Objectifs d'Apprentissage
A la fin de ce laboratoire, vous serez capable de:
- Comprendre le fonctionnement de AMSI (Antimalware Scan Interface)
- Identifier comment les scripts malveillants sont detectes
- Connaitre les techniques de contournement (a des fins defensives)
- Mettre en place une detection efficace
Duree Estimee
45 minutes
Prerequis
- VM Windows 10/11
- Windows Defender actif
- PowerShell 5.1+
- Droits administrateur
Contexte Professionnel
AMSI est une interface critique pour:
- La detection de scripts malveillants
- La protection contre les malwares fileless
- L'integration des antivirus avec PowerShell
- La securite des environnements d'entreprise
AVERTISSEMENT
Ce lab explique des concepts a des fins defensives.
- Les techniques de bypass sont presentees pour comprendre les menaces
- NE PAS utiliser ces techniques de maniere malveillante
- Executez uniquement sur des VMs de test isolees
Partie 1: Comprendre AMSI
Etape 1.1: Qu'est-ce que AMSI?
AMSI (Antimalware Scan Interface) est une interface Windows qui permet aux antivirus d'inspecter le contenu des scripts avant leur execution.
Flux d'execution:
Script PowerShell --> AMSI --> Antivirus --> Autoriser/Bloquer
Applications supportant AMSI:
- PowerShell
- Windows Script Host (wscript, cscript)
- JavaScript
- VBScript
- Office VBA macros
- .NET assemblies
Etape 1.2: Verifier que AMSI est actif
# AMSI est actif si Windows Defender est actif
Get-MpComputerStatus | Select-Object AMServiceEnabled, AntivirusEnabled, RealTimeProtectionEnabled
Etape 1.3: Tester AMSI
Windows Defender detecte la chaine de test AMSI standard:
# Cette commande DEVRAIT etre bloquee par AMSI
# Elle contient la chaine de test officielle
# Essayez ceci (sera bloque):
"AM" + "SI" + "Test"
Note: La simple mention de certains termes declenche AMSI.
Question 1: Le test AMSI a-t-il ete detecte?
Partie 2: Comment AMSI Detecte les Menaces
Etape 2.1: Detection par signature
AMSI scanne pour des patterns connus:
# Exemples de patterns detectes (ne pas executer):
# - "Invoke-Mimikatz"
# - "Invoke-Empire"
# - Certaines commandes encodees en Base64
# - Patterns de shellcode
Etape 2.2: Scripts encodes
Les attaquants utilisent souvent l'encodage Base64:
# Commande simple
$cmd = "whoami"
# Encodee en Base64
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cmd)
$encoded = [Convert]::ToBase64String($bytes)
Write-Host "Commande encodee: $encoded"
# Decoder
$decoded = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))
Write-Host "Decodee: $decoded"
AMSI analyse le contenu APRES decodage, donc l'encodage seul ne suffit pas.
Etape 2.3: Observer AMSI en action
# Ce script montre comment AMSI intercepte les commandes
# Execution avec logging
# Activer le logging PowerShell (necessite admin)
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1 -ErrorAction SilentlyContinue
# Verifier
Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -ErrorAction SilentlyContinue
Partie 3: Techniques de Bypass (Connaissance Defensive)
Etape 3.1: Pourquoi connaitre les bypass?
En tant que defenseur, vous devez connaitre les techniques des attaquants pour:
- Ameliorer la detection
- Tester vos defenses
- Comprendre les alertes de securite
- Former les equipes SOC
Etape 3.2: Categories de bypass
| Technique | Description | Detection |
|---|---|---|
| Memory Patching | Modifier AMSI en memoire | Event ID 4104, comportement suspect |
| Reflection | Utiliser .NET reflection | Script Block Logging |
| Obfuscation | Masquer le code | Analyse comportementale |
| COM Hijacking | Detourner l'interface COM | Monitoring registre |
Etape 3.3: Detection des tentatives de bypass
# Script de detection des tentatives de bypass AMSI
# Recherche dans les logs PowerShell
Write-Host "=== DETECTION BYPASS AMSI ===" -ForegroundColor Cyan
# Rechercher les termes suspects dans les logs
$suspectTerms = @(
"amsi",
"AmsiInitFailed",
"AmsiContext",
"amsiSession",
"SetValue.*amsi"
)
$events = Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -MaxEvents 100 -ErrorAction SilentlyContinue
$suspicious = @()
foreach ($event in $events) {
foreach ($term in $suspectTerms) {
if ($event.Message -match $term) {
$suspicious += [PSCustomObject]@{
Time = $event.TimeCreated
EventId = $event.Id
Match = $term
Message = $event.Message.Substring(0, [Math]::Min(200, $event.Message.Length))
}
}
}
}
if ($suspicious.Count -gt 0) {
Write-Host "`n[ALERTE] Activite suspecte detectee:" -ForegroundColor Red
$suspicious | Format-Table -AutoSize
} else {
Write-Host "`n[OK] Aucune tentative de bypass detectee" -ForegroundColor Green
}
Question 2: Des tentatives de bypass ont-elles ete detectees?
Partie 4: Renforcer la Protection
Etape 4.1: Activer le Script Block Logging
# Configurer le logging complet (necessite admin)
# Creer les cles si necessaires
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell" -Force -ErrorAction SilentlyContinue | Out-Null
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Force -ErrorAction SilentlyContinue | Out-Null
# Activer le logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" `
-Name "EnableScriptBlockLogging" -Value 1 -Type DWord
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" `
-Name "EnableScriptBlockInvocationLogging" -Value 1 -Type DWord
Write-Host "Script Block Logging active" -ForegroundColor Green
Etape 4.2: Activer le Module Logging
# Activer le module logging
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Force -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" `
-Name "EnableModuleLogging" -Value 1 -Type DWord
# Logger tous les modules
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" -Force -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" `
-Name "*" -Value "*" -Type String
Write-Host "Module Logging active" -ForegroundColor Green
Etape 4.3: Configurer Constrained Language Mode
# Verifier le mode de langage actuel
$ExecutionContext.SessionState.LanguageMode
# Pour forcer le mode contraint (via GPO ou):
# [Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine')
# Necessite redemarrage
# Note: Le mode contraint limite les fonctionnalites de PowerShell
# a utiliser avec precaution en production
Etape 4.4: Verifier la configuration
# Script de verification de la configuration de securite PowerShell
Write-Host "=== CONFIGURATION SECURITE POWERSHELL ===" -ForegroundColor Cyan
# AMSI
Write-Host "`n[AMSI]" -ForegroundColor Yellow
$defender = Get-MpComputerStatus -ErrorAction SilentlyContinue
if ($defender) {
Write-Host " AMSI Service: $($defender.AMServiceEnabled)"
Write-Host " Real-Time Protection: $($defender.RealTimeProtectionEnabled)"
}
# Language Mode
Write-Host "`n[Language Mode]" -ForegroundColor Yellow
Write-Host " Mode actuel: $($ExecutionContext.SessionState.LanguageMode)"
# Execution Policy
Write-Host "`n[Execution Policy]" -ForegroundColor Yellow
Get-ExecutionPolicy -List | Format-Table
# Script Block Logging
Write-Host "[Script Block Logging]" -ForegroundColor Yellow
$sbl = Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -ErrorAction SilentlyContinue
if ($sbl.EnableScriptBlockLogging -eq 1) {
Write-Host " Status: Active" -ForegroundColor Green
} else {
Write-Host " Status: Inactif" -ForegroundColor Red
}
# Module Logging
Write-Host "`n[Module Logging]" -ForegroundColor Yellow
$ml = Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -ErrorAction SilentlyContinue
if ($ml.EnableModuleLogging -eq 1) {
Write-Host " Status: Actif" -ForegroundColor Green
} else {
Write-Host " Status: Inactif" -ForegroundColor Red
}
Partie 5: Monitoring et Alertes
Etape 5.1: Events cles a surveiller
| Event ID | Log | Description |
|---|---|---|
| 4103 | PowerShell/Operational | Module logging |
| 4104 | PowerShell/Operational | Script block logging |
| 1116 | Microsoft-Windows-Windows Defender | Malware detecte |
| 1117 | Microsoft-Windows-Windows Defender | Action sur malware |
Etape 5.2: Script de monitoring
# Monitoring des evenements PowerShell suspects
Write-Host "=== MONITORING POWERSHELL ===" -ForegroundColor Cyan
$suspectKeywords = @(
"bypass",
"encoded",
"downloadstring",
"invoke-expression",
"iex",
"reflection",
"assembly",
"shellcode",
"mimikatz"
)
# Script Block Logs (4104)
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-PowerShell/Operational'
ID = 4104
} -MaxEvents 50 -ErrorAction SilentlyContinue
Write-Host "`nAnalyse des 50 derniers Script Block Logs..." -ForegroundColor Yellow
$alerts = @()
foreach ($event in $events) {
foreach ($keyword in $suspectKeywords) {
if ($event.Message -match $keyword) {
$alerts += [PSCustomObject]@{
Time = $event.TimeCreated
Keyword = $keyword
Preview = $event.Message.Substring(0, [Math]::Min(100, $event.Message.Length))
}
break
}
}
}
if ($alerts.Count -gt 0) {
Write-Host "`n[ALERTES] Contenu suspect detecte:" -ForegroundColor Red
$alerts | Format-Table -AutoSize
} else {
Write-Host "`n[OK] Aucune activite suspecte detectee" -ForegroundColor Green
}
Livrables
-
Reponses aux 2 questions
-
Captures d'ecran:
- Test AMSI (detection)
- Configuration de securite
- Script de monitoring execute
-
Rapport (1-2 pages):
- Explication du fonctionnement d'AMSI
- Importance du logging PowerShell
- Recommandations pour votre environnement
Criteres d'Evaluation
| Critere | Points |
|---|---|
| Comprehension AMSI | 25% |
| Configuration logging | 30% |
| Script de detection | 25% |
| Rapport et analyse | 20% |
Ressources
Lab developpe dans le cadre du cours Systemes d'Exploitation - MODULE 8