[CmdletBinding()] param( [string]$ServerUrl = "", [string]$Pin = "" ) $ErrorActionPreference = "Stop" [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) Write-Host "============================================================" -ForegroundColor Cyan Write-Host " AI REMOTE REPAIR AGENT (Phien ho tro ky thuat minh bach) " -ForegroundColor Cyan Write-Host "============================================================" -ForegroundColor Cyan Write-Host " * Khong tu chay ngam, khong cai dat vao Windows Startup." -ForegroundColor Gray Write-Host " * Dong cua so nay bat cu luc nao de ngat ket noi ngay." -ForegroundColor Yellow Write-Host "" if ([string]::IsNullOrWhiteSpace($ServerUrl)) { $ServerUrl = Read-Host "Nhap dia chi Web Server (vi du https://xxx.trycloudflare.com hoac http://127.0.0.1:8787)" } $ServerUrl = $ServerUrl.Trim().TrimEnd("/") if ([string]::IsNullOrWhiteSpace($Pin)) { $Pin = Read-Host "Nhap ma ghep noi 6 so tu Web Dashboard" } $Pin = $Pin.Trim() function Invoke-ApiJson { param( [string]$Uri, [hashtable]$Body, [hashtable]$Headers = @{} ) $json = ($Body | ConvertTo-Json -Depth 6 -Compress) $bytes = [System.Text.Encoding]::UTF8.GetBytes($json) return Invoke-RestMethod -Uri $Uri -Method Post -Body $bytes -ContentType "application/json; charset=utf-8" -Headers $Headers -TimeoutSec 30 } function Capture-PrimaryScreenBase64 { Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height) $g = [System.Drawing.Graphics]::FromImage($bmp) try { $g.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size) $ms = New-Object System.IO.MemoryStream try { $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) return [Convert]::ToBase64String($ms.ToArray()), $bounds.Width, $bounds.Height } finally { $ms.Dispose() } } finally { $g.Dispose() $bmp.Dispose() } } function Run-ExternalProcess { param( [string]$FileName, [string]$Arguments, [int]$TimeoutMs = 120000 ) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $FileName $psi.Arguments = $Arguments $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8 $psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8 $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi [void]$proc.Start() $stdoutTask = $proc.StandardOutput.ReadToEndAsync() $stderrTask = $proc.StandardError.ReadToEndAsync() if (-not $proc.WaitForExit($TimeoutMs)) { try { $proc.Kill() } catch {} return @{ ok = $false; exit_code = -1; output = "Qua thoi gian cho (120 giay). Tien trinh da bi dung." } } $proc.WaitForExit() $out = $stdoutTask.Result $err = $stderrTask.Result $combined = ($out + "`n" + $err).Trim() if ([string]::IsNullOrEmpty($combined)) { $combined = "(Hoan tat, khong co output)" } return @{ ok = ($proc.ExitCode -eq 0); exit_code = $proc.ExitCode; output = $combined } } $osCaption = (Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue).Caption $regBody = @{ pin = $Pin hostname = $env:COMPUTERNAME username = $env:USERNAME os_info = if ($osCaption) { $osCaption } else { [System.Environment]::OSVersion.VersionString } } Write-Host "[+] Dang ket noi toi $ServerUrl ..." -ForegroundColor Cyan try { $reg = Invoke-ApiJson -Uri "$ServerUrl/api/agent/register" -Body $regBody } catch { Write-Host "[!] Dang ky that bai: $($_.Exception.Message)" -ForegroundColor Red Read-Host "Nhan Enter de dong" exit 1 } $agentId = $reg.agent_id $agentToken = $reg.agent_token $authHeaders = @{ "X-Agent-Token" = $agentToken } Write-Host "[OK] Da ket noi! Ten may: $($env:COMPUTERNAME) | Agent ID: $agentId" -ForegroundColor Green Write-Host "[*] Dang cho lenh tu Web Dashboard... (Dong cua so nay de ngat ket noi)" -ForegroundColor Gray $failCount = 0 while ($true) { try { $poll = Invoke-ApiJson -Uri "$ServerUrl/api/agent/poll" -Body @{ agent_id = $agentId } -Headers $authHeaders $failCount = 0 $job = $poll.job if ($null -ne $job) { $jobId = $job.id $jType = $job.type Write-Host "" Write-Host "[LENH MOI #$jobId] Loai: $jType" -ForegroundColor Yellow if ($jType -eq "disconnect") { Write-Host "[!] Web Dashboard da ngat ket noi phien nay." -ForegroundColor Yellow break } elseif ($jType -eq "screenshot") { try { $b64, $w, $h = Capture-PrimaryScreenBase64 $msg = "Da chup man hinh (${w}x${h}) luc $(Get-Date -Format 'HH:mm:ss')" Write-Host " -> $msg" -ForegroundColor Green [void](Invoke-ApiJson -Uri "$ServerUrl/api/agent/result" -Body @{ job_id = $jobId ok = $true exit_code = 0 output = $msg screenshot_b64 = $b64 } -Headers $authHeaders) } catch { [void](Invoke-ApiJson -Uri "$ServerUrl/api/agent/result" -Body @{ job_id = $jobId ok = $false exit_code = 1 output = "Loi chup man hinh: $($_.Exception.Message)" } -Headers $authHeaders) } } elseif ($jType -eq "powershell") { $script = [string]$job.script Write-Host "--- Noi dung PowerShell ---" -ForegroundColor DarkGray Write-Host $script -ForegroundColor Gray Write-Host "---------------------------" -ForegroundColor DarkGray $wrapped = "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(`$false)`n" + $script $enc = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($wrapped)) $res = Run-ExternalProcess -FileName "powershell.exe" -Arguments "-NoProfile -ExecutionPolicy Bypass -EncodedCommand $enc" Write-Host " -> ExitCode: $($res.exit_code)" -ForegroundColor Cyan [void](Invoke-ApiJson -Uri "$ServerUrl/api/agent/result" -Body @{ job_id = $jobId ok = $res.ok exit_code = $res.exit_code output = $res.output } -Headers $authHeaders) } elseif ($jType -eq "cmd") { $script = [string]$job.script Write-Host "--- Noi dung CMD ---" -ForegroundColor DarkGray Write-Host $script -ForegroundColor Gray Write-Host "--------------------" -ForegroundColor DarkGray $tmpBat = Join-Path $env:TEMP ("air_job_" + $jobId + ".bat") $batText = "@echo off`r`nchcp 65001 >nul`r`n" + $script + "`r`n" [System.IO.File]::WriteAllText($tmpBat, $batText, [System.Text.UTF8Encoding]::new($false)) try { $res = Run-ExternalProcess -FileName "cmd.exe" -Arguments "/c `"$tmpBat`"" } finally { Remove-Item -LiteralPath $tmpBat -Force -ErrorAction SilentlyContinue } Write-Host " -> ExitCode: $($res.exit_code)" -ForegroundColor Cyan [void](Invoke-ApiJson -Uri "$ServerUrl/api/agent/result" -Body @{ job_id = $jobId ok = $res.ok exit_code = $res.exit_code output = $res.output } -Headers $authHeaders) } } Start-Sleep -Seconds 2 } catch { $statusCode = $null if ($_.Exception.Response) { try { $statusCode = [int]$_.Exception.Response.StatusCode } catch {} } if ($statusCode -eq 401 -or $statusCode -eq 403) { Write-Host "[!] Phien ket noi da bi thu hoi hoac het han (HTTP $statusCode)." -ForegroundColor Red break } $failCount++ Write-Host "[!] Loi ket noi tam thoi ($failCount/15): $($_.Exception.Message)" -ForegroundColor DarkYellow if ($failCount -ge 15) { Write-Host "[!] Mat ket noi qua lau. Tu dong dong Agent." -ForegroundColor Red break } Start-Sleep -Seconds 4 } }