Lab 7.2: Mecanismes de Persistence Windows
Objectifs d'Apprentissage
A la fin de ce laboratoire, vous serez capable de:
- Comprendre les mecanismes de persistence Windows
- Creer et supprimer des services de test
- Gerer les taches planifiees
- Detecter les persistances malveillantes
Duree Estimee
50 minutes
Prerequis
- Lab 7.1 complete
- VM Windows 10/11
- Droits administrateur
Contexte Professionnel
La persistence est une technique utilisee pour:
- Legitimement: Demarrer des services automatiquement
- Malicieusement: Maintenir l'acces apres un redemarrage
Comprendre ces mecanismes est essentiel pour la defense.
AVERTISSEMENT
Ce lab enseigne des techniques de persistence a des fins defensives.
- Executez uniquement sur des VMs de test
- Nettoyez toutes les creations a la fin du lab
Partie 1: Persistence via Services
Etape 1.1: Creer un service de test
# Creer un script de service
$scriptContent = @'
# Service de test - NE FAIT RIEN
# Ce script simule un service pour le lab
Write-Output "Service de test demarre" | Out-File C:\Temp\service_log.txt -Append
while ($true) {
Start-Sleep -Seconds 60
}
'@
# Sauvegarder le script
New-Item -Path "C:\Temp" -ItemType Directory -Force | Out-Null
$scriptContent | Out-File "C:\Temp\test_service.ps1" -Encoding UTF8
Write-Host "Script cree: C:\Temp\test_service.ps1" -ForegroundColor Green
Etape 1.2: Enregistrer le service
# Creer le service avec NSSM ou sc.exe
# Pour ce lab, nous utilisons sc.exe avec cmd.exe
# Methode 1: Service simple avec cmd.exe (pour demo)
sc.exe create "LabTestService" `
binPath= "cmd.exe /k echo Service de test" `
DisplayName= "Lab Test Service" `
start= manual
# Verifier
Get-Service "LabTestService"
sc.exe qc "LabTestService"
Etape 1.3: Modifier le service
# Changer le type de demarrage
sc.exe config "LabTestService" start= auto
# Ajouter une description
sc.exe description "LabTestService" "Service cree pour le lab 7.2"
# Verifier les changements
Get-Service "LabTestService" | Select-Object *
Etape 1.4: Detecter notre service
# Notre service devrait apparaitre comme suspect
Get-WmiObject Win32_Service | Where-Object {
$_.Name -eq "LabTestService"
} | Select-Object Name, DisplayName, PathName, StartMode, State
Question 1: Pourquoi ce service pourrait-il etre considere comme suspect?
Etape 1.5: Supprimer le service
# Arreter et supprimer
Stop-Service "LabTestService" -Force -ErrorAction SilentlyContinue
sc.exe delete "LabTestService"
# Verifier la suppression
Get-Service "LabTestService" -ErrorAction SilentlyContinue
Partie 2: Persistence via Taches Planifiees
Etape 2.1: Creer une tache simple
# Creer une tache qui s'execute au demarrage
$action = New-ScheduledTaskAction `
-Execute "cmd.exe" `
-Argument "/c echo Tache de test > C:\Temp\task_log.txt"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal `
-UserId "SYSTEM" `
-RunLevel Highest
Register-ScheduledTask `
-TaskName "LabTestTask" `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Description "Tache creee pour le lab 7.2"
Write-Host "Tache creee: LabTestTask" -ForegroundColor Green
Etape 2.2: Verifier la tache
# Voir la tache
Get-ScheduledTask -TaskName "LabTestTask"
# Details complets
Get-ScheduledTask -TaskName "LabTestTask" |
Select-Object TaskName, State, @{N='Trigger';E={$_.Triggers.AtStartup}},
@{N='Action';E={$_.Actions.Execute}}
# Informations d'execution
Get-ScheduledTaskInfo -TaskName "LabTestTask"
Etape 2.3: Creer une tache plus realiste
# Tache qui imite un service legitime (pour demo de detection)
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-WindowStyle Hidden -Command Start-Sleep 3600"
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask `
-TaskName "WindowsUpdateHelper" `
-Action $action `
-Trigger $trigger `
-Description "Mise a jour Windows (FAUX - LAB)"
Write-Host "Tache suspecte creee pour demo" -ForegroundColor Yellow
Etape 2.4: Executer la detection
# Script de detection des taches suspectes
$suspectTasks = @()
Get-ScheduledTask | Where-Object {
$_.TaskPath -notlike "\Microsoft\*"
} | ForEach-Object {
$task = $_
foreach ($action in $task.Actions) {
$isSuspect = $false
$reasons = @()
# PowerShell cache
if ($action.Arguments -match "-WindowStyle\s+Hidden") {
$isSuspect = $true
$reasons += "PowerShell cache"
}
# Commandes encodees
if ($action.Arguments -match "-[Ee]ncoded") {
$isSuspect = $true
$reasons += "Commande encodee"
}
# Nos taches de test
if ($task.TaskName -match "^Lab" -or $task.TaskName -eq "WindowsUpdateHelper") {
$isSuspect = $true
$reasons += "Tache de test/suspecte"
}
if ($isSuspect) {
$suspectTasks += [PSCustomObject]@{
TaskName = $task.TaskName
Execute = $action.Execute
Arguments = $action.Arguments
Reasons = ($reasons -join ", ")
}
}
}
}
Write-Host "`n=== TACHES SUSPECTES DETECTEES ===" -ForegroundColor Cyan
$suspectTasks | Format-Table -AutoSize
Question 2: Quelles taches ont ete detectees comme suspectes?
Etape 2.5: Supprimer les taches
# Supprimer nos taches de test
Unregister-ScheduledTask -TaskName "LabTestTask" -Confirm:$false
Unregister-ScheduledTask -TaskName "WindowsUpdateHelper" -Confirm:$false
Write-Host "Taches supprimees" -ForegroundColor Green
Partie 3: Persistence via Registre
Etape 3.1: Cles Run (auto-demarrage)
Les cles Run executent des programmes a la connexion:
# Voir les cles Run actuelles
Write-Host "=== HKCU Run ===" -ForegroundColor Cyan
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue
Write-Host "`n=== HKLM Run ===" -ForegroundColor Cyan
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue
Etape 3.2: Ajouter une entree de test
# Ajouter une entree Run (utilisateur courant)
Set-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestRun" `
-Value "cmd.exe /c echo Test > C:\Temp\run_test.txt"
Write-Host "Entree Run ajoutee" -ForegroundColor Green
# Verifier
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" |
Select-Object LabTestRun
Etape 3.3: Detecter les entrees suspectes
# Script de detection des Run keys suspects
$runKeys = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
)
Write-Host "=== ANALYSE DES CLES RUN ===" -ForegroundColor Cyan
foreach ($key in $runKeys) {
if (Test-Path $key) {
Write-Host "`n$key" -ForegroundColor Yellow
$props = Get-ItemProperty $key -ErrorAction SilentlyContinue
$props.PSObject.Properties | Where-Object {
$_.Name -notmatch "^PS"
} | ForEach-Object {
$value = $_.Value
# Detecter les suspects
$suspect = $false
if ($value -match "\\Temp\\" -or
$value -match "\\AppData\\Local\\" -or
$value -match "-[Ee]ncoded" -or
$_.Name -match "^Lab") {
$suspect = $true
}
if ($suspect) {
Write-Host " [SUSPECT] $($_.Name): $value" -ForegroundColor Red
} else {
Write-Host " [OK] $($_.Name): $value" -ForegroundColor Green
}
}
}
}
Etape 3.4: Supprimer l'entree de test
Remove-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestRun"
Write-Host "Entree Run supprimee" -ForegroundColor Green
Partie 4: Script de Detection Global
Etape 4.1: Scanner complet de persistence
# Script de detection de persistence complet
Write-Host @"
================================================================================
SCANNER DE PERSISTENCE WINDOWS
================================================================================
"@ -ForegroundColor Cyan
$findings = @()
# 1. Services suspects
Write-Host "`n[1/3] Analyse des services..." -ForegroundColor Yellow
Get-WmiObject Win32_Service | Where-Object {
$_.PathName -match "\\(Temp|AppData|Downloads)\\" -or
$_.Name -match "^(Lab|Test)"
} | ForEach-Object {
$findings += [PSCustomObject]@{
Type = "Service"
Name = $_.Name
Details = $_.PathName
Risk = "Moyen"
}
}
# 2. Taches planifiees suspectes
Write-Host "[2/3] Analyse des taches planifiees..." -ForegroundColor Yellow
Get-ScheduledTask | Where-Object {
$_.TaskPath -notlike "\Microsoft\*"
} | ForEach-Object {
$task = $_
$action = $task.Actions | Select-Object -First 1
if ($action.Arguments -match "-Hidden|-[Ee]ncoded" -or
$task.TaskName -match "^(Lab|Test|WindowsUpdate[A-Z])") {
$findings += [PSCustomObject]@{
Type = "ScheduledTask"
Name = $task.TaskName
Details = "$($action.Execute) $($action.Arguments)"
Risk = "Eleve"
}
}
}
# 3. Cles Run
Write-Host "[3/3] Analyse des cles Run..." -ForegroundColor Yellow
$runKeys = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
)
foreach ($key in $runKeys) {
if (Test-Path $key) {
$props = Get-ItemProperty $key -ErrorAction SilentlyContinue
$props.PSObject.Properties | Where-Object {
$_.Name -notmatch "^PS" -and
($_.Value -match "\\Temp\\" -or $_.Name -match "^Lab")
} | ForEach-Object {
$findings += [PSCustomObject]@{
Type = "RunKey"
Name = $_.Name
Details = $_.Value
Risk = "Eleve"
}
}
}
}
# Rapport
Write-Host "`n================================================================================`n" -ForegroundColor Cyan
if ($findings.Count -eq 0) {
Write-Host "[OK] Aucune persistence suspecte detectee" -ForegroundColor Green
} else {
Write-Host "[!] $($findings.Count) persistence(s) suspecte(s) detectee(s):" -ForegroundColor Red
$findings | Format-Table -AutoSize
}
Write-Host "================================================================================" -ForegroundColor Cyan
Partie 5: Nettoyage
Etape 5.1: Verification et nettoyage final
# Verifier qu'il ne reste rien
Write-Host "=== VERIFICATION NETTOYAGE ===" -ForegroundColor Cyan
# Services
$testService = Get-Service "LabTestService" -ErrorAction SilentlyContinue
if ($testService) {
Write-Host "Service LabTestService encore present - suppression..." -ForegroundColor Yellow
sc.exe delete "LabTestService"
}
# Taches
$testTasks = Get-ScheduledTask | Where-Object {$_.TaskName -match "^Lab|WindowsUpdateHelper"}
foreach ($task in $testTasks) {
Write-Host "Tache $($task.TaskName) encore presente - suppression..." -ForegroundColor Yellow
Unregister-ScheduledTask -TaskName $task.TaskName -Confirm:$false
}
# Run keys
$runKey = Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "LabTestRun" -ErrorAction SilentlyContinue
if ($runKey) {
Write-Host "Run key LabTestRun encore presente - suppression..." -ForegroundColor Yellow
Remove-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "LabTestRun"
}
# Fichiers
if (Test-Path "C:\Temp\test_service.ps1") {
Remove-Item "C:\Temp\test_service.ps1" -Force
}
Write-Host "`nNettoyage termine!" -ForegroundColor Green
Livrables
-
Reponses aux 2 questions
-
Captures d'ecran:
- Service cree
- Tache planifiee creee
- Resultat du scanner de persistence
-
Rapport (1-2 pages):
- Mecanismes de persistence testes
- Comment les detecter
- Recommandations de defense
Criteres d'Evaluation
| Critere | Points |
|---|---|
| Persistence via service | 25% |
| Persistence via taches | 30% |
| Persistence via registre | 20% |
| Script de detection | 25% |
Lab developpe dans le cadre du cours Systemes d'Exploitation - MODULE 7