Files
rust-discovery/deploy/windows/Complete-OriginalTimeProfile.ps1
2026-11-15 20:37:00 +01:00

429 lines
23 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
# Finish the single, console-verified public-file publication on the test VM.
# Run in a fresh Windows PowerShell process. No SSH or RMM job is involved.
[CmdletBinding()]
param([switch]$InitialCreate, [switch]$ResumeEmpty)
$ErrorActionPreference = 'Stop'
if ($InitialCreate -and $ResumeEmpty) { throw 'Choose one publication operation' }
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
$controllerHash = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
$configHash = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
$casePath = Join-Path $bootstrap "time-profile-$caseId"
$original = Join-Path (Join-Path $bootstrap $controllerHash) 'InstallPublicTimeProfile.ps1'
$originalBytes = [IO.File]::ReadAllBytes($original)
$sha = [Security.Cryptography.SHA256]::Create()
try {
$digest = [BitConverter]::ToString($sha.ComputeHash($originalBytes)).Replace('-', '')
} finally { $sha.Dispose() }
if ($digest -ne $controllerHash) { throw 'Unexpected original controller' }
# Import the verified definitions (including native FileID/SCM checks) from the
# installed original. Its first top-level preflight and install body are excluded.
$source = [Text.Encoding]::UTF8.GetString($originalBytes)
$boundary = "`nCheckControl `$boot `$true`n"
$index = $source.IndexOf($boundary, [StringComparison]::Ordinal)
if ($index -lt 1 -or $index -ne $source.LastIndexOf($boundary, [StringComparison]::Ordinal)) {
throw 'Original controller definition boundary missing'
}
$intent = Get-Content -LiteralPath (Join-Path $casePath 'intent.json') -Raw | ConvertFrom-Json
if ($intent.id -cne $caseId -or $intent.request.id -cne $caseId -or
$intent.request.script_sha256 -cne $controllerHash -or $intent.request.config_sha256 -cne $configHash) {
throw 'Unexpected original intent'
}
$global:RmmTimeProfilePayload = $intent.request
. ([scriptblock]::Create($source.Substring(0, $index)))
CheckControl $boot $true
CheckControl $folder $true
foreach ($leaf in 'intent.json','publish-intent.json','directory-acl-intent.json','directory-acl-done.json') {
CheckControl (Join-Path $folder $leaf) $false
}
CheckControl $active $false
$activeRecord = Get-Content -LiteralPath $active -Raw | ConvertFrom-Json
if ($activeRecord.id -cne $caseId -or $activeRecord.script_sha256 -cne $controllerHash -or
$activeRecord.config_sha256 -cne $configHash -or $activeRecord.no_retry -ne $true) {
throw 'Unexpected active publication record'
}
$bytes = ConfigBytes
$publish = Get-Content -LiteralPath (Join-Path $folder 'publish-intent.json') -Raw | ConvertFrom-Json
$aclDone = Get-Content -LiteralPath (Join-Path $folder 'directory-acl-done.json') -Raw | ConvertFrom-Json
$staged = Join-Path $folder 'time-attestation.candidate.json'
$resultPath = Join-Path $folder 'result.json'
$reservation = Join-Path $folder 'console-finalization-intent.json'
$initialReservation = Join-Path $folder 'console-initial-create-intent.json'
$initialResult = Join-Path $folder 'console-initial-create-result.json'
$initialError = Join-Path $folder 'console-initial-create-error.json'
$initialVerified = Join-Path $folder 'console-initial-create-verified.json'
$resumeReservation = Join-Path $folder 'console-resume-empty-intent.json'
$resumeVerified = Join-Path $folder 'console-resume-empty-verified.json'
$resumeResult = Join-Path $folder 'console-resume-empty-result.json'
$resumeError = Join-Path $folder 'console-resume-empty-error.json'
$absent = @($resultPath,$initialVerified,$initialResult,$resumeReservation,$resumeVerified,$resumeResult,$resumeError)
if (!$ResumeEmpty) { $absent += @($target,$initialReservation,$initialError) }
if ($InitialCreate -or $ResumeEmpty) {
$priorError = Join-Path $folder 'console-finalization-error.json'
CheckControl $reservation $false
CheckControl $priorError $false
$priorReservation = Get-Content -LiteralPath $reservation -Raw | ConvertFrom-Json
$priorFailure = Get-Content -LiteralPath $priorError -Raw | ConvertFrom-Json
if ($priorReservation.id -cne $caseId -or $priorReservation.config_sha256 -cne $configHash -or
$priorFailure.id -cne $caseId -or $priorFailure.phase -cne 'File.Move' -or
$priorFailure.hresult -cne '0x80070020' -or $priorFailure.exception -cne 'System.IO.IOException') {
throw 'Expected the recorded sharing violation from the original single finalization attempt'
}
} else {
$absent += $reservation
}
foreach ($path in $absent) {
if (Test-Path -LiteralPath $path) { throw 'Existing target or finalization record: read original case' }
}
$stagedAcl = ReadAcl $staged $false
$rootAcl = ReadAcl $helperRoot $true
$expected = @{
volume_serial = '9815088561147542064'
file_id = '6d990300000003000000000000000000'
bytes = 1177
acl_sha256 = '3a426f649cd6ff4e82bf70205c8ecc7d5b2c0775fa1e10fc30ce35de9bb12493'
sha256 = $configHash
}
if ($publish.create_once -ne $true -or $publish.config_sha256 -cne $configHash -or
!(JsonEqual $expected $publish.staged) -or !(JsonEqual $expected (FileIdentity $staged)) -or
(FileVolume $helperRoot) -cne $expected.volume_serial -or $rootAcl.Sddl -cne $aclDone.sddl -or
(AclHash $helperRoot) -cne '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49') {
throw 'Original file identity or permissions changed'
}
if ($ResumeEmpty) {
CheckControl $initialReservation $false
CheckControl $initialError $false
$creation = Get-Content -LiteralPath $initialReservation -Raw | ConvertFrom-Json
$failure = Get-Content -LiteralPath $initialError -Raw | ConvertFrom-Json
if ($creation.id -cne $caseId -or $creation.config_sha256 -cne $configHash -or
$creation.create_new -isnot [bool] -or !$creation.create_new -or !$creation.utc -or
!(JsonEqual $expected $creation.staged) -or $failure.id -cne $caseId -or
$failure.phase -cne 'verify_creation' -or $failure.hresult -cne '0x80131501' -or
$failure.exception -cne 'System.Management.Automation.RuntimeException') {
throw 'Unexpected initial creation intent or failure'
}
}
if ($p.probe_sha256 -cne '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac' -or
$p.system_probe_sha256 -cne '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434') {
throw 'Unexpected native status probes'
}
$before = ActualState $true
SameLive $request.expected_native $before
SameLive $intent.before $before
if ($before.agent_kernel.creation_filetime -cne '134392294174782153' -or
$before.helper_kernel.creation_filetime -cne '134392294130218261') { throw 'Service generation changed' }
# FileStandardInfo supplies the hard-link count and directory/delete-pending state
# from the same exclusive handle used to write, flush, hash and publish the DACL.
function Initialize-InitialProfileNative {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class RmmInitialProfileFile {
[StructLayout(LayoutKind.Sequential)]
private struct StandardInfo {
public long AllocationSize, EndOfFile;
public uint NumberOfLinks;
public byte DeletePending, Directory;
}
[DllImport("kernel32.dll", SetLastError=true)]
private static extern bool GetFileInformationByHandleEx(
SafeFileHandle handle, int infoClass, out StandardInfo info, uint size);
[StructLayout(LayoutKind.Sequential)]
private struct TagInfo { public uint Attributes, ReparseTag; }
[DllImport("kernel32.dll", SetLastError=true)]
private static extern bool GetFileInformationByHandleEx(
SafeFileHandle handle, int infoClass, out TagInfo info, uint size);
[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);
private static void CheckAttributes(SafeFileHandle handle, bool directory) {
TagInfo info;
if (!GetFileInformationByHandleEx(handle, 9, out info, (uint)Marshal.SizeOf(typeof(TagInfo))))
throw new Win32Exception(Marshal.GetLastWin32Error());
if ((info.Attributes & (uint)FileAttributes.ReparsePoint) != 0 ||
((info.Attributes & (uint)FileAttributes.Directory) != 0) != directory)
throw new InvalidOperationException("Unexpected file type or reparse point");
}
[StructLayout(LayoutKind.Sequential)]
private struct UnicodeString { public ushort Length, MaximumLength; public IntPtr Buffer; }
[StructLayout(LayoutKind.Sequential)]
private struct ObjectAttributes {
public int Length;
public IntPtr RootDirectory, ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor, SecurityQoS;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoStatus { public IntPtr Status, Information; }
[DllImport("ntdll.dll")]
private static extern int NtOpenFile(out SafeFileHandle file, uint access, ref ObjectAttributes attributes,
out IoStatus io, uint share, uint options);
[DllImport("ntdll.dll")]
private static extern uint RtlNtStatusToDosError(int status);
// Open-only, relative to the held volume root. OBJ_DONT_REPARSE applies to
// the complete relative path, including ProgramData and the helper directory.
public static FileStream OpenExistingTarget() {
const string relativePath = @"ProgramData\RustDiscoverySystem\time-attestation.json";
const uint backupSemanticsNoFollow = 0x02200000;
using (SafeFileHandle root = CreateFileW(@"C:\", 0xA0, 7, IntPtr.Zero, 3,
backupSemanticsNoFollow, IntPtr.Zero)) {
if (root.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
CheckAttributes(root, true);
UnicodeString name = new UnicodeString();
name.Length = checked((ushort)(relativePath.Length * sizeof(char)));
name.MaximumLength = name.Length;
name.Buffer = Marshal.StringToHGlobalUni(relativePath);
IntPtr nativeName = IntPtr.Zero;
try {
nativeName = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnicodeString)));
Marshal.StructureToPtr(name, nativeName, false);
ObjectAttributes attributes = new ObjectAttributes();
attributes.Length = Marshal.SizeOf(typeof(ObjectAttributes));
attributes.RootDirectory = root.DangerousGetHandle();
attributes.ObjectName = nativeName;
attributes.Attributes = 0x1040; // OBJ_DONT_REPARSE | OBJ_CASE_INSENSITIVE
const uint readWriteAcl = 0x00160083; // synchronize, WRITE_DAC, READ_CONTROL, attributes and data
const uint options = 0x62; // FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_WRITE_THROUGH
IoStatus io;
SafeFileHandle h;
int status = NtOpenFile(out h, readWriteAcl, ref attributes, out io, 0, options);
if (status != 0) throw new Win32Exception((int)RtlNtStatusToDosError(status));
try {
CheckSingleFile(h, 0);
return new FileStream(h, FileAccess.ReadWrite);
} catch { h.Dispose(); throw; }
} finally {
Marshal.FreeHGlobal(nativeName);
Marshal.FreeHGlobal(name.Buffer);
}
}
}
public static void CheckSingleFile(SafeFileHandle handle, long expectedLength) {
CheckAttributes(handle, false);
StandardInfo info;
if (!GetFileInformationByHandleEx(handle, 1, out info, (uint)Marshal.SizeOf(typeof(StandardInfo))))
throw new Win32Exception(Marshal.GetLastWin32Error());
if (info.NumberOfLinks != 1 || info.DeletePending != 0 || info.Directory != 0 ||
info.EndOfFile != expectedLength)
throw new InvalidOperationException("Expected one regular file of the exact size");
}
}
'@
}
function Get-HeldProfileFileId([IO.FileStream]$Stream) {
$id = New-Object RmmPipeNative+FileId
if (![RmmPipeNative]::GetFileInformationByHandleEx($Stream.SafeFileHandle, 18, [ref]$id, 24)) {
throw 'New file identity unavailable'
}
return @{
volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)
file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant()
}
}
function Get-HeldProfileIdentity([IO.FileStream]$Stream) {
[RmmInitialProfileFile]::CheckSingleFile($Stream.SafeFileHandle, 1177)
$identity = Get-HeldProfileFileId $Stream
$Stream.Position = 0
$algorithm = [Security.Cryptography.SHA256]::Create()
try { $digest = [BitConverter]::ToString($algorithm.ComputeHash($Stream)).Replace('-','').ToLowerInvariant() }
finally { $algorithm.Dispose() }
$sddl = $Stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
$identity.bytes = $Stream.Length
$identity.sha256 = $digest
$identity.acl_sha256 = BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl))
return $identity
}
# Both accepted strings retain the protected DACL, owner, group and all ACEs.
# Windows stored the newly created file without the auto-inherited marker.
function Test-ProfileDescriptor([string]$ExpectedSddl, [string]$ActualSddl) {
if (!$ExpectedSddl.StartsWith('O:BAG:BAD:PAI(', [StringComparison]::Ordinal)) { return $false }
return $ActualSddl -ceq $ExpectedSddl -or $ActualSddl -ceq $ExpectedSddl.Replace('D:PAI(', 'D:P(')
}
function New-OriginalPublicProfile {
Initialize-InitialProfileNative
$aclSections = [Security.AccessControl.AccessControlSections]'Owner,Group,Access'
$accessOnly = [Security.AccessControl.AccessControlSections]::Access
$draftAcl = [Security.AccessControl.FileSecurity]::new()
$draftAcl.SetSecurityDescriptorSddlForm($stagedAcl.Sddl, $aclSections)
foreach ($sid in @($agentSid,$helperSid)) {
$deny = [Security.AccessControl.FileSystemAccessRule]::new(
[Security.Principal.SecurityIdentifier]::new($sid),
[Security.AccessControl.FileSystemRights]::ReadData, [Security.AccessControl.AccessControlType]::Deny)
$draftAcl.AddAccessRule($deny)
}
$draftSddl = $draftAcl.GetSecurityDescriptorSddlForm($aclSections)
if (!$draftAcl.AreAccessRulesProtected -or $draftSddl -ceq $stagedAcl.Sddl) { throw 'Initial protected DACL required' }
if ((BytesHash ([Text.Encoding]::UTF8.GetBytes($draftSddl))) -cne
'd4726c7973c9b0cd8a66c1b129d1b5eb58d2bbfc1b103018e0a31a71fb1d9020') {
throw 'Unexpected draft descriptor for this case'
}
$reserved = $false
$phase = 'CreateNew'
$descriptorFailure = $null
if ($ResumeEmpty) {
$attemptResult = $resumeResult
$attemptError = $resumeError
$attemptVerified = $resumeVerified
} else {
$attemptResult = $initialResult
$attemptError = $initialError
$attemptVerified = $initialVerified
}
try {
if ($ResumeEmpty) {
$phase = 'open_existing_empty'
$stream = [RmmInitialProfileFile]::OpenExistingTarget()
} else {
$since = [DateTime]::UtcNow.ToString('o')
WriteNew $initialReservation @{id=$caseId; config_sha256=$configHash; utc=$since; staged=$expected; create_new=$true}
$reserved = $true
$rights = [Security.AccessControl.FileSystemRights]'ReadData,WriteData,ReadAttributes,ReadPermissions,ChangePermissions,Synchronize'
$stream = [IO.FileStream]::new($target, [IO.FileMode]::CreateNew,
$rights, [IO.FileShare]::None, 4096,
[IO.FileOptions]::WriteThrough, $draftAcl)
}
try {
$phase = 'verify_creation'
$actualSddl = $stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
if (!(Test-ProfileDescriptor $draftSddl $actualSddl)) {
$descriptorFailure = @{expected_sddl=$draftSddl; actual_sddl=$actualSddl; bytes=$null}
try {
$descriptorFailure.bytes = $stream.Length
$fileId = Get-HeldProfileFileId $stream
$descriptorFailure.file_id = $fileId.file_id
$descriptorFailure.volume_serial = $fileId.volume_serial
} catch {
$descriptorFailure.metadata_hresult = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult
}
throw 'Unexpected security descriptor on new file'
}
[RmmInitialProfileFile]::CheckSingleFile($stream.SafeFileHandle, 0)
$emptyId = Get-HeldProfileFileId $stream
if ($emptyId.volume_serial -cne $expected.volume_serial -or
$emptyId.file_id -ceq $expected.file_id -or $emptyId.file_id -ceq ('0' * 32)) {
throw 'Unexpected volume or identity on held empty target'
}
$draftHash = BytesHash ([Text.Encoding]::UTF8.GetBytes($actualSddl))
if ($ResumeEmpty) {
$since = [DateTime]::UtcNow.ToString('o')
WriteNew $resumeReservation @{
id=$caseId; utc=$since; config_sha256=$configHash; target_id=$emptyId.file_id
volume_serial=$emptyId.volume_serial; draft_acl_sha256=$draftHash; bytes=0
}
$reserved = $true
}
$phase = 'write_verify'
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush($true)
$new = Get-HeldProfileIdentity $stream
if ($new.volume_serial -cne $expected.volume_serial -or $new.file_id -ceq $expected.file_id -or
$new.file_id -cne $emptyId.file_id -or $new.sha256 -cne $configHash -or
$new.acl_sha256 -cne $draftHash) {
throw 'New held bytes, identity or staging permissions differ'
}
SameLive $before (ActualState $true)
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
if (!(JsonEqual $expected (FileIdentity $staged)) -or (AclHash $helperRoot) -cne $rootAclHash) {
throw 'Original source or target directory changed before publication'
}
WriteNew $attemptVerified @{
id=$caseId; utc=$since; original_candidate=$expected; held_target=$new
}
# Change only the DACL by handle after the verified bytes and FileID
# are durable. A crash before this point leaves service reads denied.
$phase = 'publish_dacl'
$final = $stream.GetAccessControl()
$final.SetSecurityDescriptorSddlForm($stagedAcl.Sddl, $accessOnly)
$stream.SetAccessControl($final)
$stream.Flush($true)
$actualFinal = $stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections)
if (!(Test-ProfileDescriptor $stagedAcl.Sddl $actualFinal)) { throw 'Unexpected final descriptor' }
$new.acl_sha256 = BytesHash ([Text.Encoding]::UTF8.GetBytes($actualFinal))
if (!(JsonEqual $new (Get-HeldProfileIdentity $stream))) { throw 'Held publication readback failed' }
} finally { $stream.Dispose() }
$phase = 'readback'
$null = ReadAcl $target $false
$published = FileIdentity $target
if (!(JsonEqual $new $published) -or !(JsonEqual $expected (FileIdentity $staged)) -or
(AclHash $helperRoot) -cne $rootAclHash) { throw 'Final source/target binding failed' }
$after = ActualState $true
SameLive $before $after
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
$outcome = @{
id=$caseId; installed=$true; publication_since=$since; configuration=$published
original_candidate=$expected; source_candidate_preserved=$true; initial_create=$true
native=$after; clock_runtime_qualified=$false; services_changed=$false; private_key_read=$false
no_jobs=$true; original_move_failed=$true
}
if ($ResumeEmpty) { $outcome.resumed_empty = $true }
WriteNew $attemptResult $outcome
} catch {
$cause = $_.Exception.GetBaseException()
$failure = @{id=$caseId; phase=$phase; hresult=('0x{0:X8}' -f $cause.HResult); exception=$cause.GetType().FullName}
if ($null -ne $descriptorFailure) { $failure.creation_descriptor = $descriptorFailure }
if ($reserved) { WriteNew $attemptError $failure }
throw
}
}
$heldAgent = [RmmPipeNative]::Open([int]$before.service.pid)
try {
$heldHelper = [RmmPipeNative]::Open([int]$before.helper_service.pid)
try {
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
if ($InitialCreate -or $ResumeEmpty) {
$rootAclHash = '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49'
New-OriginalPublicProfile
'Zeitprofil am gebundenen Dateihandle veroeffentlicht und nachgelesen.'
return
}
# WriteNew uses CreateNew. Concurrent or later invocations cannot republish.
WriteNew $reservation @{id=$caseId; config_sha256=$configHash; utc=[DateTime]::UtcNow.ToString('o')}
try {
[IO.File]::Move($staged, $target)
} catch {
$cause = $_.Exception.GetBaseException()
$failure = @{id=$caseId; phase='File.Move'; hresult=('0x{0:X8}' -f $cause.HResult); exception=$cause.GetType().FullName}
WriteNew (Join-Path $folder 'console-finalization-error.json') $failure
throw ("File.Move: {0} ({1})." -f $failure.exception, $failure.hresult)
}
$null = ReadAcl $target $false
$published = FileIdentity $target
if (!(JsonEqual $expected $published) -or (Test-Path -LiteralPath $staged)) { throw 'Publication postcheck failed' }
$after = ActualState $true
SameLive $before $after
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
WriteNew $resultPath @{
id=$caseId; installed=$true; install_not_before=$intent.install_not_before
configuration=$published; native=$after; original_root_sddl=$intent.original_root_sddl
root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl; no_jobs=$true
clock_runtime_qualified=$false; services_changed=$false; private_key_read=$false
console_finalized=$true; original_move_failed=$true
}
'Zeitprofil veroeffentlicht; Dateiidentitaet und Dienstgenerationen geprueft.'
} finally { $heldHelper.Dispose() }
} finally { $heldAgent.Dispose() }