# remote-bridge agent - runs inline in this window. Nothing of the bridge is installed. # It is alive only while this window stays open; close it (or Ctrl+C) to disconnect. # On an admin account it reopens itself elevated (silent, or one UAC click) so RustDesk # can run as a service that reaches the lock screen; that install is removed again when # this window closes, or by a SYSTEM watchdog task within a minute / at the next boot. # irm https://remote.claude.filipkin.com/ | iex # Name it explicitly (default is the computer name): # iex (irm "https://remote.claude.filipkin.com/?name=fim-av") $ErrorActionPreference = 'Continue' $Server = 'wss://remote.claude.filipkin.com/agent' $Token = '803553fa3116f17de887af3ade8856a7' $Name = $env:COMPUTERNAME # --- Elevation: an admin account that is not elevated (UAC) reopens this agent in an # elevated window and this copy ends. Declined or not an admin: carry on here, and # RustDesk runs portable (no lock screen, no UAC prompts). $script:Admin = $false try { $script:Admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { } if (-not $script:Admin) { $inAdmins = $false try { $inAdmins = [bool]((whoami /groups) -match 'S-1-5-32-544') } catch { } if ($inAdmins) { $relaunch = "iex (irm 'https://remote.claude.filipkin.com/?name=" + [Uri]::EscapeDataString($Name) + "')" $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($relaunch)) $elevated = $null try { $elevated = Start-Process powershell -Verb RunAs -PassThru -ArgumentList '-NoProfile','-EncodedCommand',$enc -ErrorAction Stop } catch { } if ($null -ne $elevated) { Write-Host 'remote-bridge: moved to the administrator window.'; return } Write-Host 'remote-bridge: not elevated; portable RustDesk.' } } # --- RustDesk relay settings (baked in; nas supplies the per-session password) -- $RdExeUrl = 'https://remote.claude.filipkin.com/rustdesk.exe' $RdSha = '8555777215510d83d2d61c9dc984e4fcc838bd7e79f9d18a42585431f5e8bb47' $RdServer = 'rustdesk.filipkin.com' $RdKey = 'giJfklxXkWYaLBxeC+VTugM++Mx1NfL+jbYnRDOyg7Y=' # --- nano-style TUI state ------------------------------------------------- $script:Name = $Name $script:Inst = [guid]::NewGuid().ToString('N') # this agent process; the server resends only to the same one $script:SrvHost = ([Uri]$Server).Host $script:State = 'connecting' $script:Start = Get-Date $script:Count = 0 $script:LastCode = '-' $script:Lines = New-Object System.Collections.Generic.List[string] $script:LastW = -1 $script:LastH = -1 # Box-drawing glyphs by code point so this script's SOURCE stays pure ASCII # (no dependence on how the .ps1 text was transported/decoded). $script:TL=[char]0x250C; $script:TR=[char]0x2510; $script:BL=[char]0x2514; $script:BR=[char]0x2518 $script:HZ=[char]0x2500; $script:VT=[char]0x2502; $script:LT=[char]0x251C; $script:RT=[char]0x2524 $script:Arrow=[char]0x25B8 $script:Esc = [char]27 # ANSI SGR escapes are built from this so the source stays ASCII $script:Scroll = 0 # inner-pane scrollback offset (0 = follow the bottom) $script:Ansi = $false # VT/ANSI colour available $script:Keys = $false # non-blocking key reads available # --- RustDesk session state (kill-on-close Job Object holds the process) --- $script:RdProc = $null $script:RdId = '' $script:RdPassword = '' $script:RdJobHandle = [IntPtr]::Zero $script:RdCreatedConfig = $false # A real cursor-addressed TUI needs an interactive console. If output is # redirected, the host has no window, or it is too small, fall back to plain # line-by-line printing and never touch the cursor. $script:Tui = $true try { if ([Console]::IsOutputRedirected) { $script:Tui = $false } elseif ([Console]::WindowHeight -lt 8 -or [Console]::WindowWidth -lt 24) { $script:Tui = $false } } catch { $script:Tui = $false } # In a TUI, turn on VT processing so ANSI colour works in plain conhost / Windows # PowerShell 5.1 (not just Windows Terminal), and allow non-blocking key reads # for scrollback. Both are optional: if either fails we render without them. if ($script:Tui) { $script:Keys = $true # Take Ctrl+C over as normal input so Poll-Keys can detect it and stop cleanly. # A blocking .NET wait does not deliver the CancelKeyPress event reliably, which # is why Ctrl+C did nothing before. try { [Console]::TreatControlCAsInput = $true } catch { } try { if (-not ('RBVt.Native' -as [type])) { Add-Type -Namespace RBVt -Name Native -MemberDefinition ' [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern System.IntPtr GetStdHandle(int n); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetConsoleMode(System.IntPtr h, out int m); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern bool SetConsoleMode(System.IntPtr h, int m); ' } $hOut = [RBVt.Native]::GetStdHandle(-11) $mode = 0 if ([RBVt.Native]::GetConsoleMode($hOut, [ref]$mode)) { if ($mode -band 0x0004) { $script:Ansi = $true } elseif ([RBVt.Native]::SetConsoleMode($hOut, ($mode -bor 0x0004))) { $script:Ansi = $true } } } catch { $script:Ansi = $false } } function Push-Line([string]$s) { if ($null -eq $s) { $s = '' } $script:Lines.Add(($s -replace '\t',' ')) if ($script:Lines.Count -gt 1000) { $script:Lines.RemoveRange(0, ($script:Lines.Count - 1000)) } # If the user has scrolled up, keep their view anchored as new lines arrive. # The offset is measured from the bottom, so grow it by one per appended line; # at offset 0 (following the bottom) the view stays on the newest output. if ($script:Scroll -gt 0) { $script:Scroll = $script:Scroll + 1 } } function Push-Text([string]$t) { if ($null -eq $t) { return } foreach ($ln in ($t -split '\r?\n')) { Push-Line $ln } } function Show-Frame { if (-not $script:Tui) { return } try { $w = [Console]::WindowWidth - 1 # never write the final column (avoids wrap-scroll) $h = [Console]::WindowHeight if ($w -lt 16 -or $h -lt 8) { return } if ($w -ne $script:LastW -or $h -ne $script:LastH) { [Console]::Clear(); $script:LastW = $w; $script:LastH = $h } $inW = $w - 4 $rows = $h - 4 $bar = [string]$script:HZ * ($w - 2) # ANSI SGR: black-on-green for the frame, bold yellow for command lines. $reset = ''; $gbar = ''; $cmdSgr = '' if ($script:Ansi) { $reset = [string]$script:Esc + '[0m' $gbar = [string]$script:Esc + '[30;42m' $cmdSgr = [string]$script:Esc + '[1;33m' } # Full-width green frame bar with an optional embedded label. $mkbar = { param($left, $right, $label) $arr = $bar.ToCharArray() if ($label) { $lab = '[ ' + $label + ' ]' if ($lab.Length -gt ($arr.Length - 2)) { $lab = $lab.Substring(0, ($arr.Length - 2)) } for ($i = 0; $i -lt $lab.Length; $i++) { $arr[$i + 1] = $lab[$i] } } $s = [string]$left + (-join $arr) + [string]$right if ($script:Ansi) { return ($gbar + $s + $reset) } else { return $s } } # Full-width green status bar. $mkstatus = { param($text) if ($null -eq $text) { $text = '' } if ($text.Length -gt $inW) { $text = $text.Substring(0, $inW) } $s = [string]$script:VT + ' ' + $text.PadRight($inW) + ' ' + [string]$script:VT if ($script:Ansi) { return ($gbar + $s + $reset) } else { return $s } } # Content row: green border glyphs, default inner background so output stays # readable; command (prompt) lines render bold yellow. $mkrow = { param($text) if ($null -eq $text) { $text = '' } if ($text.Length -gt $inW) { $text = $text.Substring(0, $inW) } $body = $text.PadRight($inW) if ($script:Ansi) { if ($text.StartsWith([string]$script:Arrow)) { $body = $cmdSgr + $body + $reset } $edge = $gbar + [string]$script:VT + $reset return ($edge + ' ' + $body + ' ' + $edge) } return ([string]$script:VT + ' ' + $body + ' ' + [string]$script:VT) } $up = (Get-Date) - $script:Start $ups = '{0:00}:{1:00}:{2:00}' -f [int]$up.TotalHours, $up.Minutes, $up.Seconds $status = 'server ' + $script:SrvHost + ' ' + $script:State + ' up ' + $ups + ' cmds ' + $script:Count + ' running ' + $script:Jobs.Count + ' last ' + $script:LastCode # Scrollback: offset 0 shows the tail; a positive offset walks upward. $total = $script:Lines.Count $maxStart = [Math]::Max(0, $total - $rows) if ($script:Scroll -gt $maxStart) { $script:Scroll = $maxStart } if ($script:Scroll -lt 0) { $script:Scroll = 0 } $startIdx = $maxStart - $script:Scroll $botLabel = 'close window to disconnect' if ($script:Scroll -gt 0) { $firstShown = $startIdx + 1 $lastShown = [Math]::Min($total, $startIdx + $rows) $botLabel = 'scrollback ' + $firstShown + '-' + $lastShown + ' / ' + $total + ' End = bottom' } $screen = New-Object System.Collections.Generic.List[string] $screen.Add((& $mkbar $script:TL $script:TR ('remote-bridge : ' + $script:Name))) $screen.Add((& $mkstatus $status)) $screen.Add((& $mkbar $script:LT $script:RT $null)) for ($i = 0; $i -lt $rows; $i++) { $idx = $startIdx + $i if ($idx -ge 0 -and $idx -lt $total) { $screen.Add((& $mkrow $script:Lines[$idx])) } else { $screen.Add((& $mkrow '')) } } $screen.Add((& $mkbar $script:BL $script:BR $botLabel)) for ($i = 0; $i -lt $screen.Count -and $i -lt $h; $i++) { [Console]::SetCursorPosition(0, $i) [Console]::Write($screen[$i]) } } catch { $script:Tui = $false } } # Show a command + its output. The TUI copy is display-only; the full $out is # still what gets sent back to the server, untouched. function Report-Command([string]$cmd, [string]$out, $code) { if ($script:Tui) { if ($script:Lines.Count -gt 0) { Push-Line '' } Push-Line ([string]$script:Arrow + ' ' + ($cmd -replace '\r?\n', ' ')) Push-Text $out Show-Frame } else { Write-Host '' Write-Host ('> ' + ($cmd -replace '\r?\n', ' ')) -ForegroundColor Cyan if ($out) { Write-Host $out.TrimEnd() } Write-Host ('[exit ' + $code + ']') -ForegroundColor DarkGray } } function Set-State([string]$s) { $script:State = $s if ($script:Tui) { Show-Frame } else { Write-Host ('[' + $s + ']') -ForegroundColor DarkGray } } # Drain any queued keys without blocking and adjust the scrollback offset. # Only ever called from the idle tick, so it never delays command handling. # Ctrl+C is not queued here (TreatControlCAsInput stays false), so it still # fires the cancel handler and stops the agent instead of scrolling. function Poll-Keys { if (-not $script:Tui -or -not $script:Keys) { return } try { $page = [Console]::WindowHeight - 4 if ($page -lt 1) { $page = 1 } while ([Console]::KeyAvailable) { $k = [Console]::ReadKey($true) # Ctrl+C arrives here as input (TreatControlCAsInput). Stop the agent. if ($k.KeyChar -eq [char]3 -or ($k.Key -eq [ConsoleKey]::C -and ($k.Modifiers -band [ConsoleModifiers]::Control))) { $script:Stop = $true try { $script:Cts.Cancel() } catch { } return } switch ($k.Key) { 'PageUp' { $script:Scroll = $script:Scroll + $page } 'PageDown' { $script:Scroll = $script:Scroll - $page } 'UpArrow' { $script:Scroll = $script:Scroll + 1 } 'DownArrow' { $script:Scroll = $script:Scroll - 1 } 'Home' { $script:Scroll = [Math]::Max(0, $script:Lines.Count - $page) } 'End' { $script:Scroll = 0 } } } $max = [Math]::Max(0, $script:Lines.Count - $page) if ($script:Scroll -gt $max) { $script:Scroll = $max } if ($script:Scroll -lt 0) { $script:Scroll = 0 } } catch { $script:Keys = $false } } # Ctrl+C: flag a stop and cancel the token so a blocked ReceiveAsync/ConnectAsync # unblocks at once. PowerShell's own handler keeps the process alive and turns # Ctrl+C into a pipeline stop, so the try/finally below always runs its cleanup # even if this flag does not propagate across the handler thread. $script:Stop = $false $script:Cts = New-Object System.Threading.CancellationTokenSource $onCancel = { param($s, $e) $script:Stop = $true try { $script:Cts.Cancel() } catch { } } try { [Console]::add_CancelKeyPress($onCancel) } catch { } # --- Commands ---------------------------------------------------------------- # Every command runs in its OWN child powershell.exe, never in this process: # * a hung command cannot block this loop: the socket, cancel, file transfer and # other commands keep working, and several commands can run at once; # * it has a hard timeout, and a timeout or cancel kills its whole process tree # (it is held in a Job Object); # * its stdin is closed and it runs -NonInteractive: Read-Host, Get-Credential, # confirm prompts and anything reading stdin fail at once; ssh/scp/sftp are # forced to BatchMode so a missing key fails instead of prompting; # * it has its own hidden console, so a program it starts never writes into this # window; # * the script reaches it base64 on its stdin, so no quoting can break it; # * its output is capped (OutCap) so a runaway command cannot eat the agent. # Each command starts fresh: no variables or current directory carry over. # A program a command launched and left running (an app) keeps running after the # command ends; only a timeout or cancel kills it. If this agent dies, commands # still running die with it (KILL_ON_JOB_CLOSE on their job). $script:RunCs = @' using System; using System.IO; using System.Text; using System.Threading; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; public class RBRunV2 { [StructLayout(LayoutKind.Sequential)] struct SA { public int nLength; public IntPtr sd; public int inherit; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct SI { public int cb; public string r1; public string desktop; public string title; public int x, y, xs, ys, xc, yc, fill, flags; public short show, r2; public IntPtr r3, hIn, hOut, hErr; } [StructLayout(LayoutKind.Sequential)] struct SIX { public SI si; public IntPtr attrs; } [StructLayout(LayoutKind.Sequential)] struct PI { public IntPtr hProcess, hThread; public int pid, tid; } [StructLayout(LayoutKind.Sequential)] struct BASIC { public long a; public long b; public uint LimitFlags; public UIntPtr c; public UIntPtr d; public uint e; public UIntPtr f; public uint g; public uint h; } [StructLayout(LayoutKind.Sequential)] struct IOC { public ulong a; public ulong b; public ulong c; public ulong d; public ulong e; public ulong f; } [StructLayout(LayoutKind.Sequential)] struct EXT { public BASIC Basic; public IOC Io; public UIntPtr a; public UIntPtr b; public UIntPtr c; public UIntPtr d; } [DllImport("kernel32.dll", SetLastError=true)] static extern bool CreatePipe(out IntPtr r, out IntPtr w, ref SA sa, int size); [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetHandleInformation(IntPtr h, int mask, int flags); [DllImport("kernel32.dll", SetLastError=true)] static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size); [DllImport("kernel32.dll", SetLastError=true)] static extern bool UpdateProcThreadAttribute(IntPtr list, int flags, IntPtr attr, IntPtr value, IntPtr size, IntPtr prev, IntPtr retSize); [DllImport("kernel32.dll")] static extern void DeleteProcThreadAttributeList(IntPtr list); [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool CreateProcessW(string app, StringBuilder cmd, IntPtr pa, IntPtr ta, bool inherit, int flags, IntPtr env, string cwd, ref SIX si, out PI pi); [DllImport("kernel32.dll")] static extern int ResumeThread(IntPtr h); [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); [DllImport("kernel32.dll")] static extern int WaitForSingleObject(IntPtr h, int ms); [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr h, out int code); [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string name); [DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr job, int cls, IntPtr info, uint len); [DllImport("kernel32.dll")] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr proc); [DllImport("kernel32.dll")] static extern bool TerminateJobObject(IntPtr job, uint code); [DllImport("kernel32.dll")] static extern bool TerminateProcess(IntPtr h, uint code); IntPtr hProc = IntPtr.Zero, job = IntPtr.Zero; readonly MemoryStream buf = new MemoryStream(); readonly object gate = new object(); long dropped; int cap; int readers; public int Pid; public bool InJob, Exited, Killed; public int ExitCode = -1; public DateTime ExitedAt; static void Limits(IntPtr job, uint flags) { EXT ext = new EXT(); ext.Basic.LimitFlags = flags; int len = Marshal.SizeOf(typeof(EXT)); IntPtr p = Marshal.AllocHGlobal(len); try { Marshal.StructureToPtr(ext, p, false); SetInformationJobObject(job, 9, p, (uint)len); } finally { Marshal.FreeHGlobal(p); } } // Start cmdline suspended, put it in a fresh kill-on-close job, then let it run. // Only its own three pipe ends are inherited (PROC_THREAD_ATTRIBUTE_HANDLE_LIST), // never this agent's socket or console handles. public static RBRunV2 Start(string cmdline, string cwd, byte[] input, int cap, int extraFlags) { SA sa = new SA(); sa.nLength = Marshal.SizeOf(typeof(SA)); sa.inherit = 1; IntPtr inR, inW, outR, outW, errR, errW; if (!CreatePipe(out inR, out inW, ref sa, 0)) throw new System.ComponentModel.Win32Exception(); CreatePipe(out outR, out outW, ref sa, 0); CreatePipe(out errR, out errW, ref sa, 0); SetHandleInformation(inW, 1, 0); SetHandleInformation(outR, 1, 0); SetHandleInformation(errR, 1, 0); IntPtr size = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size); IntPtr list = Marshal.AllocHGlobal(size); IntPtr handles = Marshal.AllocHGlobal(IntPtr.Size * 3); PI pi; bool ok; int err; try { if (!InitializeProcThreadAttributeList(list, 1, 0, ref size)) throw new System.ComponentModel.Win32Exception(); Marshal.WriteIntPtr(handles, 0, inR); Marshal.WriteIntPtr(handles, IntPtr.Size, outW); Marshal.WriteIntPtr(handles, IntPtr.Size * 2, errW); if (!UpdateProcThreadAttribute(list, 0, (IntPtr)0x20002, handles, (IntPtr)(IntPtr.Size * 3), IntPtr.Zero, IntPtr.Zero)) throw new System.ComponentModel.Win32Exception(); SIX six = new SIX(); six.si.cb = Marshal.SizeOf(typeof(SIX)); six.attrs = list; six.si.flags = 0x100 | 0x1; six.si.show = 0; // STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW, SW_HIDE six.si.hIn = inR; six.si.hOut = outW; six.si.hErr = errW; int flags = 0x4 | 0x80000 | extraFlags; // CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT ok = CreateProcessW(null, new StringBuilder(cmdline), IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, cwd, ref six, out pi); err = Marshal.GetLastWin32Error(); DeleteProcThreadAttributeList(list); } finally { Marshal.FreeHGlobal(list); Marshal.FreeHGlobal(handles); CloseHandle(inR); CloseHandle(outW); CloseHandle(errW); } if (!ok) { CloseHandle(inW); CloseHandle(outR); CloseHandle(errR); throw new System.ComponentModel.Win32Exception(err); } RBRunV2 r = new RBRunV2(); r.cap = cap; r.hProc = pi.hProcess; r.Pid = pi.pid; r.job = CreateJobObject(IntPtr.Zero, null); if (r.job != IntPtr.Zero) { Limits(r.job, 0x2000 | 0x800); // KILL_ON_JOB_CLOSE | BREAKAWAY_OK r.InJob = AssignProcessToJobObject(r.job, pi.hProcess); } ResumeThread(pi.hThread); CloseHandle(pi.hThread); r.Read(outR); r.Read(errR); r.Write(inW, input); return r; } // Reader threads keep draining until EOF even after the output is reported, so // a leftover program that inherited the pipe never blocks on a full pipe. void Read(IntPtr h) { Interlocked.Increment(ref readers); FileStream fs = new FileStream(new SafeFileHandle(h, true), FileAccess.Read, 4096, false); Thread t = new Thread(delegate() { byte[] b = new byte[8192]; try { int n; while ((n = fs.Read(b, 0, b.Length)) > 0) { lock (gate) { int room = cap - (int)buf.Length; int k = room > 0 ? Math.Min(room, n) : 0; if (k > 0) buf.Write(b, 0, k); dropped += n - k; } } } catch { } finally { try { fs.Dispose(); } catch { } Interlocked.Decrement(ref readers); } }); t.IsBackground = true; t.Start(); } void Write(IntPtr h, byte[] data) { FileStream fs = new FileStream(new SafeFileHandle(h, true), FileAccess.Write, 4096, false); Thread t = new Thread(delegate() { try { if (data != null && data.Length > 0) fs.Write(data, 0, data.Length); } catch { } finally { try { fs.Dispose(); } catch { } } }); t.IsBackground = true; t.Start(); } // True once the process has exited and its output is in (or graceMs passed since). public bool Poll(int graceMs) { if (!Exited && hProc != IntPtr.Zero && WaitForSingleObject(hProc, 0) == 0) { int c; GetExitCodeProcess(hProc, out c); ExitCode = c; Exited = true; ExitedAt = DateTime.UtcNow; } if (!Exited) return false; if (Thread.VolatileRead(ref readers) == 0) return true; return (DateTime.UtcNow - ExitedAt).TotalMilliseconds >= graceMs; } public long Bytes { get { lock (gate) { return buf.Length + dropped; } } } public void Kill() { Killed = true; if (InJob && TerminateJobObject(job, 1)) return; if (hProc != IntPtr.Zero) TerminateProcess(hProc, 1); } public string Output() { lock (gate) { string s = Encoding.UTF8.GetString(buf.GetBuffer(), 0, (int)buf.Length); if (dropped > 0) s += Environment.NewLine + "[output truncated: " + dropped + " more bytes dropped]"; return s; } } // After the reply is sent: let leftover programs live, free the handles. public void Release() { lock (gate) { cap = 0; buf.SetLength(0); } if (job != IntPtr.Zero) { Limits(job, 0x800); CloseHandle(job); job = IntPtr.Zero; } if (hProc != IntPtr.Zero) { CloseHandle(hProc); hProc = IntPtr.Zero; } } } '@ # The child's fixed launcher. It reads the base64 script from stdin until the agent # closes it, so the script itself never touches a command line or a quote. $script:RunWrapper = @' $ErrorActionPreference = 'Continue' $ProgressPreference = 'SilentlyContinue' $ConfirmPreference = 'None' try { [Console]::OutputEncoding = New-Object Text.UTF8Encoding $false } catch { } $OutputEncoding = New-Object Text.UTF8Encoding $false $rbIn = [Console]::OpenStandardInput(); $rbMs = New-Object IO.MemoryStream; $rbIn.CopyTo($rbMs); $rbIn.Dispose() $rbSrc = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Text.Encoding]::ASCII.GetString($rbMs.ToArray()))) Remove-Variable rbIn, rbMs foreach ($rbN in 'ssh', 'scp', 'sftp') { $rbExe = Get-Command ($rbN + '.exe') -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($rbExe) { $rbBody = [ScriptBlock]::Create("& '" + $rbExe.Source.Replace("'", "''") + "' -o BatchMode=yes -o ConnectTimeout=15 @args") Set-Item -Path ('function:global:' + $rbN) -Value $rbBody Set-Item -Path ('function:global:' + $rbN + '.exe') -Value $rbBody } } Remove-Variable rbN, rbExe, rbBody -ErrorAction SilentlyContinue $global:LASTEXITCODE = 0 try { $rbSb = [ScriptBlock]::Create($rbSrc) } catch { [Console]::Out.WriteLine(($_ | Out-String)); exit 1 } & $rbSb *>&1 | Out-String -Stream -Width 300 | ForEach-Object { [Console]::Out.WriteLine($_) } if ($null -ne $global:LASTEXITCODE) { exit $global:LASTEXITCODE } exit 0 '@ $script:RunWrapperEnc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script:RunWrapper)) $script:PsExe = Join-Path $PSHOME 'powershell.exe' if (-not (Test-Path $script:PsExe)) { $script:PsExe = Join-Path $PSHOME 'pwsh.exe' } $script:RunFlags = 0x08000000 # CREATE_NO_WINDOW: own hidden console $script:Jobs = @{} # run id -> running command $script:Done = New-Object System.Collections.Specialized.OrderedDictionary # run id -> reply, for a request resent after a reconnect $script:MaxJobs = 8 $script:OutCap = 2MB $script:DefTimeout = 120 $script:MaxTimeout = 3600 $script:NL = [string][char]10 $script:RunReady = $false $script:RunError = '' try { if (-not ('RBRunV2' -as [type])) { Add-Type -TypeDefinition $script:RunCs } $script:RunReady = $true } catch { $script:RunError = ($_ | Out-String).Trim() } function Start-Run($id, [string]$b64, $timeout) { $t = $script:DefTimeout if ($null -ne $timeout -and [int]$timeout -gt 0) { $t = [Math]::Min([int]$timeout, $script:MaxTimeout) } $display = '' try { $display = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) } catch { } $line = '"' + $script:PsExe + '" -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ' + $script:RunWrapperEnc $run = [RBRunV2]::Start($line, [Environment]::CurrentDirectory, [Text.Encoding]::ASCII.GetBytes($b64), $script:OutCap, $script:RunFlags) $now = Get-Date $script:Jobs[$id] = @{ id = $id; cmd = $display; run = $run; started = $now; timeout = $t; deadline = $now.AddSeconds($t); why = ''; killedAt = $null } } function Stop-Run($j, [string]$why) { if ($null -ne $j.killedAt) { return } $j.why = $why $j.killedAt = Get-Date try { $j.run.Kill() } catch { } } # Keep the last replies so a request the server resends after a reconnect is # answered, not run twice. function Remember-Reply($id, $reply) { $script:Done[$id] = $reply while ($script:Done.Count -gt 32) { $script:Done.RemoveAt(0) } } function Send-Json($ws, $obj) { $rb = [Text.Encoding]::UTF8.GetBytes(($obj | ConvertTo-Json -Compress -Depth 6)) $t = $ws.SendAsync((New-Object System.ArraySegment[byte] (,$rb)), 'Text', $true, $script:Cts.Token) # A stalled TCP send must not hold the loop: 15 s plus 20 KB/s, then drop the socket. if (-not $t.Wait(15000 + [int]($rb.Length / 20))) { try { $ws.Abort() } catch { }; throw 'send timed out' } } function Send-Reply($ws, $obj) { if ($null -eq $ws -or $ws.State -ne 'Open') { return } try { Send-Json $ws $obj } catch { } } # Enforce deadlines and reply for every command that has finished. Runs on every # tick, also while disconnected (ws $null), so timeouts hold during a reconnect. function Step-Runs($ws) { foreach ($id in @($script:Jobs.Keys)) { $j = $script:Jobs[$id] $now = Get-Date if ($now -ge $j.deadline) { Stop-Run $j 'timeout' } $fin = $false try { $fin = $j.run.Poll(1500) } catch { $fin = $true } if (-not $fin -and $null -ne $j.killedAt -and ($now - $j.killedAt).TotalSeconds -ge 5) { $fin = $true } if (-not $fin) { continue } $out = '' try { $out = $j.run.Output() } catch { } $code = if ($j.run.Exited) { $j.run.ExitCode } else { -1 } if ($j.why -eq 'timeout') { $out = $out.TrimEnd() + $script:NL + '[killed: timeout after ' + $j.timeout + ' s]' + $script:NL; $code = 124 } elseif ($j.why -eq 'cancel') { $out = $out.TrimEnd() + $script:NL + '[killed: cancelled]' + $script:NL; $code = 130 } try { $j.run.Release() } catch { } $script:Jobs.Remove($id) $reply = @{ id = $id; out = $out; code = $code } if ($j.why) { $reply.killed = $j.why } Remember-Reply $id $reply $script:Count = $script:Count + 1 $script:LastCode = $code Report-Command ([string]$j.cmd) $out $code Send-Reply $ws $reply } } # --- File operations --------------------------------------------------------- # File ops run on a small runspace pool, off this loop, so hashing a big file or a # path that hangs (a dead network share) cannot block the socket either. # put-part / part-stat / commit: resumable upload. Chunks are written at their # offset into .rbpart (idempotent, so a chunk resent after a reconnect is # harmless), each chunk checked against its SHA-256; commit verifies the whole # file and only then moves it into place. $script:FsPs = @' param($m) $ErrorActionPreference = 'Stop' function Sha([byte[]]$b, [int]$n) { $h = [Security.Cryptography.SHA256]::Create() try { return ([BitConverter]::ToString($h.ComputeHash($b, 0, $n))).Replace('-', '').ToLower() } finally { $h.Dispose() } } function ShaFile([string]$p) { $s = New-Object IO.FileStream($p, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) try { $h = [Security.Cryptography.SHA256]::Create(); return ([BitConverter]::ToString($h.ComputeHash($s))).Replace('-', '').ToLower() } finally { $s.Dispose() } } function OpenRW([string]$p) { return (New-Object IO.FileStream($p, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite)) } $r = @{} $path = [string]$m.path $part = $path + '.rbpart' switch ([string]$m.op) { 'ls' { $items = @() foreach ($e in Get-ChildItem -LiteralPath $path -Force) { $items += @{ name = $e.Name; dir = [bool]$e.PSIsContainer; size = [int64]($e.Length); mtime = [int64]([DateTimeOffset]$e.LastWriteTimeUtc).ToUnixTimeSeconds() } } $r.entries = @($items) $r.info = 'ls ' + $path + ' (' + $items.Count + ')' } 'stat' { if (Test-Path -LiteralPath $path) { $it = Get-Item -LiteralPath $path -Force $r.exists = $true $r.dir = [bool]$it.PSIsContainer if (-not $it.PSIsContainer) { $r.size = [int64]$it.Length $r.mtime = [int64]([DateTimeOffset]$it.LastWriteTimeUtc).ToUnixTimeSeconds() if (-not $m.nohash) { $r.sha256 = ShaFile $path } } } else { $r.exists = $false } $r.info = 'stat ' + $path } 'get' { $f = New-Object IO.FileStream($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) try { $r.size = [int64]$f.Length $offset = [int64]$m.offset $len = [int]$m.length [void]$f.Seek($offset, [IO.SeekOrigin]::Begin) $bytes = New-Object byte[] $len $read = 0 while ($read -lt $len) { $n = $f.Read($bytes, $read, $len - $read); if ($n -le 0) { break }; $read += $n } $r.b64 = [Convert]::ToBase64String($bytes, 0, $read) $r.sha256 = Sha $bytes $read $r.eof = (($offset + $read) -ge $f.Length) } finally { $f.Dispose() } $r.info = 'get ' + $path + ' @' + $m.offset } 'put' { # Old single-shot write (offset 0 truncates); kept for an older fs.ts. $bytes = [Convert]::FromBase64String([string]$m.b64) $offset = [int64]$m.offset $pdir = [IO.Path]::GetDirectoryName($path) if ($pdir) { [void][IO.Directory]::CreateDirectory($pdir) } $fmode = if ($offset -eq 0) { [IO.FileMode]::Create } else { [IO.FileMode]::OpenOrCreate } $f = [IO.File]::Open($path, $fmode, [IO.FileAccess]::Write) try { [void]$f.Seek($offset, [IO.SeekOrigin]::Begin); $f.Write($bytes, 0, $bytes.Length) } finally { $f.Dispose() } $r.written = $bytes.Length if ($m.final) { $r.sha256 = ShaFile $path } $r.info = 'put ' + $path + ' +' + $bytes.Length } 'part-stat' { if (Test-Path -LiteralPath $part) { $r.size = [int64](Get-Item -LiteralPath $part -Force).Length; $r.sha256 = ShaFile $part } else { $r.size = 0 } } 'put-part' { $bytes = [Convert]::FromBase64String([string]$m.b64) if ($m.sha256 -and (Sha $bytes $bytes.Length) -ne [string]$m.sha256) { throw 'chunk checksum mismatch (damaged in transit)' } $pdir = [IO.Path]::GetDirectoryName($part) if ($pdir) { [void][IO.Directory]::CreateDirectory($pdir) } $f = OpenRW $part try { [void]$f.Seek([int64]$m.offset, [IO.SeekOrigin]::Begin); $f.Write($bytes, 0, $bytes.Length); $f.Flush($true); $r.partSize = [int64]$f.Length } finally { $f.Dispose() } $r.written = $bytes.Length $r.info = 'put ' + $path + ' @' + $m.offset + ' +' + $bytes.Length } 'commit' { $want = [string]$m.sha256 if (-not (Test-Path -LiteralPath $part)) { # A commit resent after a reconnect, already done. if ((Test-Path -LiteralPath $path) -and (ShaFile $path) -eq $want) { $r.sha256 = $want; $r.ok = $true; break } throw 'no partial upload to commit' } $f = OpenRW $part try { $f.SetLength([int64]$m.size) } finally { $f.Dispose() } $got = ShaFile $part if ($got -ne $want) { Remove-Item -LiteralPath $part -Force; throw ('checksum mismatch after upload (got ' + $got + ')') } if (Test-Path -LiteralPath $path) { [IO.File]::Replace($part, $path, $null) } else { [IO.File]::Move($part, $path) } $r.sha256 = $got $r.ok = $true $r.info = 'commit ' + $path } 'mkdir' { [void][IO.Directory]::CreateDirectory($path) $r.ok = $true $r.info = 'mkdir ' + $path } default { $r.error = 'unknown op: ' + $m.op } } return $r '@ $script:FsOpNames = @('ls', 'stat', 'get', 'put', 'part-stat', 'put-part', 'commit', 'mkdir') $script:FsPool = $null $script:FsOps = @{} # request id -> in-flight file op $script:FsStuck = 0 function Start-Fs($id, $msg) { if ($null -eq $script:FsPool) { $script:FsPool = [RunspaceFactory]::CreateRunspacePool(1, 4) $script:FsPool.Open() } $ps = [PowerShell]::Create() $ps.RunspacePool = $script:FsPool [void]$ps.AddScript($script:FsPs).AddArgument($msg) $script:FsOps[$id] = @{ ps = $ps; ar = $ps.BeginInvoke(); at = Get-Date; op = [string]$msg.op } } function Step-Fs($ws) { foreach ($id in @($script:FsOps.Keys)) { $f = $script:FsOps[$id] $reply = $null if ($f.ar.IsCompleted) { try { $rs = $f.ps.EndInvoke($f.ar) if ($null -ne $rs -and $rs.Count -gt 0) { $reply = $rs[$rs.Count - 1]; if ($reply -is [psobject]) { $reply = $reply.psobject.BaseObject } } if ($reply -isnot [hashtable]) { $reply = @{ error = 'file op returned nothing' } } } catch { $e = $_.Exception while ($null -ne $e.InnerException) { $e = $e.InnerException } $reply = @{ error = $e.Message } } try { $f.ps.Dispose() } catch { } } elseif (((Get-Date) - $f.at).TotalSeconds -ge 300) { # Stuck in a call that ignores Stop: give up on it; after 3, start a fresh pool. try { [void]$f.ps.BeginStop($null, $null) } catch { } $script:FsStuck = $script:FsStuck + 1 if ($script:FsStuck -ge 3) { $script:FsPool = $null; $script:FsStuck = 0 } $reply = @{ error = 'file op timed out on the client (300 s)' } } else { continue } $script:FsOps.Remove($id) $info = '' if ($reply.ContainsKey('info')) { $info = [string]$reply.info; $reply.Remove('info') } if ($reply.ContainsKey('error')) { $info = $f.op + ' failed: ' + [string]$reply.error } $reply.id = $id if ($info -ne '') { if ($script:Tui) { Push-Line (' ' + $info); Show-Frame } else { Write-Host (' ' + $info) } } Send-Reply $ws $reply } } # --- RustDesk: ephemeral portable remote desktop -------------------------- # nas drives this (ops rd-up / rd-down). A portable RustDesk is started pointed # at Filip's own relay with a one-session password, held inside a Job Object # flagged KILL_ON_JOB_CLOSE: the moment this agent process ends (Ctrl+C, window # close, or crash) the OS tears the job down and RustDesk dies. A clean exit also # wipes the config we wrote. We refuse if a RustDesk is already set up on the box, # so an existing install is never touched. if (-not ('RBJob' -as [type])) { try { Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public static class RBJob { [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr CreateJobObject(IntPtr a, string name); [DllImport("kernel32.dll")] public static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint len); [DllImport("kernel32.dll")] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr proc); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h); [StructLayout(LayoutKind.Sequential)] public struct BASIC { public long a; public long b; public uint LimitFlags; public UIntPtr c; public UIntPtr d; public uint e; public UIntPtr f; public uint g; public uint h; } [StructLayout(LayoutKind.Sequential)] public struct IOC { public ulong a; public ulong b; public ulong c; public ulong d; public ulong e; public ulong f; } [StructLayout(LayoutKind.Sequential)] public struct EXT { public BASIC Basic; public IOC Io; public UIntPtr a; public UIntPtr b; public UIntPtr c; public UIntPtr d; } public static IntPtr CreateKillOnClose() { IntPtr job = CreateJobObject(IntPtr.Zero, null); EXT ext = new EXT(); ext.Basic.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE int len = Marshal.SizeOf(typeof(EXT)); IntPtr p = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(ext, p, false); SetInformationJobObject(job, 9, p, (uint)len); // JobObjectExtendedLimitInformation Marshal.FreeHGlobal(p); return job; } } public static class RBWin { [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); } '@ } catch { } } function Rd-ConfigRoot { Join-Path $env:APPDATA 'RustDesk' } function Rd-Sentinel { Join-Path (Rd-ConfigRoot) '.bridge' } # A real, pre-existing RustDesk we must NOT touch: an installed exe, a running # process, or a config WITHOUT our sentinel. Our own leftover (sentinel present, # e.g. a hard kill that skipped the wipe) is not "real" and gets cleared on rd-up. # A service install of OURS is marked by C:\ProgramData\rd-bridge\owned.json, so it # (and its running processes) is never mistaken for a real one. function Rd-RealInstall { $ours = Test-Path $script:RdOwned if (-not $ours) { if (Test-Path 'C:\Program Files\RustDesk\rustdesk.exe') { return $true } if (Get-Service RustDesk -ErrorAction SilentlyContinue) { return $true } if (Get-Process rustdesk -ErrorAction SilentlyContinue) { return $true } } if ((Test-Path (Join-Path (Rd-ConfigRoot) 'config\RustDesk.toml')) -and -not (Test-Path (Rd-Sentinel))) { return $true } return $false } # --- RustDesk as a service (elevated agent only) --------------------------- # A portable RustDesk cannot see the lock screen or UAC prompts (secure desktop); # only the SYSTEM service can. So an elevated agent installs RustDesk properly and # removes it again when this window goes away. Three ways the removal runs: # 1. clean exit / rd-down: Rd-Down runs the cleanup at once (-Force) # 2. window closed, crash, kill: the SYSTEM task rd-bridge-cleanup runs every # minute and cleans once the agent process in owned.json is gone # 3. power loss / reboot: the same task runs at startup (the pid is gone then) # The cleanup only acts on an install with owned.json, which is written only by us, # only after the real-install check refused nothing. A preinstalled RustDesk is # never touched. The cleanup deletes its own task and folder as the last step. $script:RdDir = 'C:\ProgramData\rd-bridge' $script:RdOwned = 'C:\ProgramData\rd-bridge\owned.json' $script:RdTask = 'rd-bridge-cleanup' $script:RdSvcId = '' $script:RdCleanupPs = @' param([switch]$Force) $ErrorActionPreference = 'SilentlyContinue' $d = 'C:\ProgramData\rd-bridge' $m = Join-Path $d 'owned.json' if (Test-Path $m) { $o = Get-Content $m -Raw | ConvertFrom-Json if (-not $Force) { $p = Get-Process -Id ([int]$o.pid) -ErrorAction SilentlyContinue if ($p -and $p.StartTime.ToFileTimeUtc() -eq [int64]$o.start) { return } } $pf = 'C:\Program Files\RustDesk' # Same steps as RustDesk's own uninstaller (get_before_uninstall + get_uninstall). sc.exe stop RustDesk | Out-Null for ($i = 0; $i -lt 20; $i++) { $s = Get-Service RustDesk -ErrorAction SilentlyContinue; if (-not $s -or $s.Status -eq 'Stopped') { break }; Start-Sleep -Milliseconds 500 } sc.exe delete RustDesk | Out-Null for ($i = 0; $i -lt 10; $i++) { $left = @(Get-Process | Where-Object { $_.Path -and $_.Path.StartsWith($pf + '\', [StringComparison]::OrdinalIgnoreCase) }) if ($left.Count -eq 0) { break } $left | Stop-Process -Force -ErrorAction SilentlyContinue Start-Sleep -Milliseconds 500 } reg.exe delete 'HKCR\.rustdesk' /f 2>&1 | Out-Null reg.exe delete 'HKCR\rustdesk' /f 2>&1 | Out-Null reg.exe delete 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\RustDesk' /f 2>&1 | Out-Null netsh.exe advfirewall firewall delete rule name='RustDesk Service' | Out-Null foreach ($f in @($pf, ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs\RustDesk'), ($env:PUBLIC + '\Desktop\RustDesk.lnk'), ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs\Startup\RustDesk Tray.lnk'), 'C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\RustDesk')) { for ($i = 0; $i -lt 5 -and (Test-Path -LiteralPath $f); $i++) { Remove-Item -LiteralPath $f -Recurse -Force -ErrorAction SilentlyContinue; if (Test-Path -LiteralPath $f) { Start-Sleep 1 } } } # The agent user's RustDesk config, only if it carries our sentinel. if ($o.appdata -and (Test-Path -LiteralPath (Join-Path $o.appdata '.bridge'))) { Remove-Item -LiteralPath $o.appdata -Recurse -Force -ErrorAction SilentlyContinue } } Unregister-ScheduledTask -TaskName 'rd-bridge-cleanup' -Confirm:$false -ErrorAction SilentlyContinue Remove-Item -LiteralPath $d -Recurse -Force -ErrorAction SilentlyContinue '@ function Rd-Cleanup([switch]$Force) { try { & ([scriptblock]::Create($script:RdCleanupPs)) -Force:$Force } catch { } } function Rd-ArmWatchdog { $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script:RdCleanupPs)) $act = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ' + $enc) $t1 = New-ScheduledTaskTrigger -AtStartup $t2 = New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(1)) -RepetitionInterval (New-TimeSpan -Minutes 1) $pr = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest $st = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 5) Register-ScheduledTask -TaskName $script:RdTask -Action $act -Trigger @($t1, $t2) -Principal $pr -Settings $st -Force -ErrorAction Stop | Out-Null } # Run the installed rustdesk.exe CLI. It is a GUI-subsystem exe, so its output only # comes back through a pipe in cmd; run it from its own folder so cmd never sees a # quoted path (cmd strips the quotes and breaks on the space in Program Files). function Rd-Cli([string]$cliArgs) { Push-Location 'C:\Program Files\RustDesk' try { return ((cmd /c ('rustdesk.exe ' + $cliArgs + ' | more')) -join ' ').Trim() } finally { Pop-Location } } function Rd-UpService([string]$password) { if ($script:RdSvcId) { return @{ id = $script:RdSvcId; password = $script:RdPassword; already = $true } } if (Rd-RealInstall) { return @{ error = 'RustDesk already set up on this machine; not touching it' } } if (Test-Path $script:RdOwned) { # Ours from an earlier session. Clean it if its agent is gone, else refuse. Rd-Cleanup if (Test-Path $script:RdOwned) { return @{ error = 'RustDesk service belongs to another live bridge session' } } } if (Test-Path (Rd-ConfigRoot)) { try { Remove-Item -LiteralPath (Rd-ConfigRoot) -Recurse -Force -ErrorAction SilentlyContinue } catch { } } $exe = Rd-EnsureExe # Mark it ours and arm the watchdog BEFORE installing, so even a crash mid-install is cleaned. [void][IO.Directory]::CreateDirectory($script:RdDir) $me = Get-Process -Id $PID $owned = @{ pid = $PID; start = $me.StartTime.ToFileTimeUtc(); appdata = (Rd-ConfigRoot); name = $script:Name } | ConvertTo-Json -Compress [IO.File]::WriteAllText($script:RdOwned, $owned) try { Rd-ArmWatchdog } catch { Rd-Cleanup -Force; return @{ error = 'watchdog task failed: ' + ($_ | Out-String).Trim() } } [void](Start-Process -FilePath $exe -ArgumentList '--silent-install', 'printer=0' -PassThru) $ok = $false for ($i = 0; $i -lt 90; $i++) { $s = Get-Service RustDesk -ErrorAction SilentlyContinue if ($s -and $s.Status -eq 'Running' -and (Test-Path 'C:\Program Files\RustDesk\rustdesk.exe')) { $ok = $true; break } Start-Sleep 1 } if (-not $ok) { Rd-Cleanup -Force; return @{ error = 'RustDesk service did not start' } } [void][IO.Directory]::CreateDirectory((Rd-ConfigRoot)) [IO.File]::WriteAllText((Rd-Sentinel), 'remote-bridge' + [Environment]::NewLine) Start-Sleep 3 foreach ($kv in @(@('custom-rendezvous-server', $RdServer), @('relay-server', $RdServer), @('key', $RdKey), @('verification-method', 'use-permanent-password'), @('approve-mode', 'password'))) { [void](Rd-Cli ('--option ' + $kv[0] + ' ' + $kv[1])) } $pw = Rd-Cli ('--password ' + $password) if ($pw -notmatch 'Done') { Rd-Cleanup -Force; return @{ error = 'setting the RustDesk password failed: ' + $pw } } $id = '' for ($i = 0; $i -lt 20 -and $id -notmatch '^[0-9]{6,}$'; $i++) { $id = Rd-Cli '--get-id'; if ($id -notmatch '^[0-9]{6,}$') { Start-Sleep 1 } } if ($id -notmatch '^[0-9]{6,}$') { Rd-Cleanup -Force; return @{ error = 'no RustDesk id from the service' } } $script:RdSvcId = $id $script:RdPassword = $password $confirmed = Rd-WaitConfirmed return @{ id = $id; password = $password; confirmed = $confirmed } } function Rd-EnsureExe { $d = Join-Path $env:TEMP 'rd-bridge' [void][IO.Directory]::CreateDirectory($d) $exe = Join-Path $d 'rustdesk.exe' $ok = $false if (Test-Path $exe) { try { if ((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLower() -eq $RdSha) { $ok = $true } } catch { } } if (-not $ok) { $old = $ProgressPreference; $ProgressPreference = 'SilentlyContinue' try { Invoke-WebRequest -Uri $RdExeUrl -OutFile $exe -UseBasicParsing -TimeoutSec 120 } finally { $ProgressPreference = $old } if ((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLower() -ne $RdSha) { throw 'rustdesk.exe hash mismatch' } } return $exe } function Rd-WriteConfig([string]$id, [string]$password) { $cfg = Join-Path (Rd-ConfigRoot) 'config' [void][IO.Directory]::CreateDirectory($cfg) $nl = [Environment]::NewLine $opts = @( "rendezvous_server = ''", 'nat_type = 0', 'serial = 0', '', '[options]', ("custom-rendezvous-server = '" + $RdServer + "'"), ("relay-server = '" + $RdServer + "'"), ("key = '" + $RdKey + "'"), "verification-method = 'use-permanent-password'", "approve-mode = 'password'" ) -join $nl [IO.File]::WriteAllText((Join-Path $cfg 'RustDesk2.toml'), ($opts + $nl)) # We pick the id (RustDesk stores it only as encrypted enc_id, unreadable; but a # plaintext id with empty enc_id is adopted and registered as-is on first load). $main = ("id = '" + $id + "'" + $nl + "password = '" + $password + "'" + $nl) [IO.File]::WriteAllText((Join-Path $cfg 'RustDesk.toml'), $main) # Mark this config as ours so a leftover (after a hard kill) is reused, not refused. [IO.File]::WriteAllText((Rd-Sentinel), 'remote-bridge' + $nl) } function Rd-Hide($p) { for ($i = 0; $i -lt 24; $i++) { $h = [IntPtr]::Zero try { $p.Refresh(); $h = $p.MainWindowHandle } catch { } if ($h -ne [IntPtr]::Zero) { try { [void][RBWin]::ShowWindow($h, 0) } catch { }; break } Start-Sleep -Milliseconds 250 } } # Wait (best effort) for RustDesk to confirm registration with the relay. function Rd-WaitConfirmed { $f = Join-Path (Rd-ConfigRoot) 'config\RustDesk.toml' for ($i = 0; $i -lt 60; $i++) { try { if (Test-Path $f) { if (Select-String -Path $f -Pattern 'key_confirmed = true' -Quiet) { return $true } } } catch { } Start-Sleep -Milliseconds 250 } return $false } # The portable rustdesk.exe we start is a launcher: it unpacks to %LOCALAPPDATA%\rustdesk, # starts that copy (inside our Job Object) and exits. So "our session is running" means # a rustdesk from that folder is alive, not that the launcher handle is. function Rd-PortableRunning { $dir = (Join-Path $env:LOCALAPPDATA 'rustdesk') + '\' return [bool](Get-Process rustdesk -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path.StartsWith($dir, [StringComparison]::OrdinalIgnoreCase) }) } function Rd-Up([string]$password) { if ($script:Admin) { return (Rd-UpService $password) } if ($script:RdId -and (Rd-PortableRunning)) { return @{ id = $script:RdId; password = $script:RdPassword; already = $true } } if (Rd-RealInstall) { return @{ error = 'RustDesk already set up on this machine; not touching it' } } # Clear any leftover config of ours (sentinel present) from a previous hard kill. if (Test-Path (Rd-ConfigRoot)) { try { Remove-Item -LiteralPath (Rd-ConfigRoot) -Recurse -Force -ErrorAction SilentlyContinue } catch { } } $exe = Rd-EnsureExe # RustDesk ids are 10-digit numbers; pick one so we know it without decrypting enc_id. $id = (Get-Random -Minimum 1000000000 -Maximum 1999999999).ToString() Rd-WriteConfig $id $password $script:RdCreatedConfig = $true if ($script:RdJobHandle -eq [IntPtr]::Zero) { $script:RdJobHandle = [RBJob]::CreateKillOnClose() } $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $exe $psi.Arguments = '--noinstall' $psi.UseShellExecute = $false $psi.WindowStyle = 'Hidden' $p = [System.Diagnostics.Process]::Start($psi) try { [void][RBJob]::AssignProcessToJobObject($script:RdJobHandle, $p.Handle) } catch { } $script:RdProc = $p Rd-Hide $p $script:RdId = $id $script:RdPassword = $password $confirmed = Rd-WaitConfirmed return @{ id = $id; password = $password; confirmed = $confirmed } } function Rd-Down { # Service mode: remove our install now, but only the one this process owns. if ($script:Admin -and (Test-Path $script:RdOwned)) { try { $o = Get-Content $script:RdOwned -Raw | ConvertFrom-Json; if ([int]$o.pid -eq $PID) { Rd-Cleanup -Force } } catch { } } $script:RdSvcId = '' # Closing the Job Object handle fires KILL_ON_JOB_CLOSE on the whole tree. try { if ($script:RdJobHandle -ne [IntPtr]::Zero) { [void][RBJob]::CloseHandle($script:RdJobHandle) } } catch { } $script:RdJobHandle = [IntPtr]::Zero try { if ($null -ne $script:RdProc -and -not $script:RdProc.HasExited) { $script:RdProc.Kill() } } catch { } $script:RdProc = $null; $script:RdId = ''; $script:RdPassword = '' if ($script:RdCreatedConfig) { try { Remove-Item -LiteralPath (Rd-ConfigRoot) -Recurse -Force -ErrorAction SilentlyContinue } catch { } $script:RdCreatedConfig = $false } } if ($script:Tui) { try { [Console]::CursorVisible = $false } catch { } try { [Console]::Clear() } catch { } Show-Frame } else { Write-Host ('remote-bridge: connecting as ' + $script:Name + ' - keep this window open, close it to disconnect.') } try { $ct = $script:Cts.Token while (-not $script:Stop) { $ws = $null try { $ws = New-Object System.Net.WebSockets.ClientWebSocket $ws.Options.KeepAliveInterval = [TimeSpan]::FromSeconds(15) $uri = [Uri]($Server + '?token=' + $Token + '&name=' + [Uri]::EscapeDataString($Name) + '&v=2&inst=' + $script:Inst) Set-State 'connecting' # Connect with a 20 s ceiling, still stepping commands while it waits. $cc = [Threading.CancellationTokenSource]::CreateLinkedTokenSource($ct) $cc.CancelAfter(20000) $connect = $ws.ConnectAsync($uri, $cc.Token) while (-not $connect.Wait(250)) { Poll-Keys; if ($script:Stop) { break }; Step-Runs $null; Step-Fs $null } if ($script:Stop) { break } [void]$connect.GetAwaiter().GetResult() Set-State 'connected' $buf = New-Object byte[] 65536 $recvTask = $null $script:LastRecv = Get-Date $script:HbSeen = $false while ($ws.State -eq 'Open' -and -not $script:Stop) { # Wait for a frame with a short ceiling so commands are stepped, the status # bar ticks and Ctrl+C (read as input in Poll-Keys) is noticed; the same # pending receive task is reused across ticks. if ($null -eq $recvTask) { $seg = New-Object System.ArraySegment[byte] (,$buf) $recvTask = $ws.ReceiveAsync($seg, $ct) } $tick = if ($script:Jobs.Count -gt 0 -or $script:FsOps.Count -gt 0) { 200 } else { 1000 } if (-not $recvTask.Wait($tick)) { if ($script:Stop) { break } Poll-Keys if ($script:Stop) { break } Step-Runs $ws Step-Fs $ws # The server sends a heartbeat every 15 s. 45 s of silence means the link # is dead even if TCP has not noticed: drop it and reconnect. if ($script:HbSeen -and ((Get-Date) - $script:LastRecv).TotalSeconds -ge 45) { try { $ws.Abort() } catch { }; break } Show-Frame; continue } $r = $recvTask.Result $recvTask = $null $script:LastRecv = Get-Date if ($r.MessageType -eq 'Close') { break } $mstream = New-Object System.IO.MemoryStream $mstream.Write($buf, 0, $r.Count) while (-not $r.EndOfMessage) { $seg2 = New-Object System.ArraySegment[byte] (,$buf) $more = $ws.ReceiveAsync($seg2, $ct) if (-not $more.Wait(30000)) { try { $ws.Abort() } catch { }; throw 'receive stalled mid-message' } $r = $more.Result if ($r.MessageType -eq 'Close') { break } $mstream.Write($buf, 0, $r.Count) } if ($r.MessageType -eq 'Close') { break } # Handle ONE message. A failure here replies with an error but must NEVER # break the connection loop (that is what used to strand the tunnel). $msg = $null try { $msg = [Text.Encoding]::UTF8.GetString($mstream.ToArray()) | ConvertFrom-Json $op = if ($msg.op) { [string]$msg.op } else { 'run' } $id = [string]$msg.id $reply = @{ id = $id } if ($op -eq 'hb') { $script:HbSeen = $true $reply = $null } elseif ($op -eq 'caps') { $reply.v = 2 $reply.ops = @('run', 'cancel', 'ps', 'caps') + $script:FsOpNames + @('rd-up', 'rd-down') $reply.maxJobs = $script:MaxJobs; $reply.outCap = $script:OutCap; $reply.maxTimeout = $script:MaxTimeout } elseif ($op -eq 'run') { if ($script:Done.Contains($id)) { $reply = $script:Done[$id] # resent after a reconnect: same answer } elseif ($script:Jobs.ContainsKey($id)) { $reply = $null # resent while running: answered when it ends } elseif (-not $script:RunReady) { $reply.error = 'command launcher unavailable on this client: ' + $script:RunError } elseif ($script:Jobs.Count -ge $script:MaxJobs) { $reply.error = 'busy: ' + $script:Jobs.Count + ' commands running (run.sh --ps / --cancel)' } else { $b64 = [string]$msg.b64 if (-not $b64) { $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$msg.cmd)) } Start-Run $id $b64 $msg.timeout Set-State 'connected' $reply = $null } } elseif ($op -eq 'cancel') { $hit = @() foreach ($j in @($script:Jobs.Values)) { if (-not $msg.job -or [string]$msg.job -eq $j.id) { Stop-Run $j 'cancel'; $hit += $j.id } } $reply.ok = ($hit.Count -gt 0) $reply.cancelled = @($hit) if ($hit.Count -eq 0) { $reply.info = 'nothing running' } elseif ($script:Tui) { Push-Line (' cancel ' + $hit.Count); Show-Frame } else { Write-Host (' cancel ' + $hit.Count) } } elseif ($op -eq 'ps') { $now = Get-Date $reply.jobs = @(foreach ($j in $script:Jobs.Values) { $c = ($j.cmd -replace '\s+', ' ').Trim() if ($c.Length -gt 120) { $c = $c.Substring(0, 120) + '...' } @{ id = $j.id; cmd = $c; pid = $j.run.Pid; secs = [int]($now - $j.started).TotalSeconds; timeout = $j.timeout; bytes = $j.run.Bytes; killing = [string]$j.why } }) $reply.fsops = $script:FsOps.Count } elseif ($script:FsOpNames -contains $op) { # Resent while still running: answered when it ends. if ($script:FsOps.ContainsKey($id)) { $reply = $null } else { Start-Fs $id $msg; $reply = $null } } else { $info = '' switch ($op) { 'rd-up' { $r = Rd-Up ([string]$msg.password) if ($r.ContainsKey('error')) { $reply.error = [string]$r.error } else { # NB: $reply.id is the rpc correlation id the server matches on; # the RustDesk id + applied password go under rdid/rdpw so they # do not clobber it. The agent owns the password it applied. $reply.rdid = [string]$r.id $reply.rdpw = [string]$r.password if ($r.ContainsKey('already')) { $reply.already = $true } if ($r.ContainsKey('confirmed')) { $reply.confirmed = [bool]$r.confirmed } } $info = 'rd-up ' + $(if ($reply.rdid) { $reply.rdid } else { $reply.error }) # nas asks again on every reconnect; show the refusal once per agent start. if ($reply.error -like '*already set up*') { if ($script:RdRefusalShown) { $info = '' } else { $script:RdRefusalShown = $true } } } 'rd-down' { Rd-Down $reply.ok = $true $info = 'rd-down' } default { $reply.error = 'unknown op: ' + $op } } if ($info -ne '') { if ($script:Tui) { Push-Line (' ' + $info); Show-Frame } else { Write-Host (' ' + $info) } } } if ($null -ne $reply) { Send-Json $ws $reply } Step-Runs $ws Step-Fs $ws } catch { if ($script:Stop) { throw } $rid = $null if ($null -ne $msg) { $rid = $msg.id } Send-Reply $ws @{ id = $rid; error = ($_ | Out-String).Trim() } } } } catch { # Ctrl+C / cancel exits; a genuine drop falls through to the reconnect wait. if ($script:Stop) { break } } finally { # Always free the socket so a reconnect is never blocked by a stale one. try { if ($null -ne $ws) { $ws.Dispose() } } catch { } } if ($script:Stop) { break } Set-State 'reconnecting' for ($i = 0; $i -lt 12 -and -not $script:Stop; $i++) { Start-Sleep -Milliseconds 250; Poll-Keys; Step-Runs $null; Step-Fs $null } } } finally { # Commands still running die with the agent (their jobs are kill-on-close; this # also covers a window that keeps running PowerShell after the agent returns). foreach ($j in @($script:Jobs.Values)) { try { $j.run.Kill(); $j.run.Release() } catch { } } # Access disappears with the window: stop RustDesk and wipe the config we wrote. try { Rd-Down } catch { } # Always restore the terminal, whatever happened. Guard every console call. try { if ($null -ne $script:FsPool) { $script:FsPool.Close() } } catch { } try { if ($null -ne $script:Cts) { $script:Cts.Cancel() } } catch { } try { [Console]::TreatControlCAsInput = $false } catch { } try { if ($script:Ansi) { [Console]::Write([string]$script:Esc + '[0m') } } catch { } try { [Console]::ResetColor() } catch { } try { [Console]::CursorVisible = $true } catch { } try { if ($script:Tui) { [Console]::Clear(); [Console]::SetCursorPosition(0, 0) } } catch { } try { Write-Host 'remote-bridge: disconnected.' } catch { } }