diff --git a/.github/workflows/r06-no-admin-acceptance.yml b/.github/workflows/r06-no-admin-acceptance.yml new file mode 100644 index 000000000..fc4afbca7 --- /dev/null +++ b/.github/workflows/r06-no-admin-acceptance.yml @@ -0,0 +1,222 @@ +name: R06 No-Admin Packaged Acceptance + +on: + workflow_dispatch: + push: + branches: + - r06-gospel-no-admin-acceptance-0927-sol + paths: + - 'lanes/dev1/repair_overlay/packaging/run_no_admin_acceptance.ps1' + - 'lanes/dev1/repair_overlay/packaging/probe_packaged_startup.ps1' + - 'lanes/dev1/repair_overlay/tests/test_no_admin_acceptance_contract.py' + - '.github/workflows/r06-no-admin-acceptance.yml' + pull_request: + paths: + - 'lanes/dev1/repair_overlay/packaging/run_no_admin_acceptance.ps1' + - 'lanes/dev1/repair_overlay/packaging/probe_packaged_startup.ps1' + - 'lanes/dev1/repair_overlay/tests/test_no_admin_acceptance_contract.py' + - '.github/workflows/r06-no-admin-acceptance.yml' + +env: + DEV01_SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + DEV01_BASE_SOURCE_SHA256: 10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35 + PYTHONUTF8: '1' + +jobs: + no-admin-packaged-acceptance: + runs-on: windows-latest + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.DEV01_SOURCE_SHA }} + + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: Confirm exact source checkout + shell: pwsh + run: | + $actual = (git rev-parse HEAD).Trim() + if ($actual -ne $env:DEV01_SOURCE_SHA) { throw "Expected $env:DEV01_SOURCE_SHA, got $actual" } + + - name: Reconstruct and verify canonical FINALPREP02 source + shell: pwsh + run: | + $parts = Get-ChildItem release_inputs/dev1_finalprep02/part-*.b64 | Sort-Object Name + $b64 = ($parts | ForEach-Object { Get-Content $_.FullName -Raw }) -join '' + [IO.File]::WriteAllBytes('DEV1_R06_PLATFORM_SOURCE.zip', [Convert]::FromBase64String($b64)) + python lanes\dev1\verify_source_archive.py DEV1_R06_PLATFORM_SOURCE.zip $env:DEV01_BASE_SOURCE_SHA256 + if ($LASTEXITCODE -ne 0) { throw "DEV1 source archive verification failed with exit code $LASTEXITCODE" } + Expand-Archive DEV1_R06_PLATFORM_SOURCE.zip -DestinationPath . -Force + if (-not (Test-Path r06_platform -PathType Container)) { throw "Verified archive did not extract r06_platform" } + Copy-Item -Path lanes\dev1\repair_overlay\* -Destination r06_platform -Recurse -Force + + - name: Run no-admin contract regressions + shell: pwsh + run: | + python -m unittest discover -s lanes\dev1\repair_overlay\tests -p test_no_admin_acceptance_contract.py -v + if ($LASTEXITCODE -ne 0) { throw "No-admin contract regressions failed with exit code $LASTEXITCODE" } + + - name: Build exact packaged executable + shell: pwsh + run: | + ./r06_platform/packaging/build_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "Packaged build failed with exit code $LASTEXITCODE" } + if (-not (Test-Path r06_platform/dist/ScriptureArchive-R06-DEV01.exe -PathType Leaf)) { + throw "Expected packaged executable was not produced" + } + + - name: Prove harness fails closed under the admin runner token + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $exe = (Resolve-Path r06_platform/dist/ScriptureArchive-R06-DEV01.exe).Path + $hash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() + $resultPath = (Join-Path (Resolve-Path r06_platform/dist).Path "no_admin_admin_negative.json") + $harness = (Resolve-Path r06_platform/packaging/run_no_admin_acceptance.ps1).Path + $arguments = @( + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", "Bypass", + "-File", ('"' + $harness + '"'), + "-Executable", ('"' + $exe + '"'), + "-ExpectedSha256", $hash, + "-ProbeSeconds", "1", + "-OutputJson", ('"' + $resultPath + '"') + ) + $powershell = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe" + $negative = Start-Process -FilePath $powershell -ArgumentList $arguments -Wait -PassThru + if ($negative.ExitCode -ne 2) { throw "Admin negative control returned unexpected exit code $($negative.ExitCode)" } + $result = Get-Content -Raw -Encoding utf8 -LiteralPath $resultPath | ConvertFrom-Json + if ($result.status -ne "NO_ADMIN_ACCEPTANCE_FAIL") { throw "Admin negative control did not fail closed" } + if ($result.is_admin -ne $true) { throw "Admin negative control did not record is_admin=true" } + if ($result.failure -notlike "Standard-user token required*") { throw "Admin negative control failed for the wrong reason: $($result.failure)" } + Write-Output "NO_ADMIN_ADMIN_NEGATIVE_CONTROL_PASS" + + - name: Execute packaged acceptance as ephemeral standard user + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $user = "ScriptureNoAdmin" + $publicRoot = Join-Path $env:PUBLIC "ScriptureArchive-NoAdmin" + $resultPath = Join-Path $publicRoot "no_admin_acceptance.json" + $childLog = Join-Path $publicRoot "child-output.log" + $childError = Join-Path $publicRoot "child-error.log" + $password = [guid]::NewGuid().ToString("N") + "!Aa7" + $secure = ConvertTo-SecureString $password -AsPlainText -Force + $credential = New-Object System.Management.Automation.PSCredential(".\$user", $secure) + + try { + if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) { + Remove-LocalUser -Name $user + } + New-LocalUser -Name $user -Password $secure -PasswordNeverExpires -UserMayNotChangePassword | Out-Null + $administrators = Get-LocalGroup -SID "S-1-5-32-544" + $isAdminMember = @(Get-LocalGroupMember -Group $administrators.Name -ErrorAction Stop | Where-Object { + $_.Name -eq "$env:COMPUTERNAME\$user" -or $_.Name -eq ".\$user" + }).Count -gt 0 + if ($isAdminMember) { + throw "Standard-user account unexpectedly belongs to the Administrators group" + } + + New-Item -ItemType Directory -Force -Path $publicRoot | Out-Null + $acl = Get-Acl -LiteralPath $publicRoot + $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( + "$env:COMPUTERNAME\$user", + "Modify", + "ContainerInherit,ObjectInherit", + "None", + "Allow" + ) + $acl.SetAccessRule($rule) + Set-Acl -LiteralPath $publicRoot -AclObject $acl + + $buildExe = (Resolve-Path r06_platform/dist/ScriptureArchive-R06-DEV01.exe).Path + $hash = (Get-FileHash -LiteralPath $buildExe -Algorithm SHA256).Hash.ToLowerInvariant() + $exe = Join-Path $publicRoot "ScriptureArchive-R06-DEV01.exe" + $harness = Join-Path $publicRoot "run_no_admin_acceptance.ps1" + $startupProbe = Join-Path $publicRoot "probe_packaged_startup.ps1" + Copy-Item -LiteralPath $buildExe -Destination $exe -Force + Copy-Item r06_platform/packaging/run_no_admin_acceptance.ps1 $harness -Force + Copy-Item r06_platform/packaging/probe_packaged_startup.ps1 $startupProbe -Force + $publicHash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() + if ($publicHash -ne $hash) { throw "Public staging copy does not match the exact build artifact SHA-256" } + + $arguments = @( + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", "Bypass", + "-File", ('"' + $harness + '"'), + "-Executable", ('"' + $exe + '"'), + "-ExpectedSha256", $hash, + "-ProbeSeconds", "8", + "-OutputJson", ('"' + $resultPath + '"'), + "-StartupProbeScript", ('"' + $startupProbe + '"') + ) + $powershell = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe" + $child = Start-Process -FilePath $powershell -ArgumentList $arguments -Credential $credential -LoadUserProfile -WorkingDirectory $publicRoot -RedirectStandardOutput $childLog -RedirectStandardError $childError -PassThru + if (-not $child.WaitForExit(120000)) { + Stop-Process -Id $child.Id -Force -ErrorAction SilentlyContinue + throw "Standard-user acceptance process exceeded the 120-second bound" + } + $child.Refresh() + + if ($child.ExitCode -ne 0) { + if (Test-Path $childLog) { Get-Content $childLog } + if (Test-Path $childError) { Get-Content $childError } + throw "Standard-user acceptance process failed with exit code $($child.ExitCode)" + } + if (-not (Test-Path -LiteralPath $resultPath -PathType Leaf)) { + throw "Standard-user acceptance did not emit result JSON" + } + $result = Get-Content -Raw -Encoding utf8 -LiteralPath $resultPath | ConvertFrom-Json + if ($result.status -ne "NO_ADMIN_ACCEPTANCE_PASS") { throw "No-admin result status was $($result.status)" } + if ($result.is_admin -ne $false) { throw "Child acceptance token was not standard-user" } + if (-not $result.identity_name -or -not $result.user_sid) { throw "Standard-user identity evidence is incomplete" } + if (-not $result.profile_sid_bound) { throw "Per-user state root was not bound to the child SID profile" } + if ($result.local_app_data_source -ne "HKLM_ProfileList_current_sid") { throw "Unexpected per-user state authority: $($result.local_app_data_source)" } + if (-not $result.per_user_state_writable) { throw "Per-user state write/readback was not proven" } + if (-not $result.webview2_detected) { throw "WebView2 was not detected in standard-user context" } + if (-not $result.unicode_spaced_path) { throw "Unicode + spaced per-user launch path was not proven" } + if (-not $result.process_started) { throw "Packaged process did not start under standard-user token" } + if (-not $result.survived_probe_window) { throw "Packaged process did not survive the standard-user probe window" } + if ($result.source_sha256 -ne $hash -or $result.copied_sha256 -ne $hash) { throw "No-admin evidence SHA-256 does not match the exact build artifact" } + Write-Output "NO_ADMIN_ACCEPTANCE_PASS user=$user sha256=$($result.source_sha256)" + } + finally { + if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) { + Remove-LocalUser -Name $user + } + } + + - name: Collect no-admin evidence inside workspace + if: always() + shell: pwsh + run: | + $destination = Join-Path $PWD "no_admin_evidence" + New-Item -ItemType Directory -Force -Path $destination | Out-Null + $sources = @( + @{ Path = "C:\Users\Public\ScriptureArchive-NoAdmin\no_admin_acceptance.json"; Name = "no_admin_acceptance.json" }, + @{ Path = "C:\Users\Public\ScriptureArchive-NoAdmin\child-output.log"; Name = "child-output.log" }, + @{ Path = "C:\Users\Public\ScriptureArchive-NoAdmin\child-error.log"; Name = "child-error.log" }, + @{ Path = (Join-Path $PWD "r06_platform\dist\no_admin_admin_negative.json"); Name = "no_admin_admin_negative.json" } + ) + foreach ($source in $sources) { + if (Test-Path -LiteralPath $source.Path -PathType Leaf) { + Copy-Item -LiteralPath $source.Path -Destination (Join-Path $destination $source.Name) -Force + } + } + Get-ChildItem -LiteralPath $destination -File -ErrorAction SilentlyContinue | ForEach-Object { + Write-Output ("NO_ADMIN_EVIDENCE_STAGED " + $_.Name) + } + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: R06-no-admin-packaged-acceptance + path: no_admin_evidence + if-no-files-found: warn diff --git a/lanes/dev1/repair_overlay/frontend/application-update.js b/lanes/dev1/repair_overlay/frontend/application-update.js index 32a4791ea..be2fbdf22 100644 --- a/lanes/dev1/repair_overlay/frontend/application-update.js +++ b/lanes/dev1/repair_overlay/frontend/application-update.js @@ -30,6 +30,16 @@ function clearDetails(){ $('application-update-details')?.replaceChildren(); } +function authenticityLabel(status){ + if(status==='same_publisher_authenticode_verified'){ + return 'Підтверджено: чинний Authenticode; сертифікат видавця збігається з поточною програмою'; + } + if(status==='not_proven_by_local_hash_verification'){ + return 'Не підтверджено: локальний SHA-256 не доводить автентичність підпису або походження'; + } + return 'Не підтверджено: невідомий статус автентичності'; +} + function renderDetails(data){ const host=$('application-update-details'); if(!host)return; @@ -44,7 +54,7 @@ function renderDetails(data){ ['Файл пакета',data.artifact_name], ['Розмір',Number.isFinite(Number(data.artifact_size))?`${data.artifact_size} байт`:'—'], ['SHA-256',data.artifact_sha256], - ['Автентичність',data.authenticity==='not_proven_by_local_hash_verification'?'Локальний hash не доводить автентичність підпису/джерела':'—'], + ['Автентичність',authenticityLabel(data.authenticity)], ]; for(const [label,value] of rows){ const dt=document.createElement('dt');dt.textContent=label; @@ -75,7 +85,10 @@ async function selectAndVerify(){ const data=await invokeNativeVerification(); if(data.verified===true&&data.status==='verified'){ renderDetails(data); - announce(`Локальний пакет перевірено: ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'}. Нічого не встановлено.`); + const publisherStatus=data.authenticity==='same_publisher_authenticode_verified' + ?' Видавець підтверджений чинним Authenticode і збігається з поточною програмою.' + :' Автентичність видавця не підтверджена.'; + announce(`Локальний пакет перевірено: ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'}.${publisherStatus} Нічого не встановлено.`); }else if(data.status==='cancelled'){ announce(data.message||'Вибір локального оновлення скасовано.'); }else{ diff --git a/lanes/dev1/repair_overlay/packaging/run_no_admin_acceptance.ps1 b/lanes/dev1/repair_overlay/packaging/run_no_admin_acceptance.ps1 new file mode 100644 index 000000000..1960a08af --- /dev/null +++ b/lanes/dev1/repair_overlay/packaging/run_no_admin_acceptance.ps1 @@ -0,0 +1,278 @@ +param( + [Parameter(Mandatory = $true)] + [string]$Executable, + [string]$ExpectedSha256 = "", + [int]$ProbeSeconds = 8, + [string]$OutputJson = "", + [string]$StartupProbeScript = "" +) + +$ErrorActionPreference = "Stop" + +function Get-Sha256Hex { + param([Parameter(Mandatory = $true)][string]$Path) + + $resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path + $stream = [IO.File]::Open($resolved, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) + try { + $sha = [System.Security.Cryptography.SHA256]::Create() + try { + $digest = $sha.ComputeHash($stream) + } + finally { + $sha.Dispose() + } + } + finally { + $stream.Dispose() + } + return ([BitConverter]::ToString($digest)).Replace("-", "").ToLowerInvariant() +} + +function Test-IsAdministrator { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($identity) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +function Resolve-CurrentUserLocalAppData { + param([Security.Principal.WindowsIdentity]$Identity) + + if (-not $Identity -or -not $Identity.User) { + throw "Current Windows identity does not expose a user SID." + } + $sid = $Identity.User.Value + $profileKey = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid" + if (-not (Test-Path -LiteralPath $profileKey)) { + throw "Current standard-user SID is not bound to a Windows profile." + } + + $profileRaw = [string](Get-ItemProperty -LiteralPath $profileKey -Name ProfileImagePath -ErrorAction Stop).ProfileImagePath + if (-not $profileRaw) { + throw "Current standard-user profile does not expose ProfileImagePath." + } + $profilePath = [Environment]::ExpandEnvironmentVariables($profileRaw) + if (-not [IO.Path]::IsPathRooted($profilePath)) { + throw "Current standard-user ProfileImagePath is not absolute." + } + $profilePath = [IO.Path]::GetFullPath($profilePath).TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + if (-not (Test-Path -LiteralPath $profilePath -PathType Container)) { + throw "Current standard-user profile directory is unavailable." + } + + $localAppData = Join-Path $profilePath "AppData\Local" + New-Item -ItemType Directory -Force -Path $localAppData | Out-Null + $localAppData = (Resolve-Path -LiteralPath $localAppData -ErrorAction Stop).Path + $prefix = $profilePath + [IO.Path]::DirectorySeparatorChar + if (-not $localAppData.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "Resolved LocalApplicationData escaped the current SID-bound profile." + } + + return [ordered]@{ + profile_path = $profilePath + local_app_data = $localAppData + profile_sid_bound = $true + } +} + +function Get-WebView2Candidates { + param([string]$LocalAppData) + + $matches = @() + $registryRoots = @( + "HKCU:\SOFTWARE\Microsoft\EdgeUpdate\Clients", + "HKLM:\SOFTWARE\Microsoft\EdgeUpdate\Clients", + "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients" + ) + foreach ($root in $registryRoots) { + if (-not (Test-Path -LiteralPath $root)) { continue } + foreach ($child in Get-ChildItem -LiteralPath $root -ErrorAction SilentlyContinue) { + try { + $props = Get-ItemProperty -LiteralPath $child.PSPath -ErrorAction Stop + $name = [string]$props.name + if ($name -and $name.ToLowerInvariant().Contains("webview2")) { + $matches += [ordered]@{ + source = "registry" + location = $child.Name + name = $name + version = [string]$props.pv + } + } + } + catch { } + } + } + + foreach ($root in @($env:ProgramFiles, ${env:ProgramFiles(x86)}, $LocalAppData)) { + if (-not $root) { continue } + $path = Join-Path $root "Microsoft\EdgeWebView\Application" + if (Test-Path -LiteralPath $path -PathType Container) { + $versions = @(Get-ChildItem -LiteralPath $path -Directory -ErrorAction SilentlyContinue | Sort-Object Name -Descending) + $matches += [ordered]@{ + source = "filesystem" + location = $path + name = "Microsoft Edge WebView2 Runtime" + version = $(if ($versions.Count) { $versions[0].Name } else { "present" }) + } + } + } + return @($matches) +} + +function Write-AcceptanceResult { + param([System.Collections.IDictionary]$Payload) + $json = $Payload | ConvertTo-Json -Depth 8 + Write-Output $json + if ($OutputJson) { + $parent = Split-Path -Parent $OutputJson + if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null } + $json | Set-Content -Encoding utf8 -LiteralPath $OutputJson + } +} + +$result = [ordered]@{ + schema = "R06_NO_ADMIN_ACCEPTANCE_v1" + started_utc = (Get-Date).ToUniversalTime().ToString("o") + user = [Environment]::UserName + identity_name = $null + user_sid = $null + is_admin = $null + profile_image_path = $null + local_app_data = $null + local_app_data_source = $null + profile_sid_bound = $false + per_user_state_writable = $false + webview2_detected = $false + webview2_candidate_count = 0 + source_artifact = $null + source_sha256 = $null + expected_sha256 = $(if ($ExpectedSha256) { $ExpectedSha256.ToLowerInvariant() } else { $null }) + copied_artifact = $null + copied_sha256 = $null + unicode_spaced_path = $false + process_started = $false + survived_probe_window = $false + process_exit_code = $null + status = "RUNNING" + not_proven = @( + "human NVDA acceptance", + "complete functional WebView UI acceptance", + "visual quality acceptance", + "source/theological audit" + ) + failure = $null +} + +$exitCode = 0 +$writeProbe = $null + +try { + if ($env:OS -ne "Windows_NT") { + throw "No-admin packaged acceptance requires Windows." + } + + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $result.identity_name = $identity.Name + $result.user_sid = $identity.User.Value + $result.is_admin = [bool](Test-IsAdministrator) + if ($result.is_admin) { + throw "Standard-user token required: current process is elevated/administrator." + } + + $profile = Resolve-CurrentUserLocalAppData -Identity $identity + $localAppData = [string]$profile.local_app_data + $result.profile_image_path = [string]$profile.profile_path + $result.local_app_data = $localAppData + $result.local_app_data_source = "HKLM_ProfileList_current_sid" + $result.profile_sid_bound = [bool]$profile.profile_sid_bound + + $source = (Resolve-Path -LiteralPath $Executable -ErrorAction Stop).Path + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { + throw "Packaged executable is not a regular file." + } + $result.source_artifact = $source + $sourceHash = Get-Sha256Hex -Path $source + $result.source_sha256 = $sourceHash + + if ($ExpectedSha256) { + $expected = $ExpectedSha256.Trim().ToLowerInvariant() + if ($expected -notmatch "^[0-9a-f]{64}$") { + throw "Expected SHA-256 must be exactly 64 hexadecimal characters." + } + if ($sourceHash -ne $expected) { + throw "Source artifact SHA-256 does not match the expected build identity." + } + } + + $stateRoot = Join-Path $localAppData "ScriptureArchive" + $diagnosticsRoot = Join-Path $stateRoot "diagnostics" + New-Item -ItemType Directory -Force -Path $diagnosticsRoot | Out-Null + $writeProbe = Join-Path $diagnosticsRoot ("no-admin-write-probe-" + $PID + ".tmp") + [IO.File]::WriteAllText($writeProbe, "scripture-archive-no-admin-write-probe", (New-Object Text.UTF8Encoding($false))) + if ([IO.File]::ReadAllText($writeProbe, [Text.Encoding]::UTF8) -ne "scripture-archive-no-admin-write-probe") { + throw "Per-user state write/readback probe mismatch." + } + $result.per_user_state_writable = $true + + $webviewCandidates = @(Get-WebView2Candidates -LocalAppData $localAppData) + $result.webview2_candidate_count = $webviewCandidates.Count + $result.webview2_detected = $webviewCandidates.Count -gt 0 + if (-not $result.webview2_detected) { + throw "Edge WebView2 Runtime was not detected for the standard-user context." + } + + $acceptanceRoot = Join-Path $stateRoot "acceptance\Архів Писання Standard User" + New-Item -ItemType Directory -Force -Path $acceptanceRoot | Out-Null + $target = Join-Path $acceptanceRoot ([IO.Path]::GetFileName($source)) + Copy-Item -LiteralPath $source -Destination $target -Force + $target = (Resolve-Path -LiteralPath $target).Path + $result.copied_artifact = $target + $result.unicode_spaced_path = ($target.Contains(" ") -and ($target.ToCharArray() | Where-Object { [int]$_ -gt 127 }).Count -gt 0) + if (-not $result.unicode_spaced_path) { + throw "Acceptance copy did not land in the required Unicode + spaced per-user path." + } + + $copyHash = Get-Sha256Hex -Path $target + $result.copied_sha256 = $copyHash + if ($copyHash -ne $sourceHash) { + throw "Copied artifact SHA-256 differs from the source artifact." + } + + if (-not $StartupProbeScript) { + $StartupProbeScript = Join-Path $PSScriptRoot "probe_packaged_startup.ps1" + } + $probeScript = (Resolve-Path -LiteralPath $StartupProbeScript -ErrorAction Stop).Path + $probeJson = Join-Path $acceptanceRoot "packaged_startup_probe.json" + & $probeScript -Executable $target -ProbeSeconds $ProbeSeconds -OutputJson $probeJson + if (-not (Test-Path -LiteralPath $probeJson -PathType Leaf)) { + throw "Packaged startup probe did not emit its evidence JSON." + } + $probe = Get-Content -Raw -Encoding utf8 -LiteralPath $probeJson | ConvertFrom-Json + $result.process_started = [bool]$probe.process_started + $result.survived_probe_window = [bool]$probe.survived_probe_window + $result.process_exit_code = $probe.exit_code + if (-not $result.process_started) { + throw "Packaged process did not start under the standard-user token." + } + if (-not $result.survived_probe_window) { + if ($null -ne $result.process_exit_code -and [int]$result.process_exit_code -ne 0) { + throw "Packaged process exited non-zero during the no-admin probe." + } + throw "Packaged process did not remain alive for the full no-admin probe window." + } + + $result.status = "NO_ADMIN_ACCEPTANCE_PASS" +} +catch { + $result.status = "NO_ADMIN_ACCEPTANCE_FAIL" + $result.failure = $_.Exception.Message + $exitCode = 2 +} +finally { + if ($writeProbe) { + Remove-Item -LiteralPath $writeProbe -Force -ErrorAction SilentlyContinue + } + Write-AcceptanceResult -Payload $result +} + +exit $exitCode diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/authenticode.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/authenticode.py new file mode 100644 index 000000000..582ca602f --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/authenticode.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import ctypes +import json +import os +from pathlib import Path +import stat +import subprocess +from typing import Any + +_MAX_OUTPUT_BYTES = 8192 +_THUMBPRINT_HEX_LEN = 40 + +_POWERSHELL_SCRIPT = r""" +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) +$paths = @($env:SCRIPTURE_AUTH_CURRENT, $env:SCRIPTURE_AUTH_CANDIDATE) +$result = @() +foreach ($path in $paths) { + $signature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $path + $thumbprint = $null + if ($null -ne $signature.SignerCertificate) { + $thumbprint = [string]$signature.SignerCertificate.Thumbprint + } + $result += [pscustomobject]@{ + status = [string]$signature.Status + thumbprint = $thumbprint + } +} +$result | ConvertTo-Json -Compress +""".strip() + + +def verify_same_publisher_authenticode( + current_executable: str | os.PathLike[str], + candidate_artifact: str | os.PathLike[str], +) -> bool: + """Return True only when Windows validates both files to the same signer. + + This is an authenticity signal only. It does not install, execute, replace, or + trust a candidate by path. Any later update mutation must re-bind the exact + staged bytes to the verified manifest digest and repeat authenticity checks. + """ + + if os.name != "nt": + return False + + # Preserve concrete Path objects supplied by the native layer instead of + # re-dispatching pathlib's platform factory after the Windows guard. This is + # behaviorally identical on Windows and keeps cross-platform qualification + # from corrupting pathlib by mocking the process-wide os.name singleton. + current = current_executable if isinstance(current_executable, Path) else Path(current_executable) + candidate = candidate_artifact if isinstance(candidate_artifact, Path) else Path(candidate_artifact) + if not _regular_non_symlink(current) or not _regular_non_symlink(candidate): + return False + + system_directory = _windows_system_directory() + if system_directory is None: + return False + powershell_root = system_directory / "WindowsPowerShell" / "v1.0" + powershell = powershell_root / "powershell.exe" + modules = powershell_root / "Modules" + if not _regular_non_symlink(powershell) or not modules.is_dir(): + return False + + environment = os.environ.copy() + # Do not let inherited user/process module search paths redirect the + # module-qualified Authenticode command away from the system module tree. + environment["PSModulePath"] = str(modules) + environment["SCRIPTURE_AUTH_CURRENT"] = str(current.resolve()) + environment["SCRIPTURE_AUTH_CANDIDATE"] = str(candidate.resolve()) + try: + completed = subprocess.run( + [ + str(powershell), + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-Command", + _POWERSHELL_SCRIPT, + ], + env=environment, + capture_output=True, + text=True, + encoding="utf-8", + errors="strict", + timeout=10, + check=False, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except (OSError, subprocess.SubprocessError, UnicodeError): + return False + + if completed.returncode != 0: + return False + encoded = completed.stdout.encode("utf-8", errors="strict") + if not encoded or len(encoded) > _MAX_OUTPUT_BYTES: + return False + return _same_valid_signer_payload(completed.stdout) + + +def _windows_system_directory() -> Path | None: + """Resolve System32 from Win32 itself, never from inherited environment.""" + + if os.name != "nt": + return None + try: + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + get_system_directory = kernel32.GetSystemDirectoryW + get_system_directory.argtypes = [ + ctypes.POINTER(ctypes.c_wchar), + ctypes.c_uint, + ] + get_system_directory.restype = ctypes.c_uint + capacity = 32768 + buffer = ctypes.create_unicode_buffer(capacity) + length = int(get_system_directory(buffer, capacity)) + except (AttributeError, OSError, TypeError, ValueError): + return None + if length <= 0 or length >= capacity or not buffer.value: + return None + system_directory = Path(buffer.value) + if not system_directory.is_absolute(): + return None + return system_directory + + +def _regular_non_symlink(path: Path) -> bool: + try: + metadata = path.lstat() + except OSError: + return False + return not stat.S_ISLNK(metadata.st_mode) and stat.S_ISREG(metadata.st_mode) + + +def _same_valid_signer_payload(payload: str) -> bool: + """Parse the bounded PowerShell result without trusting extra fields.""" + + try: + value: Any = json.loads(payload) + except (TypeError, ValueError): + return False + if not isinstance(value, list) or len(value) != 2: + return False + + thumbprints: list[str] = [] + for record in value: + if not isinstance(record, dict) or set(record) != {"status", "thumbprint"}: + return False + if record.get("status") != "Valid": + return False + thumbprint = record.get("thumbprint") + if not isinstance(thumbprint, str): + return False + normalized = thumbprint.strip().upper() + if len(normalized) != _THUMBPRINT_HEX_LEN or any( + char not in "0123456789ABCDEF" for char in normalized + ): + return False + thumbprints.append(normalized) + return thumbprints[0] == thumbprints[1] diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py index dfaf83660..62e725451 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py @@ -5,6 +5,9 @@ from pathlib import Path from typing import Any, Callable +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) from scripture_archive_platform.transport.contracts import ( error_response, ok_response, @@ -75,6 +78,8 @@ class NativeApplicationUpdateLayer: All ordinary commands remain owned by the wrapped application. The browser can request update selection only with an empty payload; local paths are created by the native picker and are never serialized into a successful or failed response. + Hash/size verification remains independent from the optional fail-closed Windows + same-publisher Authenticode signal. Nothing is installed or executed here. """ def __init__( @@ -84,11 +89,17 @@ def __init__( selector: Callable[[], tuple[str, str] | None], *, current_version: str, + authenticity_verifier: Callable[[Path], bool] | None = None, ) -> None: self._app = app self._repo_root = Path(repo_root).resolve() self._selector = selector self._current_version = current_version + self._authenticity_verifier = ( + authenticity_verifier + if authenticity_verifier is not None + else self._default_authenticity_verifier + ) def handle(self, request: Any) -> dict[str, Any]: if not isinstance(request, dict) or request.get("command") != UPDATE_COMMAND: @@ -123,6 +134,24 @@ def handle(self, request: Any) -> dict[str, Any]: artifact_path, current_version=self._current_version, ) + + authenticity_verified = False + try: + authenticity_verified = bool(self._authenticity_verifier(artifact_path)) + except Exception: + authenticity_verified = False + authenticity = "not_proven_by_local_hash_verification" + if authenticity_verified: + # Bind the positive signature result to bytes that still satisfy the + # exact manifest after OS signature inspection. Failure here aborts + # the whole request rather than returning stale `verified=true`. + verified = verify_local_update( + manifest, + artifact_path, + current_version=self._current_version, + ) + authenticity = "same_publisher_authenticode_verified" + return ok_response( rid, { @@ -136,7 +165,7 @@ def handle(self, request: Any) -> dict[str, Any]: "artifact_name": verified.artifact_name, "artifact_size": verified.artifact_size, "artifact_sha256": verified.artifact_sha256, - "authenticity": "not_proven_by_local_hash_verification", + "authenticity": authenticity, }, ) except ValueError as exc: @@ -154,6 +183,9 @@ def handle(self, request: Any) -> dict[str, Any]: "Local application update verification failed closed.", ) + def _default_authenticity_verifier(self, candidate: Path) -> bool: + return verify_same_publisher_authenticode(Path(sys.executable), candidate) + def _load_update_core(self) -> tuple[Any, Any]: root_text = str(self._repo_root) if root_text not in sys.path: @@ -178,4 +210,4 @@ def _read_manifest_fail_closed(path: Path) -> bytes: after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) if before_identity != after_identity or len(payload) != before.st_size: raise ValueError("update manifest changed while being read") - return payload + return payload \ No newline at end of file diff --git a/lanes/dev1/repair_overlay/tests/test_no_admin_acceptance_contract.py b/lanes/dev1/repair_overlay/tests/test_no_admin_acceptance_contract.py new file mode 100644 index 000000000..180c73724 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_no_admin_acceptance_contract.py @@ -0,0 +1,118 @@ +from pathlib import Path +import unittest + + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] +PACKAGING = ROOT / "packaging" + + +def repository_root() -> Path: + for parent in FILE.parents: + workflow = parent / ".github" / "workflows" / "r06-no-admin-acceptance.yml" + if workflow.is_file(): + return parent + raise RuntimeError("repository root with no-admin workflow not found") + + +WORKFLOW = repository_root() / ".github" / "workflows" / "r06-no-admin-acceptance.yml" + + +class NoAdminAcceptanceContractTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.harness = (PACKAGING / "run_no_admin_acceptance.ps1").read_text(encoding="utf-8") + cls.probe = (PACKAGING / "probe_packaged_startup.ps1").read_text(encoding="utf-8") + cls.workflow = WORKFLOW.read_text(encoding="utf-8") + + def test_harness_refuses_admin_and_requires_real_standard_user_profile(self): + self.assertIn("Test-IsAdministrator", self.harness) + self.assertIn("WindowsBuiltInRole]::Administrator", self.harness) + self.assertIn("if ($result.is_admin)", self.harness) + self.assertIn("$result.identity_name = $identity.Name", self.harness) + self.assertIn("$result.user_sid = $identity.User.Value", self.harness) + self.assertIn("Standard-user token required", self.harness) + self.assertIn("Resolve-CurrentUserLocalAppData", self.harness) + self.assertIn("ProfileList\\$sid", self.harness) + self.assertIn("ProfileImagePath", self.harness) + self.assertIn("Resolved LocalApplicationData escaped the current SID-bound profile", self.harness) + self.assertIn('$result.local_app_data_source = "HKLM_ProfileList_current_sid"', self.harness) + self.assertIn("$result.profile_sid_bound = [bool]$profile.profile_sid_bound", self.harness) + self.assertIn("$result.local_app_data = $localAppData", self.harness) + self.assertIn("per_user_state_writable", self.harness) + self.assertIn('status = "NO_ADMIN_ACCEPTANCE_PASS"', self.harness) + self.assertIn('status = "NO_ADMIN_ACCEPTANCE_FAIL"', self.harness) + + def test_harness_binds_exact_artifact_and_unicode_spaced_per_user_copy(self): + self.assertIn("Get-Sha256Hex", self.harness) + self.assertIn("[System.Security.Cryptography.SHA256]::Create()", self.harness) + self.assertIn("Get-Sha256Hex -Path $source", self.harness) + self.assertIn("Get-Sha256Hex -Path $target", self.harness) + self.assertNotIn("Get-FileHash", self.harness) + self.assertIn("Source artifact SHA-256 does not match", self.harness) + self.assertIn("Copied artifact SHA-256 differs", self.harness) + self.assertIn("Архів Писання Standard User", self.harness) + self.assertIn("unicode_spaced_path", self.harness) + self.assertIn("Copy-Item -LiteralPath $source", self.harness) + self.assertIn("Get-FileHash -LiteralPath $buildExe -Algorithm SHA256", self.workflow) + self.assertIn("Public staging copy does not match the exact build artifact SHA-256", self.workflow) + self.assertIn("No-admin evidence SHA-256 does not match the exact build artifact", self.workflow) + + def test_harness_requires_webview2_and_real_packaged_startup(self): + self.assertIn("Get-WebView2Candidates", self.harness) + self.assertIn("Edge WebView2 Runtime was not detected", self.harness) + self.assertIn("probe_packaged_startup.ps1", self.harness) + self.assertIn("process_started", self.harness) + self.assertIn("survived_probe_window", self.harness) + self.assertIn("did not remain alive for the full no-admin probe window", self.harness) + self.assertIn("Packaged process did not start under the standard-user token", self.harness) + self.assertIn("Start-Process -FilePath $exe -PassThru", self.probe) + + def test_workflow_runs_harness_under_ephemeral_non_admin_credentials(self): + for token in ( + "New-LocalUser", + "Start-Process", + "-Credential $credential", + "-LoadUserProfile", + "run_no_admin_acceptance.ps1", + "NO_ADMIN_ACCEPTANCE_PASS", + "is_admin", + "Remove-LocalUser", + "WaitForExit(120000)", + "Standard-user acceptance process exceeded the 120-second bound", + "Standard-user identity evidence is incomplete", + "Per-user state root was not bound to the child SID profile", + 'HKLM_ProfileList_current_sid', + "NO_ADMIN_ADMIN_NEGATIVE_CONTROL_PASS", + "Admin negative control returned unexpected exit code", + "NO_ADMIN_ACCEPTANCE_FAIL", + "S-1-5-32-544", + "Standard-user account unexpectedly belongs to the Administrators group", + ): + self.assertIn(token, self.workflow) + self.assertNotIn("Add-LocalGroupMember", self.workflow) + self.assertNotIn("net localgroup administrators", self.workflow.lower()) + self.assertIn('if ($result.is_admin -ne $true)', self.workflow) + self.assertIn('if ($negative.ExitCode -ne 2)', self.workflow) + + def test_workflow_stages_evidence_inside_workspace_before_upload(self): + self.assertIn("Collect no-admin evidence inside workspace", self.workflow) + self.assertIn('$destination = Join-Path $PWD "no_admin_evidence"', self.workflow) + self.assertIn("NO_ADMIN_EVIDENCE_STAGED", self.workflow) + self.assertIn("path: no_admin_evidence", self.workflow) + upload_block = self.workflow.split("- uses: actions/upload-artifact@v4", 1)[1] + self.assertNotIn("C:\\Users\\Public", upload_block) + self.assertNotIn("r06_platform\\dist\\no_admin_admin_negative.json", upload_block) + + def test_workflow_does_not_echo_or_persist_generated_password(self): + self.assertIn("ConvertTo-SecureString", self.workflow) + self.assertNotIn("Write-Output $password", self.workflow) + self.assertNotIn("Write-Host $password", self.workflow) + self.assertNotIn("echo $password", self.workflow.lower()) + password_lines = "\n".join(line for line in self.workflow.splitlines() if "$password" in line) + self.assertNotIn("Set-Content", password_lines) + self.assertNotIn("Out-File", password_lines) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py index fbbe30ee5..83e2d9d98 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py @@ -1,9 +1,16 @@ import hashlib import json +import os import tempfile import unittest from pathlib import Path +from unittest import mock +from scripture_archive_platform.desktop_host.authenticode import ( + _same_valid_signer_payload, + _windows_system_directory, + verify_same_publisher_authenticode, +) from scripture_archive_platform.desktop_host.update_application import ( NativeApplicationUpdateLayer, NativeUpdateFileSelector, @@ -130,6 +137,60 @@ def test_non_update_commands_remain_owned_by_wrapped_application(self): self.assertEqual([request], self.base.calls) self.assertEqual(0, self.selection_calls) + def _layer_with_authenticity_verifier(self, verifier): + def selector(): + self.selection_calls += 1 + return str(self.manifest), str(self.artifact) + + return NativeApplicationUpdateLayer( + self.base, + repository_root(), + selector, + current_version="0.6.0-r06.3dev.a", + authenticity_verifier=verifier, + ) + + def test_positive_same_publisher_signal_is_reported_only_after_byte_recheck(self): + calls = [] + + def verifier(candidate): + calls.append(candidate) + return True + + response = self._layer_with_authenticity_verifier(verifier).handle(update_request()) + self.assertTrue(response["ok"]) + self.assertTrue(response["data"]["verified"]) + self.assertEqual("same_publisher_authenticode_verified", response["data"]["authenticity"]) + self.assertEqual([self.artifact], calls) + + def test_negative_or_unavailable_authenticity_does_not_fake_publisher_proof(self): + for verifier in ( + lambda candidate: False, + lambda candidate: (_ for _ in ()).throw(RuntimeError("unavailable")), + ): + with self.subTest(verifier=verifier): + response = self._layer_with_authenticity_verifier(verifier).handle(update_request()) + self.assertTrue(response["ok"]) + self.assertTrue(response["data"]["verified"]) + self.assertEqual( + "not_proven_by_local_hash_verification", + response["data"]["authenticity"], + ) + + def test_positive_signature_then_mutated_bytes_fails_entire_request_closed(self): + original_size = self.artifact.stat().st_size + + def mutate_after_signature(candidate): + candidate.write_bytes(b"x" * original_size) + return True + + response = self._layer_with_authenticity_verifier(mutate_after_signature).handle(update_request()) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn(str(self.artifact), serialized) + def test_frontend_materializes_semantic_empty_payload_update_surface(self): platform = Path(__file__).resolve().parents[1] html = (platform / "frontend" / "index.html").read_text(encoding="utf-8") @@ -140,10 +201,118 @@ def test_frontend_materializes_semantic_empty_payload_update_surface(self): self.assertIn('role="status"', html) self.assertIn("application_update.select_verify", script) self.assertIn("payload:{}", script) + self.assertIn("same_publisher_authenticode_verified", script) + self.assertIn("Підтверджено: чинний Authenticode", script) + self.assertIn("Автентичність видавця не підтверджена", script) self.assertNotIn("innerHTML", script) self.assertNotIn("payload:{path", script.replace(" ", "")) +class AuthenticodePayloadTests(unittest.TestCase): + VALID_A = "0123456789ABCDEF0123456789ABCDEF01234567" + VALID_B = "89ABCDEF0123456789ABCDEF0123456789ABCDEF" + + @staticmethod + def payload(left_status="Valid", right_status="Valid", left_thumb=None, right_thumb=None, extra=False): + left = {"status": left_status, "thumbprint": left_thumb or AuthenticodePayloadTests.VALID_A} + right = {"status": right_status, "thumbprint": right_thumb or AuthenticodePayloadTests.VALID_A} + if extra: + left["unexpected"] = True + return json.dumps([left, right]) + + def test_parser_accepts_only_two_valid_matching_signers(self): + self.assertTrue(_same_valid_signer_payload(self.payload())) + + def test_parser_rejects_signer_mismatch_invalid_status_and_extra_fields(self): + self.assertFalse(_same_valid_signer_payload(self.payload(right_thumb=self.VALID_B))) + self.assertFalse(_same_valid_signer_payload(self.payload(right_status="HashMismatch"))) + self.assertFalse(_same_valid_signer_payload(self.payload(extra=True))) + + def test_parser_rejects_malformed_shapes_and_thumbprints(self): + for payload in ( + "not-json", + "{}", + "[]", + json.dumps([{"status": "Valid", "thumbprint": self.VALID_A}]), + json.dumps([ + {"status": "Valid", "thumbprint": "xyz"}, + {"status": "Valid", "thumbprint": "xyz"}, + ]), + ): + with self.subTest(payload=payload): + self.assertFalse(_same_valid_signer_payload(payload)) + + def test_non_windows_verifier_fails_closed_before_subprocess(self): + current = Path("current.exe") + candidate = Path("candidate.exe") + with mock.patch( + "scripture_archive_platform.desktop_host.authenticode.os.name", + "posix", + ), mock.patch( + "scripture_archive_platform.desktop_host.authenticode.subprocess.run" + ) as run: + self.assertFalse( + verify_same_publisher_authenticode( + current, + candidate, + ) + ) + run.assert_not_called() + + def test_windows_verifier_uses_native_system_directory_not_hostile_environment(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + current = root / "current.exe" + candidate = root / "candidate.exe" + current.write_bytes(b"current") + candidate.write_bytes(b"candidate") + system32 = root / "trusted-system32" + powershell_root = system32 / "WindowsPowerShell" / "v1.0" + modules = powershell_root / "Modules" + modules.mkdir(parents=True) + powershell = powershell_root / "powershell.exe" + powershell.write_bytes(b"fake-powershell") + payload = self.payload() + + completed = mock.Mock(returncode=0, stdout=payload) + with mock.patch( + "scripture_archive_platform.desktop_host.authenticode.os.name", + "nt", + ), mock.patch( + "scripture_archive_platform.desktop_host.authenticode._windows_system_directory", + return_value=system32, + ), mock.patch.dict( + "scripture_archive_platform.desktop_host.authenticode.os.environ", + { + "WINDIR": str(root / "attacker-windir"), + "PSModulePath": str(root / "attacker-modules"), + }, + clear=False, + ), mock.patch( + "scripture_archive_platform.desktop_host.authenticode.subprocess.run", + return_value=completed, + ) as run: + self.assertTrue(verify_same_publisher_authenticode(current, candidate)) + + args, kwargs = run.call_args + self.assertEqual(str(powershell), args[0][0]) + self.assertNotIn("attacker-windir", args[0][0]) + self.assertEqual(str(modules), kwargs["env"]["PSModulePath"]) + self.assertNotIn("attacker-modules", kwargs["env"]["PSModulePath"]) + self.assertIn( + "Microsoft.PowerShell.Security\\Get-AuthenticodeSignature", + args[0][-1], + ) + + @unittest.skipUnless(os.name == "nt", "Windows Authenticode integration only") + def test_windows_verifier_executes_real_system_authenticode_command(self): + system_directory = _windows_system_directory() + self.assertIsInstance(system_directory, Path) + powershell = system_directory / "WindowsPowerShell" / "v1.0" / "powershell.exe" + self.assertTrue(powershell.is_file()) + self.assertTrue(verify_same_publisher_authenticode(powershell, powershell)) + + class NativeUpdateFileSelectorTests(unittest.TestCase): class FakeWebview: class FileDialog: