From 81a69dc432ad2da37c04af20509c861dfb68715c Mon Sep 17 00:00:00 2001 From: CristianD Date: Mon, 24 Aug 2026 15:25:49 +0100 Subject: [PATCH] Update 8x8_Work_Updater.ps1 --- 8x8_Work_Updater.ps1 | 206 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 172 insertions(+), 34 deletions(-) diff --git a/8x8_Work_Updater.ps1 b/8x8_Work_Updater.ps1 index 1dba053..579f2cb 100644 --- a/8x8_Work_Updater.ps1 +++ b/8x8_Work_Updater.ps1 @@ -1,8 +1,8 @@ # ============================================================================== # Script Name: 8x8_Work_Updater.ps1 -# Description: Self-contained updater script runnable directly from console. -# Downloads PsExec + 8x8, pops up the live countdown GUI on the -# active user's desktop, silently updates, and relaunches 8x8. +# Description: Self-contained console updater. Uses native Win32 token +# privilege elevation to launch the interactive GUI on the +# active desktop without triggering Defender or using external tools. # ============================================================================== # Ensure script is running elevated @@ -16,14 +16,12 @@ Add-Type -AssemblyName System.Net.Http $workDir = "C:\ProgramData\JCT600_8x8Update" $flagFile = Join-Path $workDir "8x8_Update_Proceed.flag" $guiScript = Join-Path $workDir "Show-8x8UserGui.ps1" -$psexecPath = Join-Path $workDir "PsExec.exe" $installerPath = Join-Path $workDir "8x8_Work_Installer.msi" if (-not (Test-Path $workDir)) { New-Item -Path $workDir -ItemType Directory -Force | Out-Null } -# Ensure standard user has full read/write access to folder and signal flags $acl = Get-Acl $workDir $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) @@ -31,20 +29,168 @@ Set-Acl $workDir $acl if (Test-Path $flagFile) { Remove-Item $flagFile -Force } +# ------------------------------------------------------------------------------ +# Native Win32 Interactive Session Process Spawner (Defender-Compliant) +# ------------------------------------------------------------------------------ +$PInvokeCode = @" +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; + +public class NativeDesktopLauncher +{ + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid); + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength); + + [DllImport("wtsapi32.dll", SetLastError = true)] + private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr phToken); + + [DllImport("kernel32.dll")] + private static extern uint WTSGetActiveConsoleSessionId(); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool CreateProcessAsUser( + IntPtr hToken, + string lpApplicationName, + string lpCommandLine, + IntPtr lpProcessAttributes, + IntPtr lpThreadAttributes, + bool bInheritHandles, + uint dwCreationFlags, + IntPtr lpEnvironment, + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation + ); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr hObject); + + [StructLayout(LayoutKind.Sequential)] + private struct LUID + { + public uint LowPart; + public int HighPart; + } + + [StructLayout(LayoutKind.Sequential)] + private struct TOKEN_PRIVILEGES + { + public uint PrivilegeCount; + public LUID Luid; + public uint Attributes; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct STARTUPINFO + { + public int cb; + public string lpReserved; + public string lpDesktop; + public string lpTitle; + public int dwX; + public int dwY; + public int dwXSize; + public int dwYSize; + public int dwXCountChars; + public int dwYCountChars; + public int dwFillAttribute; + public int dwFlags; + public short wShowWindow; + public short cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public int dwProcessId; + public int dwThreadId; + } + + private static bool EnablePrivilege(string privilegeName) + { + IntPtr hToken; + if (!OpenProcessToken(Process.GetCurrentProcess().Handle, 0x0020 | 0x0008, out hToken)) return false; + + LUID luid; + if (!LookupPrivilegeValue(null, privilegeName, out luid)) + { + CloseHandle(hToken); + return false; + } + + TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(); + tp.PrivilegeCount = 1; + tp.Luid = luid; + tp.Attributes = 0x00000002; // SE_PRIVILEGE_ENABLED + + bool result = AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); + CloseHandle(hToken); + return result; + } + + public static bool RunAsActiveUser(string commandLine) + { + EnablePrivilege("SeAssignPrimaryTokenPrivilege"); + EnablePrivilege("SeIncreaseQuotaPrivilege"); + + uint activeSession = WTSGetActiveConsoleSessionId(); + if (activeSession == 0xFFFFFFFF) return false; + + IntPtr userToken = IntPtr.Zero; + if (!WTSQueryUserToken(activeSession, out userToken)) return false; + + STARTUPINFO si = new STARTUPINFO(); + si.cb = Marshal.SizeOf(si); + si.lpDesktop = @"winsta0\default"; + + PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); + bool success = CreateProcessAsUser( + userToken, + null, + commandLine, + IntPtr.Zero, + IntPtr.Zero, + false, + 0x00000010, // CREATE_NEW_CONSOLE + IntPtr.Zero, + null, + ref si, + out pi + ); + + if (pi.hProcess != IntPtr.Zero) CloseHandle(pi.hProcess); + if (pi.hThread != IntPtr.Zero) CloseHandle(pi.hThread); + if (userToken != IntPtr.Zero) CloseHandle(userToken); + + return success; + } +} +"@ + +Add-Type -TypeDefinition $PInvokeCode -ErrorAction SilentlyContinue + try { # -------------------------------------------------------------------------- - # Step 1: Download 8x8 Setup Installer with Console Progress Bar & PsExec + # Step 1: Download 8x8 Installer with Stream Progress Bar # -------------------------------------------------------------------------- $installerUrl = "https://work-desktop-assets.8x8.com/prod-publish/ga/work-64-msi-v8.35.2-6.msi" - $psexecUrl = "https://live.sysinternals.com/PsExec.exe" - - Write-Host "[1/4] Downloading 8x8 Work installer and helper tools..." -ForegroundColor Cyan + Write-Host "[1/4] Downloading 8x8 Work installer..." -ForegroundColor Cyan try { - # Download PsExec directly from Microsoft Sysinternals - Invoke-WebRequest -Uri $psexecUrl -OutFile $psexecPath -UseBasicParsing - - # Download 8x8 Installer with Stream Progress Bar $httpClient = New-Object System.Net.Http.HttpClient $response = $httpClient.GetAsync($installerUrl, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).Result if (-not $response.IsSuccessStatusCode) { throw "HTTP Error $($response.StatusCode)" } @@ -73,12 +219,12 @@ try { $outputStream.Close(); $inputStream.Close(); $httpClient.Dispose() Write-Host "`nDownload complete: $installerPath" -ForegroundColor Green } catch { - Write-Error "`nFailed to download installer or tools. Error: $_" + Write-Error "`nFailed to download installer. Error: $_" exit 1 } # -------------------------------------------------------------------------- - # Step 2: Generate User-Session GUI Script (BOM-Free UTF-8) + # Step 2: Write User-Session GUI Script (BOM-Free UTF-8) # -------------------------------------------------------------------------- Write-Host "[2/4] Generating countdown dialog for active desktop..." -ForegroundColor Cyan @@ -172,28 +318,24 @@ $timer.Start() [System.IO.File]::WriteAllText($guiScript, $guiContent, $utf8NoBom) # -------------------------------------------------------------------------- - # Step 3: Launch GUI Directly onto User's Screen & Wait + # Step 3: Launch Native GUI on User's Screen & Wait # -------------------------------------------------------------------------- - $explorerProc = Get-Process -Name explorer -ErrorAction SilentlyContinue | Select-Object -First 1 + $psExe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" + $launchCmd = "`"$psExe`" -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$guiScript`"" - if (-not $explorerProc) { - Write-Warning "No active user desktop session detected. Proceeding directly to update." - } else { - $sessionId = $explorerProc.SessionId - Write-Host "Targeting Active Desktop Session ID: $sessionId" -ForegroundColor Green - - # Launch the GUI directly into the active user's physical screen via PsExec - $psExe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" - & $psexecPath -accepteula -nobanner -i $sessionId -d $psExe -ExecutionPolicy Bypass -WindowStyle Hidden -File "$guiScript" + $launched = [NativeDesktopLauncher]::RunAsActiveUser($launchCmd) + if ($launched) { Write-Host "Dialog displayed on screen. Waiting for user response or 1-hour expiration..." -ForegroundColor Yellow while (-not (Test-Path $flagFile)) { Start-Sleep -Seconds 2 } + } else { + Write-Warning "Could not detect active console session. Proceeding with silent install." } # -------------------------------------------------------------------------- - # Step 4: Stop 8x8, Silently Install & Relaunch + # Step 4: Stop 8x8 Processes & Install Silently # -------------------------------------------------------------------------- Write-Host "[3/4] Stopping 8x8 processes and installing silently..." -ForegroundColor Cyan @@ -219,7 +361,7 @@ $timer.Start() Write-Host "Installation completed successfully." -ForegroundColor Green # -------------------------------------------------------------------------- - # Step 5: Launch 8x8 Work + # Step 5: Launch Updated 8x8 Work in User Session # -------------------------------------------------------------------------- Write-Host "[4/4] Launching updated 8x8 Work..." -ForegroundColor Cyan @@ -233,12 +375,8 @@ $timer.Start() $exePath = $possiblePaths | Where-Object { Test-Path $_ } | Select-Object -First 1 if ($exePath) { - if ($explorerProc) { - & $psexecPath -accepteula -nobanner -i $sessionId -d "$exePath" - Write-Host "8x8 Work launched successfully in user context." -ForegroundColor Green - } else { - Start-Process -FilePath $exePath - } + [NativeDesktopLauncher]::RunAsActiveUser("`"$exePath`"") | Out-Null + Write-Host "8x8 Work launched successfully in user context." -ForegroundColor Green } else { Write-Warning "Could not locate 8x8 Work executable." }