XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
# Real previous-release evidence and regular-file migration tests. No raw disks.
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$Image,
      [Parameter(Mandatory=$true)][string]$PreviousWriteResult,
      [Parameter(Mandatory=$true)][string]$PreviousWriteResultSha256)
$ErrorActionPreference='Stop'
$candidate=$Image
$previousPath=$PreviousWriteResult
$previousHash=$PreviousWriteResultSha256
. (Join-Path $PSScriptRoot 'physical-media.ps1') -LoadFunctionsOnly
$directory=Join-Path (Join-Path $PSScriptRoot '../build') ('PreviousStockImportTests-'+[Guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($directory)
$disk=[pscustomobject]@{Number=3;SerialNumber='230222336207';UniqueId='5000000000002AEF';Size=[uint64]256060514304;BusType='USB';LogicalSectorSize=512}
$script:checks=0
function Check([bool]$Condition,[string]$Message){if(!$Condition){throw $Message};$script:checks++}
function Refuse([scriptblock]$Action,[string]$Message){$failed=$false;try{& $Action | Out-Null}catch{$failed=$true};Check $failed $Message}
function Fixture($Receipt,[string]$Name){$path=Join-Path $directory $Name;$Receipt | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $path -Encoding UTF8;return $path}
$prior=Get-Content -LiteralPath $previousPath -Raw -Encoding UTF8 | ConvertFrom-Json
$originalImageHash=(Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash
$originalOldHash=(Get-FileHash -LiteralPath $prior.Plan.image -Algorithm SHA256).Hash
$known=Get-XfePreviousStockImport $previousPath $previousHash $disk
Check ($known.DefaultImportSha256 -ceq $prior.ExperimentalEvidence.DefaultImportSha256 -and $known.EvidenceLocks.Count -eq 5) 'Previous stock release was not bound.'
Refuse {Get-XfePreviousStockImport $previousPath '' $disk} 'Missing pin was accepted.'
Refuse {Get-XfePreviousStockImport $previousPath ('0'*64) $disk} 'Wrong completion pin was accepted.'
$disk.SerialNumber='another-usb'
Refuse {Get-XfePreviousStockImport $previousPath $previousHash $disk} 'Wrong serial was accepted.'
$disk.SerialNumber='230222336207';$disk.UniqueId='another-unique-id'
Refuse {Get-XfePreviousStockImport $previousPath $previousHash $disk} 'Wrong unique ID was accepted.'
$disk.UniqueId='5000000000002AEF'
foreach($change in @('failed','not-persistent','incomplete-readback','changed-image','changed-boot')) {
    $fixture=Get-Content -LiteralPath $previousPath -Raw -Encoding UTF8 | ConvertFrom-Json
    switch($change) {
        'failed' {$fixture.Status='failed'}
        'not-persistent' {$fixture.ExperimentalEvidence.PersistentConfigurationVerified=$false}
        'incomplete-readback' {$fixture.Verification.FullImageVerified=$false}
        'changed-image' {$path=Join-Path $directory 'changed.img';[IO.File]::WriteAllBytes($path,[byte[]]@(1,2,3));$fixture.ExperimentalEvidence.ImagePath=$path}
        'changed-boot' {
            $boot=Get-Content -LiteralPath $fixture.ExperimentalEvidence.BootResultPath -Raw -Encoding UTF8 | ConvertFrom-Json
            $boot.Passed=$false
            $path=Fixture $boot 'failed-boot.json'
            $fixture.ExperimentalEvidence.BootResultPath=$path
            $fixture.ExperimentalEvidence.BootResultSha256=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
        }
    }
    $path=Fixture $fixture ($change+'.json')
    $hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
    Refuse {Get-XfePreviousStockImport $path $hash $disk} ('Invalid previous release accepted: '+$change)
}
$manifest=Get-Content -LiteralPath ($candidate+'.json') -Raw -Encoding UTF8 | ConvertFrom-Json
$currentImport=(Get-Content -LiteralPath $previousPath -Raw -Encoding UTF8 | ConvertFrom-Json).ExperimentalEvidence.DefaultImportSha256
# A deliberately different candidate hash exercises the migration branch even
# when the supplied old/current fixtures happen to contain the same sample.
$differentImport='f'*64
if($differentImport -ceq $currentImport){$differentImport='e'*64}
$oldPath=Join-Path $directory 'Existing.img';Copy-Item -LiteralPath $prior.Plan.image -Destination $oldPath
$newPath=Join-Path $directory 'Updated.img';Copy-Item -LiteralPath $candidate -Destination $newPath
$old=$source=$target=$null
try {
    $old=[IO.File]::Open($oldPath,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::Read)
    Refuse {Get-XfePreservedWorkspace $old $old.Length $directory $differentImport} 'Unidentified changed import was overwritten.'
    $preserved=Get-XfePreservedWorkspace $old $old.Length $directory $differentImport $known
    Check ($preserved.Bytes.Length -eq 64MB -and $preserved.StockImportBackup.Sha256 -ceq $currentImport -and
        (Get-FileHash -LiteralPath $preserved.StockImportBackup.SnapshotPath -Algorithm SHA256).Hash.ToLowerInvariant() -ceq $currentImport) 'Previous stock sample was not backed up exactly.'
    Check ((Get-FileHash -LiteralPath $preserved.SnapshotPath -Algorithm SHA256).Hash.ToLowerInvariant() -ceq $preserved.Sha256) 'Workspace backup was not exact.'
    $source=[IO.File]::OpenRead($candidate)
    $target=[IO.File]::Open($newPath,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::Read)
    $target.SetLength(300MB)
    $patch=[pscustomobject]@{Offset=[uint64]$manifest.WorkspaceFirstLba*512;Bytes=$preserved.Bytes}
    Write-XfeBytes $target $patch.Offset $patch.Bytes
    Set-XfeAdjustedGpt $target (Get-XfeAdjustedGpt $source $target.Length)
    $target.Flush($true)
    $verification=Test-XfeAdjustedReadback $source $target $target.Length $patch
    Check ($verification.FullImageVerified -and $verification.ActualTailBackupGptVerified) 'Cross-version full workspace restore failed.'
    # A user replacement must still fail with valid old-release authorization.
    $boot=Read-XfeBytes $old (2048*512) 512
    $reserved=[BitConverter]::ToUInt16($boot,14);$fatSectors=[BitConverter]::ToUInt32($boot,36)
    $clusterBytes=[int]$boot[13]*512
    $fat=Read-XfeBytes $old ((2048+$reserved)*512) ($fatSectors*512)
    $data=([uint64]2048+$reserved+2*[uint64]$fatSectors)*512
    $root=@(Get-XfeFatDirectory $old $data $fat ([BitConverter]::ToUInt32($boot,44)) $clusterBytes)
    $folder=@($root | Where-Object ShortName -CEQ 'USERFILE   ')[0]
    $file=@(Get-XfeFatDirectory $old $data $fat $folder.Cluster $clusterBytes)[0]
    $offset=$data+([uint64]$file.Cluster-2)*$clusterBytes
    $original=Read-XfeBytes $old $offset 512
    $changed=[byte[]]$original.Clone();$changed[0]=$changed[0] -bxor 1
    Write-XfeBytes $old $offset $changed
    Refuse {Get-XfePreservedWorkspace $old $old.Length $directory $differentImport $known} 'A user replacement bypassed old-release validation.'
    Write-XfeBytes $old $offset $original
    $plain=Get-XfeMediaIdentity $disk @() 'image-hash' 'LegacyPhysical256' $null
    $withPrevious=Get-XfeMediaIdentity $disk @() 'image-hash' 'LegacyPhysical256' $null $known
    Check ((Get-XfeToken $plain) -cne (Get-XfeToken $withPrevious)) 'Previous-release authorization was omitted from the plan token.'
} finally {
    foreach($stream in @($old,$source,$target)){if($stream){$stream.Dispose()}}
    Check ((Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash -ceq $originalImageHash -and
        (Get-FileHash -LiteralPath $prior.Plan.image -Algorithm SHA256).Hash -ceq $originalOldHash -and
        (Get-FileHash -LiteralPath $previousPath -Algorithm SHA256).Hash.ToLowerInvariant() -ceq $previousHash) 'Original accepted inputs changed.'
}
[ordered]@{Kind='XfePreviousStockImportTests';Passed=$true;Checks=$script:checks;PhysicalDiskOpened=$false;Directory=$directory} | ConvertTo-Json