& { $ErrorActionPreference = 'Stop' $stage = 'Подготовка' $authComplete = $false try { $base = 'https://ecpx.ru' $clientPin = '1b8ef13c3f7a36a65fdc0a2e0327876050b32f5d16f4f5c30d8e5398542ac0db' $catalogPin = 'daac703fc0ffa814256d02693f472d65c51f24fad71af84533a829a2e94428b2' $signerPin = '' $caPin = '' # Shared by the HTTPS launcher and the protected system helper. Never changes trust. function Assert-ECPOrigin([string]$origin) { if ($origin -cnotmatch '^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?$') { throw 'ECP_ORIGIN_INVALID' } $u = [uri]$origin if ($u.UserInfo -or $u.Query -or $u.Fragment -or $u.AbsolutePath -ne '/' -or $u.Port -lt 1 -or $u.Port -gt 65535) { throw 'ECP_ORIGIN_INVALID' } } # The pinned byte check alone is not permission to execute. function Open-ECPPinnedClient([string]$path, [string]$pin) { if ($pin -notmatch '^[0-9a-f]{64}$') { throw 'ECP_RELEASE_PIN_INVALID' } $item = Get-Item -LiteralPath $path -Force if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'ECP_RELEASE_FILE_INVALID' } for ($parent = $item.Directory; $parent; $parent = $parent.Parent) { if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'ECP_RELEASE_FILE_INVALID' } } # Hold a read-only sharing handle until the child exits. No write or delete # sharing is permitted while the hash, signature and launch are performed. $stream = [IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read) try { if ($stream.Length -lt 2 -or $stream.Length -gt 33554432) { throw 'ECP_RELEASE_FILE_INVALID' } $h = [Security.Cryptography.SHA256]::Create() try { $actual = [BitConverter]::ToString($h.ComputeHash($stream)).Replace('-','') } finally { $h.Dispose() } if ($actual -ne $pin) { throw 'ECP_RELEASE_HASH_MISMATCH' } return $stream } catch { $stream.Dispose(); throw } } function Open-ECPVerifiedClient([string]$path, [string]$pin, [string]$signerPin, [bool]$localSigning, [bool]$lab) { if ($pin -notmatch '^[0-9a-f]{64}$' -or (-not $lab -and $signerPin -notmatch '^[0-9a-f]{64}$')) { throw 'ECP_RELEASE_PIN_INVALID' } if (-not $lab -and -not $localSigning) { throw 'ECP_RELEASE_MODE_UNSUPPORTED' } $stream = Open-ECPPinnedClient $path $pin try { if (-not $lab) { $sig = Get-AuthenticodeSignature -LiteralPath $path if ($sig.Status -eq 'HashMismatch') { throw 'ECP_RELEASE_SIGNATURE_DAMAGED' } if ($sig.Status -eq 'NotSigned') { throw 'ECP_RELEASE_UNSIGNED' } if (-not $sig.SignerCertificate) { if ($sig.Status -eq 'NotTrusted') { throw 'ECP_RELEASE_NOT_TRUSTED' } throw 'ECP_RELEASE_SIGNATURE_UNKNOWN' } $cert = $sig.SignerCertificate $h = [Security.Cryptography.SHA256]::Create() try { $actual = [BitConverter]::ToString($h.ComputeHash($cert.RawData)).Replace('-','') } finally { $h.Dispose() } if ($actual -ne $signerPin) { throw 'ECP_RELEASE_SIGNER_MISMATCH' } if ($cert.Subject -cne $cert.Issuer) { throw 'ECP_RELEASE_CERT_INVALID' } $now = [DateTime]::UtcNow if ($now -lt $cert.NotBefore.ToUniversalTime() -or $now -ge $cert.NotAfter.ToUniversalTime()) { throw 'ECP_RELEASE_CERT_EXPIRED' } $eku = @($cert.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.37' }) if ($eku.Count -ne 1 -or -not (@($eku[0].EnhancedKeyUsages | ForEach-Object { $_.Value }) -contains '1.3.6.1.5.5.7.3.3')) { throw 'ECP_RELEASE_CERT_INVALID' } # A matching pin is NOT a successful system trust decision. if ($sig.Status -eq 'NotTrusted') { throw 'ECP_RELEASE_NOT_TRUSTED' } if ($sig.Status -ne 'Valid') { throw 'ECP_RELEASE_SIGNATURE_UNKNOWN' } } return $stream } catch { $stream.Dispose(); throw } } function Get-ECPReleaseMessage([string]$code) { switch ($code) { 'ECP_ORIGIN_INVALID' { return 'Некорректный HTTPS-адрес сервера.' } 'ECP_RELEASE_CHANGED' { return 'Релиз изменился. Повторите исходную команду запуска.' } 'ECP_RELEASE_PIN_INVALID' { return 'Некорректные данные опубликованного релиза.' } 'ECP_RELEASE_FILE_INVALID' { return 'Недопустимый клиентский файл.' } 'ECP_CATALOG_HASH_MISMATCH' { return 'Ключ подписанного каталога не совпадает. Запуск запрещён.' } 'ECP_RELEASE_HASH_MISMATCH' { return 'Контрольная сумма клиента не совпадает. Запуск запрещён.' } 'ECP_RELEASE_SIGNATURE_DAMAGED' { return 'Подпись клиента повреждена. Запуск запрещён.' } 'ECP_RELEASE_UNSIGNED' { return 'Клиент не подписан. Запуск запрещён.' } 'ECP_RELEASE_SIGNER_MISMATCH' { return 'Сертификат издателя не совпадает с релизом. Запуск запрещён.' } 'ECP_RELEASE_CERT_INVALID' { return 'Некорректный сертификат Code Signing клиента.' } 'ECP_RELEASE_CERT_EXPIRED' { return 'Срок действия сертификата клиента не подтверждён.' } 'ECP_RELEASE_MODE_UNSUPPORTED' { return 'Устаревший режим публикации клиента. Используйте актуальный комплект релиза.' } 'ECP_RELEASE_NOT_TRUSTED' { return 'Windows не доверяет издателю клиента. Обратитесь к администратору.' } 'ECP_RELEASE_SIGNATURE_UNKNOWN' { return 'Windows не подтвердила подпись или доверие к издателю. Причину уточните у администратора.' } default { return $null } } } Assert-ECPOrigin $base $lab = $caPin -ne '' $localSigning = '0' -eq '1' $manual = '1' -eq '1' $releaseVersion = '0.63.0-preview.151' $releaseCommit = '164a5e60695f161df21cc5256b537d65962f32f5' if ($lab -and -not ([uri]$base).IsLoopback) { throw 'Lab requires loopback HTTPS' } $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal]::new($identity) $desktopRelaunch = $env:ECP_DESKTOP_RELAUNCH -eq '1' Remove-Item Env:ECP_DESKTOP_RELAUNCH -ErrorAction SilentlyContinue if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { if ($manual) { Write-Host 'Скачивание выполняется в обычном пользовательском PowerShell. Откройте его и повторите команду.'; return } if ($desktopRelaunch) { throw 'ECP: рабочий стол тоже запущен с повышенными правами. Войдите в обычную интерактивную учётную запись Windows.' } # Use the desktop Explorer automation object, not the elevated caller's token. # No password, token, or file from the elevated process crosses this boundary. $command = '$env:ECP_DESKTOP_RELAUNCH = ''1''; try { Invoke-RestMethod -UseBasicParsing -MaximumRedirection 0 -Uri ''' + $base + '/'' | Invoke-Expression } catch { Write-Host $_.Exception.Message -ForegroundColor Red; Read-Host ''Enter — закрыть окно'' | Out-Null }' $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) $shell = New-Object -ComObject Shell.Application $hwnd = 0 $desktop = $shell.Windows().FindWindowSW(0, 0, 8, [ref]$hwnd, 1) if (-not $desktop) { throw 'ECP: обычный рабочий стол Explorer недоступен. Откройте сеанс пользователя Windows.' } $ps = Join-Path $env:windir 'System32\WindowsPowerShell\v1.0\powershell.exe' $desktop.Document.Application.ShellExecute($ps, ('-NoProfile -NoLogo -EncodedCommand ' + $encoded), '', 'open', 1) Write-Host 'ECP: продолжите в открывшемся окне пользователя Windows.' return } # All credentials are entered only in the ordinary desktop user's process. # Never place credentials in arguments, environment variables, URL or files. function Get-ECPAuthError($record) { $body = $record.ErrorDetails.Message if (-not $body -and $record.Exception.Response) { try { $reader = [IO.StreamReader]::new($record.Exception.Response.GetResponseStream()) try { $body = $reader.ReadToEnd() } finally { $reader.Dispose() } } catch { } } try { $code = ($body | ConvertFrom-Json -ErrorAction Stop).code if ($code -in @('MFA_REQUIRED','AUTH_FAILED','RATE_LIMITED','UNAVAILABLE')) { return $code } } catch { } return 'AUTH_UNAVAILABLE' } function Invoke-ECPLogin($secret, $otpSecret) { $p = [IntPtr]::Zero $o = [IntPtr]::Zero $body = $null try { $p = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret) $data = @{ password = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($p) } if ($otpSecret) { $o = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($otpSecret) $data.otp = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($o) } $body = [Text.Encoding]::UTF8.GetBytes(($data | ConvertTo-Json -Compress)) try { return (Invoke-RestMethod -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 30 -Method Post -Uri ($base+'/api/v1/auth/login') -ContentType 'application/json; charset=utf-8' -Body $body) } catch { throw (Get-ECPAuthError $_) } } finally { if ($body) { [Array]::Clear($body, 0, $body.Length) } $data = $null if ($p -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($p) } if ($o -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($o) } } } function Get-ECPLoginMessage($code) { # BEGIN GENERATED AUTH MESSAGES $messages = @{ 'AUTH_FAILED' = 'Не удалось войти. Проверьте персональный пароль и код MFA' 'RATE_LIMITED' = 'Слишком много попыток. Повторите позже.' 'UNAVAILABLE' = 'Сервис временно недоступен.' 'AUTH_UNAVAILABLE' = 'Авторизация недоступна.' 'MFA_REQUIRED' = 'Требуется код MFA.' } # END GENERATED AUTH MESSAGES if (-not $messages.ContainsKey($code)) { $code = 'AUTH_UNAVAILABLE' } return ('ECP: '+$messages[$code]+' Скачивание не начато.') } if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { throw 'Профиль пользователя Windows недоступен.' } function Remove-ECPOwnedLeaf([string]$path) { for ($i=0; $i -lt 3; $i++) { try { if (-not (Test-Path -LiteralPath $path)) { return $true } $item = Get-Item -LiteralPath $path -Force if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return $false } Remove-Item -LiteralPath $path -Force -ErrorAction Stop return $true } catch { if ($i -lt 2) { Start-Sleep -Milliseconds 100 } } } return $false } function Remove-ECPLauncherFiles([string]$dir) { try { $info = Get-Item -LiteralPath $dir -Force if (-not $info.PSIsContainer -or ($info.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return $false } $allowed = @('ecp-client.exe','catalog-public.key','ca.pem','.lease') foreach ($item in @(Get-ChildItem -LiteralPath $dir -Force)) { if ($item.Name -cnotin $allowed -or $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return $false } } # Delete the executable first. A running Windows image is locked; # if it cannot be removed, preserve keys and retry at next launch. foreach ($name in @('ecp-client.exe','catalog-public.key','ca.pem')) { if (-not (Remove-ECPOwnedLeaf (Join-Path $dir $name))) { return $false } } return $true } catch { return $false } } function Complete-ECPLauncherCleanup([string]$dir) { if (-not (Remove-ECPOwnedLeaf (Join-Path $dir '.lease'))) { return } try { if (@(Get-ChildItem -LiteralPath $dir -Force).Count -eq 0) { [IO.Directory]::Delete($dir,$false) } } catch { Write-Warning ('Временная папка осталась: '+$dir) } } # Only ordinary user's owned launch directories with our exclusive lease. # A previous version without a lease is not automatically reclaimed. try { $local = Get-Item -LiteralPath $env:LOCALAPPDATA -Force if (-not ($local.Attributes -band [IO.FileAttributes]::ReparsePoint)) { foreach ($oldHandoff in @(Get-ChildItem -LiteralPath $env:LOCALAPPDATA -File -Force | Where-Object { $_.Name -cmatch '^ECPSetup-handoff-[0-9a-f]{32}\.json$' -and $_.LastWriteTimeUtc -lt [DateTime]::UtcNow.AddDays(-1) })) { [void](Remove-ECPOwnedLeaf $oldHandoff.FullName) } foreach ($old in @(Get-ChildItem -LiteralPath $env:LOCALAPPDATA -Directory -Force | Where-Object { $_.Name -cmatch '^ECPSetup-once-[0-9a-f]{32}$' -and $_.LastWriteTimeUtc -lt [DateTime]::UtcNow.AddDays(-1) })) { if ($old.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue } $oldLease = $null; $clean = $false try { $leaseItem = Get-Item -LiteralPath (Join-Path $old.FullName '.lease') -Force if ($leaseItem.PSIsContainer -or ($leaseItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue } $oldLease = [IO.File]::Open($leaseItem.FullName,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None) $clean = Remove-ECPLauncherFiles $old.FullName } catch { } finally { if ($oldLease) { $oldLease.Dispose() } } if ($clean) { Complete-ECPLauncherCleanup $old.FullName } } } } catch { Write-Warning 'Не удалось проверить старые временные папки ECP.' } $prefix = if ($manual) { 'ECPSetup-download-' } else { 'ECPSetup-once-' } $root = Join-Path $env:LOCALAPPDATA ($prefix + [guid]::NewGuid().ToString('N')) $manualSaved = $false $exe = Join-Path $root 'ecp-client.exe' $key = Join-Path $root 'catalog-public.key' $ca = Join-Path $root 'ca.pem' $headers = $null $pipe = $null $process = $null $ticketBytes = $null $delivered = $false $lease = $null $rootCreated = $false $exeLock = $null try { $stage = 'Авторизация' Write-Host 'ECP Setup | Авторизация' -ForegroundColor Cyan $secret = Read-Host 'Пароль оператора' -AsSecureString $otpSecret = $null try { if ($secret.Length -eq 0) { throw 'ECP: пароль не введён.' } try { $login = Invoke-ECPLogin $secret $null } catch { if ($_.Exception.Message -ne 'MFA_REQUIRED') { throw (Get-ECPLoginMessage $_.Exception.Message) } $otpSecret = Read-Host 'Код MFA' -AsSecureString try { $login = Invoke-ECPLogin $secret $otpSecret } catch { throw (Get-ECPLoginMessage $_.Exception.Message) } } if ($login.access_token -notmatch '^[A-Za-z0-9_-]{43}$' -or $login.role -ne 'operator') { throw 'ECP: требуется действующая сессия оператора.' } $headers = @{ Authorization = ('Bearer '+$login.access_token); 'X-ECP-Client-SHA256' = $clientPin.ToLowerInvariant() } } finally { $login = $null if ($secret) { $secret.Dispose() } if ($otpSecret) { $otpSecret.Dispose() } } $authComplete = $true $stage = 'Скачивание клиента' Write-Host 'Авторизация выполнена. Скачивание клиента...' -ForegroundColor Green $local = Get-Item -LiteralPath $env:LOCALAPPDATA -Force if (-not $local.PSIsContainer -or ($local.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'ECP_RELEASE_FILE_INVALID' } New-Item -ItemType Directory -Path $root -ErrorAction Stop | Out-Null $rootCreated = $true $lease = [IO.File]::Open((Join-Path $root '.lease'),[IO.FileMode]::CreateNew,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None) Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 120 -Headers $headers -Uri ($base+'/bootstrap/windows/amd64') -OutFile $exe $stage = 'Проверка клиентского файла' if ($manual) { # Preserve the Internet Zone mark; failure to set it aborts delivery. Set-Content -LiteralPath $exe -Stream Zone.Identifier -Value "[ZoneTransfer]`r`nZoneId=3" -Encoding ASCII $exeLock = Open-ECPPinnedClient $exe $clientPin $sig = Get-AuthenticodeSignature -LiteralPath $exe if ($sig.Status -eq 'HashMismatch') { throw 'ECP_RELEASE_SIGNATURE_DAMAGED' } Write-Host ('Authenticode (Windows): ' + $sig.Status) } else { $exeLock = Open-ECPVerifiedClient $exe $clientPin $signerPin $localSigning $lab } $sha = [Security.Cryptography.SHA256]::Create() try { $namespace = [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($base+'|'+$catalogPin.ToLowerInvariant()))).Replace('-','').ToLowerInvariant() } finally { $sha.Dispose() } $stage = 'Получение ключа каталога' Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 30 -Headers $headers -Uri ($base+'/bootstrap/catalog-key') -OutFile $key if ((Get-Item -LiteralPath $key).Length -ne 32 -or (Get-FileHash -Algorithm SHA256 -LiteralPath $key).Hash -ne $catalogPin) { throw 'Ключ подписанного каталога не совпадает.' } $sessionHome = Join-Path $env:LOCALAPPDATA ('ECPSetup\sessions\'+$namespace) if ($manual) { # No automatic launch, no RunAs, no handoff ticket on disk. # The operator starts the downloaded client separately and signs in again. $manualArgs = @('--server',$base,'--catalog-key',$key,'--catalog-key-sha256',$catalogPin.ToLowerInvariant(),'--home',$sessionHome,'--one-shot','--ui','tui','--remote-auth','--ca=','--release-sha256',$clientPin.ToLowerInvariant(),'--manual-account-sid',$identity.User.Value) if ($localSigning) { $manualArgs += @('--release-local-signing','--release-signer-sha256',$signerPin.ToLowerInvariant()) } else { $manualArgs += '--release-unsigned' } foreach ($arg in $manualArgs) { if ($arg.Contains('"') -or $arg.EndsWith('\')) { throw 'ECP: недопустимый аргумент запуска.' } } $quoted = ($manualArgs | ForEach-Object { '"'+$_+'"' }) -join ' ' $manualSaved = $true Write-Host ('Источник: GitHub CI / commit '+$releaseCommit) Write-Host ('Версия: '+$releaseVersion) Write-Host ('SHA-256: '+$clientPin) if ($localSigning) { Write-Host 'Локальная самоподпись не означает публичного доверия Windows.' } else { Write-Host 'Клиент без встроенной подписи. Автоматический запуск отключён.' -ForegroundColor Yellow } Write-Host ('Файл: '+$exe) Write-Host 'Перед ручным запуском сравните SHA-256 с указанным выше; не отключайте защиту Windows.' Write-Host ("Get-FileHash -Algorithm SHA256 -LiteralPath '"+$exe.Replace("'","''")+"'") Write-Host 'Если файл не повреждён и запуск разрешён политикой, используйте следующую команду:' Write-Host ("Start-Process -FilePath '"+$exe.Replace("'","''")+"' -ArgumentList '"+$quoted.Replace("'","''")+"'") Write-Host 'Потребуется повторный вход. Системные действия требуют отдельного штатного повышения прав; автоматический помощник здесь не используется.' Write-Host 'Для системной установки используйте ту же ручную команду в повышенном PowerShell той же учётной записи, добавив --allow-system-install к ArgumentList. Не переносите пользовательский MSI в чужой профиль.' Write-Host 'После перезагрузки повторите ручной запуск, войдите и откройте историю операций. Не повторяйте неизвестный результат вслепую.' Write-Host ('После завершения клиента удалите только скачанную папку: '+$root) Write-Host 'Журнал истории в ECPSetup\sessions сохраняется. Не удаляйте его для очистки дистрибутива.' return } $clientArgs = @('--server',$base,'--catalog-key',$key,'--catalog-key-sha256',$catalogPin.ToLowerInvariant(),'--home',$sessionHome,'--one-shot','--ui','tui','--remote-auth','--auto-uac') if ($lab) { Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 30 -Headers $headers -Uri ($base+'/bootstrap/ca') -OutFile $ca if ((Get-FileHash -Algorithm SHA256 -LiteralPath $ca).Hash -ne $caPin) { throw 'Контрольная сумма лабораторного сертификата не совпадает.' } $clientArgs += @('--ca',$ca,'--ca-sha256',$caPin.ToLowerInvariant()) } else { $clientArgs += @('--ca=','--release-sha256',$clientPin.ToLowerInvariant(),'--release-signer-sha256',$signerPin.ToLowerInvariant()) if ($localSigning) { $clientArgs += '--release-local-signing' } } # Current-user-only local named pipe; verify BOTH process identities. # Only the random pipe identifier and parent PID travel in arguments. $stage = 'Подготовка канала авторизации' if (-not ('ECPBootstrap.PipeNative' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace ECPBootstrap { public static class PipeNative { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint pid); } } '@ } $pipeName = 'ECPSetup-' + [guid]::NewGuid().ToString('N') if ($PSVersionTable.PSEdition -eq 'Core') { Add-Type -AssemblyName System.IO.Pipes.AccessControl } $acl = [IO.Pipes.PipeSecurity]::new() $acl.SetAccessRuleProtection($true, $false) $sid = $identity.User $network = [Security.Principal.SecurityIdentifier]::new([Security.Principal.WellKnownSidType]::NetworkSid, $null) $acl.AddAccessRule([IO.Pipes.PipeAccessRule]::new($network, [IO.Pipes.PipeAccessRights]::FullControl, [Security.AccessControl.AccessControlType]::Deny)) $acl.AddAccessRule([IO.Pipes.PipeAccessRule]::new($sid, [IO.Pipes.PipeAccessRights]::FullControl, [Security.AccessControl.AccessControlType]::Allow)) if ($PSVersionTable.PSEdition -eq 'Core') { $pipe = [IO.Pipes.NamedPipeServerStreamAcl]::Create($pipeName, [IO.Pipes.PipeDirection]::Out, 1, [IO.Pipes.PipeTransmissionMode]::Byte, [IO.Pipes.PipeOptions]::Asynchronous, 0, 4096, $acl, [IO.HandleInheritability]::None, [IO.Pipes.PipeAccessRights]0) } else { $pipe = [IO.Pipes.NamedPipeServerStream]::new($pipeName, [IO.Pipes.PipeDirection]::Out, 1, [IO.Pipes.PipeTransmissionMode]::Byte, [IO.Pipes.PipeOptions]::Asynchronous, 0, 4096, $acl) } $clientArgs += @('--bootstrap-pipe',$pipeName,'--bootstrap-parent',([string]$PID)) # Start-Process joins arguments; quote each Windows path/argument. None # of these values may contain a quote or end in a backslash. foreach ($arg in $clientArgs) { if ($arg.Contains('"') -or $arg.EndsWith('\')) { throw 'ECP: недопустимый аргумент запуска.' } } $quotedArgs = ($clientArgs | ForEach-Object { '"'+$_+'"' }) -join ' ' $wait = $pipe.WaitForConnectionAsync() $stage = 'Запуск клиента' Write-Host 'Клиент проверен. Запуск...' $process = Start-Process -FilePath $exe -ArgumentList $quotedArgs -NoNewWindow -PassThru if (-not $wait.Wait(25000)) { throw 'ECP: клиент не подключился к каналу авторизации.' } [uint32]$actualPID = 0 if (-not [ECPBootstrap.PipeNative]::GetNamedPipeClientProcessId($pipe.SafePipeHandle, [ref]$actualPID) -or $actualPID -ne $process.Id -or $process.HasExited) { throw 'ECP: неизвестный процесс подключился к каналу авторизации.' } try { $handoff = Invoke-RestMethod -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 15 -Method Post -Headers $headers -Uri ($base+'/api/v1/auth/bootstrap/issue') -ContentType 'application/json' -Body (@{client_sha256=$clientPin.ToLowerInvariant()} | ConvertTo-Json -Compress) if ($handoff.ticket -notmatch '^[A-Za-z0-9_-]{43}$') { throw 'Invalid handoff' } $ticketBytes = [Text.Encoding]::ASCII.GetBytes($handoff.ticket) $pipe.Write($ticketBytes,0,$ticketBytes.Length) $pipe.Flush() $delivered = $true } catch { if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 409) { throw 'ECP_RELEASE_CHANGED' } throw 'ECP: не удалось передать авторизацию. Повторите команду запуска.' } finally { $handoff = $null if ($ticketBytes) { [Array]::Clear($ticketBytes,0,$ticketBytes.Length) } } # Keep the pipe open until the child consumes the fixed-size message; # the child owns the console and the new session from here on. $stage = 'Выполнение клиента' $process.WaitForExit() $code = $process.ExitCode if (('0x{0:X8}' -f [int]$code) -in @('0x000000E1','0x000000E2','0x000004EC','0x00000241','0x80070241','0xC0000428','0xC0000906','0xC0000907','0x800700E1','0x800700E2','0x800704EC')) { throw ('ECP: Windows сообщила об отказе защиты, проверки целостности или политики безопасности. Код: '+$code+'. Не повторяйте запуск до проверки журнала.') } if ($code -eq 10) { throw 'ECP: операция остановлена после отказа защиты или аварийного завершения. Проверьте журнал. Не повторяйте запуск до проверки.' } if ($code -eq 1073741845) { throw 'ECP: аварийное завершение (0x40000015). Проверьте журнал Windows и антивируса. Не отключайте защиту. Перед повторным запуском обратитесь к администратору.' } if ($code -ne 0) { throw ('ECP завершился с кодом '+$code) } } finally { if ($pipe) { $pipe.Dispose() } # If handoff succeeded this token was already invalidated atomically. # Otherwise close the original session, including its refresh token. if ($headers) { try { Invoke-RestMethod -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 10 -Method Post -Headers $headers -Uri ($base+'/api/v1/auth/logout') | Out-Null } catch { } $headers.Clear() } $clientExited = $true if ($process) { if (-not $delivered -and -not $process.HasExited) { [void]$process.WaitForExit(10000) } $clientExited = $process.HasExited $process.Dispose() } if ($exeLock) { $exeLock.Dispose() } $clean = $false if ($rootCreated -and $lease -and $clientExited -and -not $manualSaved) { $clean = Remove-ECPLauncherFiles $root } if ($lease) { $lease.Dispose() } if ($manualSaved) { [void](Remove-ECPOwnedLeaf (Join-Path $root '.lease')) } elseif ($clean) { Complete-ECPLauncherCleanup $root } elseif ($rootCreated -and -not $lease -and -not $process) { try { $item = Get-Item -LiteralPath $root -Force if ($item.PSIsContainer -and -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -and @(Get-ChildItem -LiteralPath $root -Force).Count -eq 0) { [IO.Directory]::Delete($root,$false) } } catch { } } elseif ($rootCreated) { Write-Warning ('Временные файлы ECP сохранены для повторной очистки: '+$root) } } } catch { $record = $_ $kind = 'Причина не подтверждена. Проверьте доступность сервера и журналы защиты.' $failure = $record.Exception $nativeCode = $null while ($failure) { $hr = [long]$failure.HResult -band 0xffffffffL $native = if ($failure -is [ComponentModel.Win32Exception]) { $failure.NativeErrorCode } else { 0 } if ($native -in @(225,226) -or $hr -in @(0x800700e1L,0x800700e2L,0xc0000906L,0xc0000907L)) { $kind = 'Windows сообщила о блокировке или удалении файла защитой.'; $nativeCode = $hr; break } if ($native -eq 1260 -or $hr -eq 0x800704ecL) { $kind = 'Операция запрещена политикой безопасности Windows.'; $nativeCode = $hr; break } if ($native -eq 577 -or $hr -in @(0x80070241L,0xc0000428L)) { $kind = 'Windows не подтвердила целостность исполняемого файла.'; $nativeCode = $hr; break } if ($native -eq 1223 -or $hr -eq 0x800704c7L) { $kind = 'Повышение прав отменено.'; $nativeCode = $hr; break } $failure = $failure.InnerException } if ($stage -eq 'Авторизация' -and -not $authComplete) { $kind = 'Вход не выполнен. Скачивание не начато.' foreach ($authCode in @('AUTH_FAILED','RATE_LIMITED','UNAVAILABLE','AUTH_UNAVAILABLE','MFA_REQUIRED')) { $message = Get-ECPLoginMessage $authCode if ($record.Exception.Message -ceq $message) { $kind = $message; break } } if ($record.Exception.Message -eq 'ECP: пароль не введён.') { $kind = 'Пароль не введён. Скачивание не начато.' } } if ($null -eq $nativeCode) { if ($stage -eq 'Проверка клиентского файла') { $kind = 'Проверка файла не пройдена. Запуск запрещён.' } $releaseMessage = Get-ECPReleaseMessage $record.Exception.Message if ($releaseMessage) { $kind = $releaseMessage } if (-not $manual -and -not $lab -and $record.Exception.Message -in @('ECP_RELEASE_NOT_TRUSTED','ECP_RELEASE_UNSIGNED','ECP_RELEASE_SIGNATURE_UNKNOWN')) { Write-Host ("Отдельное скачивание без запуска (если разрешено политикой): irm '"+$base+"/?download=1'|iex") } } $releaseChanged = $record.Exception.Message -eq 'ECP_RELEASE_CHANGED' if ($record.Exception.Response) { $status = [int]$record.Exception.Response.StatusCode if ($status -eq 409) { $releaseChanged = $true } elseif ($status -in @(401,403,451)) { $kind = 'Сервер или политика отказали в получении файла (HTTP '+$status+').' } } if ($releaseChanged) { $kind = 'Релиз изменился. Операция не начата. Выполните исходную команду ещё раз.' } $normalOutcome = $releaseChanged if ($stage -eq 'Выполнение клиента' -and $null -ne $code) { $hexCode = '0x{0:X8}' -f [int]$code if ($hexCode -in @('0x000000E1','0x000000E2','0x800700E1','0x800700E2','0xC0000906','0xC0000907')) { $kind = 'Windows сообщила об обнаружении или удалении файла защитой.' } elseif ($hexCode -in @('0x000004EC','0x800704EC')) { $kind = 'Запуск запрещён политикой безопасности.' } elseif ($hexCode -in @('0x00000241','0x80070241','0xC0000428')) { $kind = 'Windows не подтвердила подпись или целостность файла.' } elseif ($code -eq 10 -or $hexCode -eq '0x40000015') { $kind = 'Операция остановлена. Причину уточните по локальному журналу.' } elseif ($code -eq 3) { $kind = 'Оператор отменил операцию.'; $normalOutcome = $true } elseif ($code -eq 4) { $kind = 'Остались ручные действия. Смотрите итог клиента.'; $normalOutcome = $true } elseif ($code -eq 5) { $kind = 'Требуется перезагрузка. Смотрите итог клиента.'; $normalOutcome = $true } elseif ($code -eq 2) { $kind = 'План выполнен не полностью. Смотрите итог и журнал клиента.'; $normalOutcome = $true } } Write-Host '' Write-Host 'ECP Setup | Запуск остановлен' -ForegroundColor Red Write-Host ('Этап: '+$stage) Write-Host $kind -ForegroundColor Yellow if ($null -ne $nativeCode) { Write-Host ('Код Windows: 0x{0:X8}' -f $nativeCode) } if (-not $normalOutcome -and $stage -ne 'Авторизация') { Write-Host 'Не отключайте защиту. Не повторяйте загрузку или запуск до проверки администратором.' } throw 'ECP Setup: операция не выполнена.' } }