389 lines
15 KiB
PowerShell
389 lines
15 KiB
PowerShell
# ==============================================================================
|
|
# Script Name: 8x8_Work_Updater.ps1
|
|
# 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
|
|
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
|
Write-Error "This script must be executed with Administrator privileges."
|
|
exit 1
|
|
}
|
|
|
|
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"
|
|
$installerPath = Join-Path $workDir "8x8_Work_Installer.msi"
|
|
|
|
if (-not (Test-Path $workDir)) {
|
|
New-Item -Path $workDir -ItemType Directory -Force | Out-Null
|
|
}
|
|
|
|
$acl = Get-Acl $workDir
|
|
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
|
|
$acl.AddAccessRule($rule)
|
|
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 Installer with Stream Progress Bar
|
|
# --------------------------------------------------------------------------
|
|
$installerUrl = "https://work-desktop-assets.8x8.com/prod-publish/ga/work-64-msi-v8.35.2-6.msi"
|
|
Write-Host "[1/4] Downloading 8x8 Work installer..." -ForegroundColor Cyan
|
|
|
|
try {
|
|
$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)" }
|
|
|
|
$totalBytes = $response.Content.Headers.ContentLength
|
|
$inputStream = $response.Content.ReadAsStreamAsync().Result
|
|
$outputStream = [System.IO.File]::Create($installerPath)
|
|
$buffer = New-Object byte[] 8192
|
|
$totalBytesRead = 0; $bytesRead = 0
|
|
|
|
while (($bytesRead = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
|
|
$outputStream.Write($buffer, 0, $bytesRead)
|
|
$totalBytesRead += $bytesRead
|
|
|
|
if ($totalBytes -gt 0) {
|
|
$percent = [math]::Round(($totalBytesRead / $totalBytes) * 100)
|
|
$downloadedMB = [math]::Round($totalBytesRead / 1MB, 2)
|
|
$totalMB = [math]::Round($totalBytes / 1MB, 2)
|
|
$barLength = 30
|
|
$filledLength = [math]::Round(($percent / 100) * $barLength)
|
|
$bar = ("#" * $filledLength) + ("-" * ($barLength - $filledLength))
|
|
|
|
Write-Host "`rDownloading: [$bar] $percent% ($downloadedMB MB / $totalMB MB)" -NoNewline -ForegroundColor Yellow
|
|
}
|
|
}
|
|
$outputStream.Close(); $inputStream.Close(); $httpClient.Dispose()
|
|
Write-Host "`nDownload complete: $installerPath" -ForegroundColor Green
|
|
} catch {
|
|
Write-Error "`nFailed to download installer. Error: $_"
|
|
exit 1
|
|
}
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Step 2: Write User-Session GUI Script (BOM-Free UTF-8)
|
|
# --------------------------------------------------------------------------
|
|
Write-Host "[2/4] Generating countdown dialog for active desktop..." -ForegroundColor Cyan
|
|
|
|
$guiContent = @'
|
|
Add-Type -AssemblyName System.Windows.Forms
|
|
Add-Type -AssemblyName System.Drawing
|
|
|
|
$flagPath = "C:\ProgramData\JCT600_8x8Update\8x8_Update_Proceed.flag"
|
|
|
|
$form = New-Object System.Windows.Forms.Form
|
|
$form.Text = "JCT600 IT Support — 8x8 Work Update"
|
|
$form.Size = New-Object System.Drawing.Size(460, 260)
|
|
$form.StartPosition = 'CenterScreen'
|
|
$form.FormBorderStyle = 'FixedDialog'
|
|
$form.MaximizeBox = $false
|
|
$form.MinimizeBox = $false
|
|
$form.ControlBox = $false
|
|
$form.TopMost = $true
|
|
|
|
$script:allowClose = $false
|
|
$form.Add_FormClosing({
|
|
param($sender, $e)
|
|
if (-not $script:allowClose) { $e.Cancel = $true }
|
|
})
|
|
|
|
$labelHeader = New-Object System.Windows.Forms.Label
|
|
$labelHeader.Text = "JCT600 — IT SUPPORT"
|
|
$labelHeader.Location = New-Object System.Drawing.Point(20, 15)
|
|
$labelHeader.Size = New-Object System.Drawing.Size(400, 25)
|
|
$labelHeader.Font = New-Object System.Drawing.Font("Segoe UI", 12, [System.Drawing.FontStyle]::Bold)
|
|
$labelHeader.ForeColor = [System.Drawing.Color]::Navy
|
|
$labelHeader.TextAlign = 'TopCenter'
|
|
$form.Controls.Add($labelHeader)
|
|
|
|
$labelMsg = New-Object System.Windows.Forms.Label
|
|
$labelMsg.Text = "An automatic update for 8x8 Work has been scheduled by IT Support.`nPlease save active work or click 'Update Now' to proceed."
|
|
$labelMsg.Location = New-Object System.Drawing.Point(20, 48)
|
|
$labelMsg.Size = New-Object System.Drawing.Size(400, 40)
|
|
$labelMsg.Font = New-Object System.Drawing.Font("Segoe UI", 9)
|
|
$labelMsg.TextAlign = 'TopCenter'
|
|
$form.Controls.Add($labelMsg)
|
|
|
|
$labelTimer = New-Object System.Windows.Forms.Label
|
|
$labelTimer.Location = New-Object System.Drawing.Point(20, 95)
|
|
$labelTimer.Size = New-Object System.Drawing.Size(400, 40)
|
|
$labelTimer.Font = New-Object System.Drawing.Font("Segoe UI", 20, [System.Drawing.FontStyle]::Bold)
|
|
$labelTimer.ForeColor = [System.Drawing.Color]::DarkRed
|
|
$labelTimer.TextAlign = 'MiddleCenter'
|
|
$form.Controls.Add($labelTimer)
|
|
|
|
$btnUpdateNow = New-Object System.Windows.Forms.Button
|
|
$btnUpdateNow.Text = "Update Now"
|
|
$btnUpdateNow.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
|
|
$btnUpdateNow.Size = New-Object System.Drawing.Size(150, 40)
|
|
$btnUpdateNow.Location = New-Object System.Drawing.Point(145, 155)
|
|
$btnUpdateNow.UseVisualStyleBackColor = $true
|
|
|
|
$timer = New-Object System.Windows.Forms.Timer
|
|
$timer.Interval = 1000
|
|
$script:remaining = 3600 # 1 Hour
|
|
|
|
$btnUpdateNow.Add_Click({
|
|
$timer.Stop()
|
|
$script:allowClose = $true
|
|
New-Item -Path $flagPath -ItemType File -Force | Out-Null
|
|
$form.Close()
|
|
})
|
|
$form.Controls.Add($btnUpdateNow)
|
|
|
|
$timer.Add_Tick({
|
|
if ($script:remaining -gt 0) {
|
|
$timeSpan = [TimeSpan]::FromSeconds($script:remaining)
|
|
$labelTimer.Text = $timeSpan.ToString("hh\:mm\:ss")
|
|
$script:remaining--
|
|
} else {
|
|
$timer.Stop()
|
|
$script:allowClose = $true
|
|
New-Item -Path $flagPath -ItemType File -Force | Out-Null
|
|
$form.Close()
|
|
}
|
|
})
|
|
|
|
$initialSpan = [TimeSpan]::FromSeconds($script:remaining)
|
|
$labelTimer.Text = $initialSpan.ToString("hh\:mm\:ss")
|
|
|
|
$timer.Start()
|
|
[System.Windows.Forms.Application]::Run($form)
|
|
'@
|
|
|
|
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
|
[System.IO.File]::WriteAllText($guiScript, $guiContent, $utf8NoBom)
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Step 3: Launch Native GUI on User's Screen & Wait
|
|
# --------------------------------------------------------------------------
|
|
$psExe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
|
|
$launchCmd = "`"$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 Processes & Install Silently
|
|
# --------------------------------------------------------------------------
|
|
Write-Host "[3/4] Stopping 8x8 processes and installing silently..." -ForegroundColor Cyan
|
|
|
|
$targetProcesses = Get-Process | Where-Object {
|
|
$_.ProcessName -like "*8x8*" -or $_.MainWindowTitle -like "*8x8*"
|
|
}
|
|
|
|
if ($targetProcesses) {
|
|
foreach ($proc in $targetProcesses) {
|
|
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
|
|
}
|
|
Start-Sleep -Seconds 3
|
|
}
|
|
|
|
$msiArgs = "/i `"$installerPath`" /quiet /norestart"
|
|
$installJob = Start-Process msiexec.exe -ArgumentList $msiArgs -Wait -PassThru
|
|
|
|
if ($installJob.ExitCode -ne 0 -and $installJob.ExitCode -ne 3010) {
|
|
Write-Error "Installation failed with exit code $($installJob.ExitCode)."
|
|
exit $installJob.ExitCode
|
|
}
|
|
|
|
Write-Host "Installation completed successfully." -ForegroundColor Green
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Step 5: Launch Updated 8x8 Work in User Session
|
|
# --------------------------------------------------------------------------
|
|
Write-Host "[4/4] Launching updated 8x8 Work..." -ForegroundColor Cyan
|
|
|
|
$possiblePaths = @(
|
|
"${env:ProgramFiles}\8x8 Inc\8x8 Work\8x8 Work.exe",
|
|
"${env:ProgramFiles(x86)}\8x8 Inc\8x8 Work\8x8 Work.exe",
|
|
"${env:ProgramFiles}\8x8 Work\8x8 Work.exe",
|
|
"$env:LocalAppData\Programs\8x8 Work\8x8 Work.exe"
|
|
)
|
|
|
|
$exePath = $possiblePaths | Where-Object { Test-Path $_ } | Select-Object -First 1
|
|
|
|
if ($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."
|
|
}
|
|
|
|
} finally {
|
|
Write-Host "Cleaning up temporary files..." -ForegroundColor Gray
|
|
if (Test-Path $workDir) {
|
|
Remove-Item $workDir -Recurse -Force -ErrorAction SilentlyContinue
|
|
}
|
|
} |