137 lines
8.7 KiB
PowerShell
137 lines
8.7 KiB
PowerShell
#requires -Version 5.1
|
|
#requires -RunAsAdministrator
|
|
# Resume the single observed interrupted first staging copy on the test VM.
|
|
[CmdletBinding()]
|
|
param([Parameter(Mandatory)][ValidateSet('Read','Resume')][string]$Action)
|
|
$ErrorActionPreference='Stop'
|
|
$base=Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1'
|
|
$baseHash='c54e36b32a2fcccb072f2cca52a38b6c4da31755d86205599016c5d180f5cec4'
|
|
if ((Get-FileHash -LiteralPath $base).Hash -ne $baseHash) { throw 'Original passive-pair controller differs' }
|
|
$text=[IO.File]::ReadAllText($base)
|
|
$i=$text.IndexOf("`n`$originalCase = ",[StringComparison]::Ordinal)
|
|
$j=$text.IndexOf("`nif (`$Mode -eq 'Read') {",[StringComparison]::Ordinal)
|
|
if ($i -le 0 -or $j -le $i) { throw 'Original fixed declaration boundary' }
|
|
. ([scriptblock]::Create($text.Substring($i,$j-$i)))
|
|
Add-Type -TypeDefinition @'
|
|
using System;
|
|
using System.IO;
|
|
using System.ComponentModel;
|
|
using System.Runtime.InteropServices;
|
|
using System.Security.Cryptography;
|
|
using Microsoft.Win32.SafeHandles;
|
|
|
|
public static class RmmPassiveStage {
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct Basic { public long Created,Accessed,Written,Changed; public uint Attributes; }
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct Standard { public long Allocated,End; public uint Links; public byte Pending,Directory; }
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct Id { public ulong Volume, Low, High; }
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)]
|
|
private static extern SafeFileHandle CreateFileW(string path,uint access,uint sharing,IntPtr security,uint disposition,uint flags,IntPtr template);
|
|
[DllImport("kernel32.dll",SetLastError=true)]
|
|
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Basic b,uint n);
|
|
[DllImport("kernel32.dll",SetLastError=true)]
|
|
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Standard s,uint n);
|
|
[DllImport("kernel32.dll",SetLastError=true)]
|
|
private static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int k,out Id id,uint n);
|
|
[DllImport("kernel32.dll",SetLastError=true)]
|
|
private static extern bool SetFileInformationByHandle(SafeFileHandle h,int k,ref Basic b,uint n);
|
|
private static string Hex(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-","").ToLowerInvariant(); }
|
|
public static uint Check(string expectedId,string digest,string volume,bool clear) {
|
|
const string path=@"C:\ProgramData\RustDiscoveryBootstrap\job-passive-pair-49c230d8-fb5d-4c64-96b6-e0edce03ed90\install-stage-agent";
|
|
using (SafeFileHandle h=CreateFileW(path,clear?0x181u:0x81u,0,IntPtr.Zero,3,0x00200000,IntPtr.Zero)) {
|
|
if (h.IsInvalid) throw new Win32Exception();
|
|
Basic b; Standard s; Id id;
|
|
uint nb=(uint)Marshal.SizeOf(typeof(Basic));
|
|
if (!GetFileInformationByHandleEx(h,0,out b,nb) ||
|
|
!GetFileInformationByHandleEx(h,1,out s,(uint)Marshal.SizeOf(typeof(Standard))) ||
|
|
!GetFileInformationByHandleEx(h,18,out id,(uint)Marshal.SizeOf(typeof(Id)))) throw new Win32Exception();
|
|
string hexId=Hex(BitConverter.GetBytes(id.Low))+Hex(BitConverter.GetBytes(id.High));
|
|
if (s.Directory!=0 || s.Pending!=0 || s.End!=23541484 || s.Links!=1 || (b.Attributes & 0x410)!=0 ||
|
|
id.Volume.ToString(System.Globalization.CultureInfo.InvariantCulture)!=volume || expectedId!=hexId)
|
|
throw new InvalidDataException("Unexpected stage identity/type/links");
|
|
using (var fs=new FileStream(h,FileAccess.Read))
|
|
using (var hash=SHA256.Create()) {
|
|
if (Hex(hash.ComputeHash(fs))!=digest) throw new InvalidDataException("Staged image hash changed");
|
|
uint original=b.Attributes;
|
|
if (clear) {
|
|
if ((original & 1)==0) throw new InvalidDataException("ReadOnly not present");
|
|
Basic changed=new Basic();changed.Attributes=original & ~1u;
|
|
if (changed.Attributes==0) changed.Attributes=0x80; // FILE_ATTRIBUTE_NORMAL
|
|
if (!SetFileInformationByHandle(h,0,ref changed,nb) ||
|
|
!GetFileInformationByHandleEx(h,0,out b,nb)) throw new Win32Exception();
|
|
if (b.Attributes!=changed.Attributes) throw new InvalidDataException("Attribute verification");
|
|
}
|
|
return original;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
'@
|
|
VerifyPassiveContext
|
|
StopCheck
|
|
CheckControl $work $true
|
|
$expected=@('prepared.json','install-intent.json','install-stop-agent.json','install-stop-helper.json',
|
|
'old-agent','old-settings','old-pin','new-settings','new-pin','install-stage-agent')
|
|
$found=@(Get-ChildItem -LiteralPath $work -Force | ForEach-Object { $_.Name })
|
|
if (@(Compare-Object -CaseSensitive ($expected|Sort-Object) ($found|Sort-Object)).Count) {
|
|
throw 'Only the original completed preparation, two stops and first private staging copy may exist'
|
|
}
|
|
foreach ($f in $expected) { CheckControl (Join-Path $work $f) $false }
|
|
$prep=LoadRecord 'prepared';$intent=LoadRecord 'install-intent'
|
|
if ($prep.id -cne $id -or $intent.id -cne $id -or !(JsonEqual $prep.files (CurrentFiles)) -or
|
|
!(JsonEqual $prep.device (PreservedDevice)) -or !(JsonEqual $prep.agent (LoadRecord 'install-stop-agent')) -or
|
|
!(JsonEqual $prep.helper (LoadRecord 'install-stop-helper'))) { throw 'Stored original stop, device or protected file identity changed' }
|
|
VerifyFiles $prep.files $oldHashes
|
|
foreach ($n in $locations.Keys) {
|
|
if ((Hash (Join-Path $work ('old-'+$n))) -cne $oldHashes.$n) { throw 'Recovery backup changed' }
|
|
}
|
|
foreach ($n in @('settings','pin')) {
|
|
if ((Hash (Join-Path $work ('new-'+$n))) -cne $newHashes.$n) { throw 'Settings candidate changed' }
|
|
}
|
|
CheckControl (Split-Path $source) $true
|
|
CheckControl $source $false
|
|
$stagedPath=Join-Path $work 'install-stage-agent'
|
|
$originalCopy=FileIdentity $stagedPath
|
|
$sourceId=FileIdentity $source
|
|
if ($sourceId.sha256 -cne $newHashes.agent -or $originalCopy.sha256 -cne $newHashes.agent -or
|
|
$originalCopy.file_id -ceq $sourceId.file_id -or $originalCopy.volume_serial -cne $prep.files.agent.volume_serial -or
|
|
$originalCopy.file_id -ceq $prep.files.agent.file_id) { throw 'Staged copy not separately bound to expected image' }
|
|
$flags=[RmmPassiveStage]::Check($originalCopy.file_id,$newHashes.agent,$originalCopy.volume_serial,$false)
|
|
if ($Action -ceq 'Read') {
|
|
[ordered]@{id=$id;both_services_stopped=$true;no_replacement_markers=$true;private_stage=$originalCopy
|
|
attributes=[string]([IO.FileAttributes]$flags);readonly=[bool]($flags -band 1);links=1;source_id=$sourceId.file_id} |
|
|
ConvertTo-Json -Depth 6 -Compress
|
|
return
|
|
}
|
|
if ($flags -ne 0x2021 -or (Get-Item -LiteralPath $source -Force).Attributes -ne [IO.FileAttributes]0x2021) {
|
|
throw 'Source and own staging copy must have the observed ReadOnly, Archive, NotContentIndexed attributes'
|
|
}
|
|
Record 'install-resume-stage-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o');stage=$originalCopy;attributes=$flags;source=$sourceId}
|
|
$null=[RmmPassiveStage]::Check($originalCopy.file_id,$newHashes.agent,$originalCopy.volume_serial,$true)
|
|
if (!(JsonEqual $originalCopy (FileIdentity $stagedPath))) { throw 'Changed staged file after clearing its copy-only attribute' }
|
|
# Run the original checked swap from FlushFile onward for the existing first stage.
|
|
# For the two JSON files retain the original CreateNew-style copy in full.
|
|
$from=$text.IndexOf('function SwapFile(',[StringComparison]::Ordinal)
|
|
$to=$text.IndexOf('function StartKnownRole(',[StringComparison]::Ordinal)
|
|
$swap=$text.Substring($from,$to-$from)
|
|
$copy='[IO.File]::Copy($inputPath,$stage,$false)'
|
|
if (!$swap.Contains($copy) -or $swap.IndexOf($copy) -ne $swap.LastIndexOf($copy)) { throw 'Copy resume boundary' }
|
|
$branch='if ($name -ceq "agent") { if (!(JsonEqual $originalCopy (FileIdentity $stage))) { throw "Existing private copy changed" } } else { '+$copy+' }'
|
|
. ([scriptblock]::Create($swap.Replace($copy,$branch)))
|
|
foreach ($name in $locations.Keys) {
|
|
$inputPath=Join-Path $work ('new-'+$name)
|
|
if ($name -ceq 'agent') { $inputPath=$source }
|
|
SwapFile $name $inputPath $prep.files.$name $newHashes.$name 'install'
|
|
}
|
|
VerifyFiles (CurrentFiles) $newHashes
|
|
StartKnownRole 'helper' $helperName $helperHash 'install'
|
|
StartKnownRole 'agent' $agentName $newHashes.agent 'install'
|
|
$a=LiveRole 'agent' $newHashes.agent
|
|
$h=LiveRole 'helper' $helperHash
|
|
if (!(JsonEqual $prep.device (PreservedDevice))) { throw 'Device changed after passive restart' }
|
|
Record 'installed' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');agent=$a;helper=$h;files=(CurrentFiles)
|
|
device=$prep.device;job_mode=$false;clock_qualified=$false})
|
|
Write-Output "Installed passive pair from confirmed read-only copy $id"
|