Compare commits

..
Author SHA1 Message Date
kevin_janssen 5f21b753ed Provision the missing original Windows time profile through an exclusive first-create handle
Rust development slice / linux (push) Failing after 7s
2026-11-15 17:13:01 +01:00
kevin_janssen 00717e4283 Record native Windows time profile sharing violation and cloud receipt
Rust development slice / linux (push) Failing after 6s
2026-11-15 17:08:37 +01:00
kevin_janssen aa36b178aa Record verified cloud receiver and automatic close time for the console window
Rust development slice / linux (push) Failing after 6s
2026-11-15 17:05:23 +01:00
kevin_janssen d37160ba41 Return fixed Windows maintenance results over a foreground loopback SSH forward
Rust development slice / linux (push) Failing after 7s
2026-11-15 17:03:38 +01:00
kevin_janssen 577132fb42 Expose the existing passive Windows console reader as a directly runnable script
Rust development slice / linux (push) Failing after 6s
2026-11-15 17:01:33 +01:00
kevin_janssen ca588abce4 Prepare guarded console completion for the verified Windows time profile
Rust development slice / linux (push) Failing after 7s
2026-11-15 16:56:27 +01:00
kevin_janssen 53d17757ab Record operator verification of the retained Windows time profile candidate
Rust development slice / linux (push) Failing after 7s
2026-11-15 16:53:58 +01:00
kevin_janssen 27bb6a1257 Merge commit 'cd80745'
Rust development slice / linux (push) Failing after 7s
2026-11-15 16:45:46 +01:00
kevin_janssen cd80745d44 Add fixed read-only diagnostics for the original partial Windows time profile
Rust development slice / linux (push) Failing after 6s
2026-11-15 16:45:24 +01:00
7 changed files with 760 additions and 65 deletions
@@ -0,0 +1,268 @@
#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)
$ErrorActionPreference = 'Stop'
$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'
$absent = @($target,$resultPath,$initialReservation,$initialResult,$initialError)
if ($InitialCreate) {
$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 ($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.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);
public static void CheckSingleFile(SafeFileHandle handle, long expectedLength) {
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-HeldProfileIdentity([IO.FileStream]$Stream) {
[RmmInitialProfileFile]::CheckSingleFile($Stream.SafeFileHandle, 1177)
$id = New-Object RmmPipeNative+FileId
if (![RmmPipeNative]::GetFileInformationByHandleEx($Stream.SafeFileHandle, 18, [ref]$id, 24)) {
throw 'New file identity unavailable'
}
$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)
return @{
volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)
file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant()
bytes=$Stream.Length; sha256=$digest; acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))
}
}
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' }
# Record the lower bound immediately before the only possible first creation.
$since = [DateTime]::UtcNow.ToString('o')
WriteNew $initialReservation @{id=$caseId; config_sha256=$configHash; utc=$since; staged=$expected; create_new=$true}
$phase = 'CreateNew'
try {
$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'
if ($stream.GetAccessControl().GetSecurityDescriptorSddlForm($aclSections) -cne $draftSddl) {
throw 'Unexpected security descriptor on new file'
}
[RmmInitialProfileFile]::CheckSingleFile($stream.SafeFileHandle, 0)
$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 -ceq ('0' * 32) -or $new.sha256 -cne $configHash -or
$new.acl_sha256 -cne (BytesHash ([Text.Encoding]::UTF8.GetBytes($draftSddl)))) {
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 (Join-Path $folder 'console-initial-create-verified.json') @{
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)
$new.acl_sha256 = $expected.acl_sha256
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
WriteNew $initialResult @{
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
}
} catch {
$cause = $_.Exception.GetBaseException()
WriteNew $initialError @{id=$caseId; phase=$phase; hresult=('0x{0:X8}' -f $cause.HResult); exception=$cause.GetType().FullName}
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) {
$rootAclHash = '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49'
New-OriginalPublicProfile
'Zeitprofil erstmalig erstellt und anhand seiner neuen Dateiidentitaet geprueft.'
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() }
@@ -0,0 +1,105 @@
#requires -Version 5.1
#requires -RunAsAdministrator
# The relay receives a fixed public receipt. There is no command reader.
$ErrorActionPreference = 'Stop'
$until = [DateTimeOffset]::Parse('2026-11-15T17:00:00+00:00')
$deadline = [DateTimeOffset]::UtcNow.AddMinutes(12)
if ($deadline -gt $until) { $deadline = $until }
if ($deadline -le [DateTimeOffset]::UtcNow) { throw 'Das Wartungsfenster ist abgelaufen.' }
$base = 'https://gitea.incoso.eu/kevin_janssen/rust-discovery/raw/commit/577132fb422bf854276b3afb5bafdb12d2c08427/deploy/windows'
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
$case = Join-Path $bootstrap "time-profile-$caseId"
$access = 'C:\ProgramData\RmmDevAccess'
$sshBin = Join-Path $env:WINDIR 'System32\OpenSSH'
$known = Join-Path $access 'known_hosts'
$key = Join-Path $access 'tunnel_ed25519'
$fp = & "$sshBin\ssh-keygen.exe" -lf $known
if ($LASTEXITCODE -ne 0 -or @($fp).Count -ne 1 -or
$fp.Split(' ')[1] -cne 'SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw') { throw 'Server-Hostpin stimmt nicht.' }
$session = [guid]::NewGuid().ToString()
$work = Join-Path $bootstrap "time-receipt-$session"
$null = New-Item -ItemType Directory -Path $work
$listener = $null
$ssh = $null
$scripts = [ordered]@{
'Complete-OriginalTimeProfile.ps1' = '5ad85ae7a3a513d3cc2f5f5dca3e48eb42fd863522c3384f9c64cdcf0273ef1a'
'Read-PassiveTimeSamples.ps1' = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
}
try {
foreach ($name in $scripts.Keys) {
$path = Join-Path $work $name
Invoke-WebRequest -UseBasicParsing -Uri "$base/$name" -OutFile $path -TimeoutSec 30
if ((Get-FileHash -LiteralPath $path).Hash -ne $scripts[$name]) { throw "Downloadhash: $name" }
Unblock-File -LiteralPath $path
}
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
$listener.Start(4)
$port = $listener.LocalEndpoint.Port
$options = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
'-o',"UserKnownHostsFile=$known",'-o','ExitOnForwardFailure=yes','-o','ConnectTimeout=10',
'-o','ServerAliveInterval=15','-o','ServerAliveCountMax=2','-i',$key,
'-R',"127.0.0.1:22240:127.0.0.1:$port",'rmm-win-tunnel@discovery.ease-technologies.de')
$ssh = Start-Process -FilePath "$sshBin\ssh.exe" -ArgumentList $options -PassThru -NoNewWindow
if ($ssh.WaitForExit(1800)) { throw "SSH Exit $($ssh.ExitCode)" }
Write-Host 'Wartungsfenster aktiv. Dieses Fenster offen lassen. Strg+C beendet es.'
$receipt = [ordered]@{session=$session; case_id=$caseId; phase='preflight'; read_only_channel=$true}
$result = Join-Path $case 'result.json'
try {
if (!(Test-Path -LiteralPath $result)) {
$null = & (Join-Path $work 'Complete-OriginalTimeProfile.ps1')
}
$record = Get-Content -LiteralPath $result -Raw | ConvertFrom-Json
$actual = Get-FileHash -LiteralPath 'C:\ProgramData\RustDiscoverySystem\time-attestation.json'
if ($record.id -cne $caseId -or $record.installed -ne $true -or
$record.console_finalized -ne $true -or $record.clock_runtime_qualified -ne $false -or
$actual.Hash -ne '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b') { throw 'Unexpected publication result' }
$marker = Get-Content -LiteralPath (Join-Path $case 'console-finalization-intent.json') -Raw | ConvertFrom-Json
if ($marker.id -cne $caseId -or $marker.config_sha256 -ne $actual.Hash) { throw 'Unexpected finalization intent' }
$receipt.phase = 'published'
$receipt.publication_since = $marker.utc
$receipt.result_sha256 = (Get-FileHash -LiteralPath $result).Hash
} catch {
$receipt.phase = 'finalization_failed'
$receipt.exception_type = $_.Exception.GetBaseException().GetType().FullName
$receipt.line = $_.InvocationInfo.ScriptLineNumber
$receipt.file = [IO.Path]::GetFileName($_.InvocationInfo.ScriptName)
Write-Warning $_.Exception.Message
$failurePath = Join-Path $case 'console-finalization-error.json'
if (Test-Path -LiteralPath $failurePath) {
$failure = Get-Content -LiteralPath $failurePath -Raw | ConvertFrom-Json
if ($failure.id -ceq $caseId -and $failure.hresult -cmatch '^0x[0-9A-Fa-f]{8}$') { $receipt.move_hresult = $failure.hresult }
}
}
$readScript = Join-Path $work 'Read-PassiveTimeSamples.ps1'
$readInput = @{id=$session; agent_sha256='0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'; helper_sha256='59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'} | ConvertTo-Json -Compress
while ([DateTimeOffset]::UtcNow -lt $deadline -and !$ssh.HasExited) {
if (!$listener.Pending()) { Start-Sleep -Milliseconds 250; continue }
$client = $listener.AcceptTcpClient()
try {
if ($receipt.phase -eq 'published') {
$receipt.native = $null
try {
$json = $readInput | & "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy RemoteSigned -File $readScript
if ($LASTEXITCODE -eq 0) { $receipt.native = ($json -join "`n") | ConvertFrom-Json }
} catch { Write-Warning 'Passive Zeitbelege aktuell nicht lesbar.' }
}
$client.SendTimeout = 3000
$body = [Text.Encoding]::UTF8.GetBytes(($receipt | ConvertTo-Json -Depth 16 -Compress))
if ($body.Length -gt 65536) { throw 'Ergebnis zu gross.' }
$client.GetStream().Write($body,0,$body.Length)
} catch { Write-Warning $_.Exception.Message } finally { $client.Dispose() }
}
} finally {
if ($null -ne $ssh) {
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
}
if ($null -ne $listener) { $listener.Stop() }
foreach ($name in $scripts.Keys) {
$path = Join-Path $work $name
if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path }
}
if ((Get-ChildItem -LiteralPath $work -Force | Measure-Object).Count -eq 0) { [IO.Directory]::Delete($work) }
}
@@ -0,0 +1,63 @@
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
function Check($path,[bool]$directory){
$i=Get-Item -LiteralPath $path -Force
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
}
Add-Type -TypeDefinition @'
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
public static class RmmPassiveTimeRead {
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
}
'@
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function Runtime($role){
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
if($s.PathName-cne$expected){throw 'Current fixed service command'}
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
}
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
$path=Join-Path $state $name
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
$after=New-Object RmmPassiveTimeRead+Info
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
}finally{$stream.Dispose()}
}
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
$directoryAfter=Check $state $true
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -Compress
+1 -64
View File
@@ -27,70 +27,7 @@ SECOND_NS = 1_000_000_000
# No report is requested from a service. The only content reads on the guest
# are these two public JSONs and public executable hashes. CIM/process queries
# obtain current boot/SCM/image/birth metadata without starting another binary.
SCRIPT = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
function Check($path,[bool]$directory){
$i=Get-Item -LiteralPath $path -Force
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
}
Add-Type -TypeDefinition @'
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
public static class RmmPassiveTimeRead {
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
}
'@
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function Runtime($role){
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
if($s.PathName-cne$expected){throw 'Current fixed service command'}
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
}
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
$path=Join-Path $state $name
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
$after=New-Object RmmPassiveTimeRead+Info
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
}finally{$stream.Dispose()}
}
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
$directoryAfter=Check $state $true
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -Compress
'''
SCRIPT = Path(__file__).with_name('Read-PassiveTimeSamples.ps1').read_text(encoding='utf-8')
def need(value, tag):
@@ -99,5 +99,42 @@ class PublicProfileContract(unittest.TestCase):
with self.assertRaises(GuardError):t.read(path,limit=1)
class OriginalPartialDiagnosticContract(unittest.TestCase):
def test_closed_reader_cannot_publish_or_repair(self):
source=t.partial_reader()
self.assertIn('time-profile-'+t.PARTIAL_ID,source)
self.assertIn('time-attestation.candidate.json',source)
self.assertIn('old_move_hresult_unknown=$true',source)
for forbidden in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory'):
self.assertNotIn(forbidden,source)
def test_diagnostic_executes_bound_reader_without_legacy_load_or_target_success(self):
import datetime as dt
from unittest.mock import Mock
manifest={'id':t.PARTIAL_ID,'generator_sha256':t.PARTIAL_GENERATOR_SHA,
'script_sha256':t.PARTIAL_SCRIPT_SHA,'request':{'config_sha256':t.PARTIAL_CONFIG_SHA}}
result={'id':t.PARTIAL_ID,'read_only':True,'retry_authorized':False,
'installation_verified':False,'clock_runtime_qualified':False}
access=Mock();access.powershell.return_value=result
expiry=(dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=1)).isoformat()
with tempfile.TemporaryDirectory() as root,patch.object(t,'ROOT',Path(root)), \
patch.object(t,'read',side_effect=[(b'original',manifest),(b'staged',None)]), \
patch.object(t,'load_case',side_effect=AssertionError('original case must not adopt new generator')), \
patch.object(t.raw_capture,'CaptureAccess',return_value=access), \
patch.object(t.prior.cb.contract,'protected_json',return_value={'expires_at':expiry}):
t.diagnose_partial()
call=access.powershell.call_args
executed=base64.b64decode(call.args[1]['source_base64'])
self.assertIn(t.sha(executed),call.args[0])
cases=list((Path(root)/'devstate/windows-time-profile-diagnostics').iterdir())
self.assertEqual(len(cases),1)
intent=json.loads((cases[0]/'intent.json').read_bytes())
receipt=json.loads((cases[0]/'receipt.json').read_bytes())
self.assertEqual(intent['reader_sha256'],t.sha(executed))
self.assertEqual(receipt['reader_sha256'],t.sha(executed))
self.assertTrue(receipt['old_move_hresult_unknown'])
self.assertEqual((cases[0]/'reader.ps1').read_bytes(),executed)
if __name__ == '__main__':
unittest.main()
+83 -1
View File
@@ -524,8 +524,90 @@ def target(action,ident):
write(output,canonical(result))
print(json.dumps({'id':ident,'action':action,'reply_sha256':sha(canonical(result)),'clock_runtime_qualified':False}))
# Dedicated read-only path for the already attempted original case. It never
# passes through load_case(): changing the generator must not rewrite or adopt
# the original staged controller/intent hash binding.
PARTIAL_ID = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
PARTIAL_MANIFEST_SHA = '0c9a3ffeed490757f7bd8c63d7e2ec28156212945094621f511e20679ce0b3b0'
PARTIAL_GENERATOR_SHA = 'a8d55b60d413c1d68f568c173e6ea32727cef8645e61eb772d24f98e22b0b10a'
PARTIAL_SCRIPT_SHA = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
PARTIAL_CONFIG_SHA = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
PARTIAL_CASE = ROOT.parent/'rust-discovery-agent-updater'/'devstate/windows-time-profile-config'/PARTIAL_ID
def partial_reader():
"""Fixed file/ACL/marker observation only; no service or publication code."""
require(sha(Path(prior.__file__).read_bytes())=='e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0'
and sha(Path(prior.u.__file__).read_bytes())=='f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38',
'exact original metadata-only primitive sources')
source = prior.u.SCRIPT
functions = []
for name in ('Check','BytesHash','Hash','AclHash','CheckControl'):
start=source.index('function '+name+'(');end=source.find('\nfunction ',start+1)
require(end>start,'closed original read-only function');functions.append(source[start:end])
native=prior.NATIVE.split('function FileIdentity(',1)[0]
identity='function FileIdentity('+prior.NATIVE.split('function FileIdentity(',1)[1].split('function Kernel(',1)[0]
header=r'''$ErrorActionPreference='Stop';$inputRecord=$global:RmmPartialReaderInput
if((($inputRecord.PSObject.Properties.Name|Sort-Object)-join',')-cne'kind'-or$inputRecord.kind-cne'original-public-time-profile-ad9-readonly'){throw 'Fixed original partial profile observation'}
$sys='S-1-5-18';$admin='S-1-5-32-544';$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value;$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoverySystemHelper')).Translate([Security.Principal.SecurityIdentifier]).Value
$folder='C:\ProgramData\RustDiscoveryBootstrap\time-profile-ad9fd154-b2be-4f5d-9e17-65abb721ceaf';$root='C:\ProgramData\RustDiscoverySystem';$active='C:\ProgramData\RustDiscoveryBootstrap\time-profile-initial-active.json'
'''
body=r'''function ErrorNumber($errorRecord){$ex=$errorRecord.Exception.GetBaseException();$h=[int64]$ex.HResult-band0xffffffffL;$win32=$null;if(($h-band0xffff0000L)-eq0x80070000L){$win32=$h-band0xffffL};return @{exception_type=$ex.GetType().FullName;hresult_hex=('0x{0:x8}'-f$h);win32_code=$win32}}
function ObservePublic($path){
if(!(Test-Path -LiteralPath $path)){return @{present=$false}}
try{Check $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt16384){throw 'Bounded public profile only'};$identity=FileIdentity $path;return @{present=$true;identity=$identity;attributes=[int64]$item.Attributes;creation_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();last_write_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();expected_hash=($identity.sha256-ceq'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b')}}catch{return @{present=$true;observation_failed=$true;error=(ErrorNumber $_)}}
}
CheckControl $folder $true;Check $root $true
$records=[ordered]@{};foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','publish-failure.json','result.json')){$path=Join-Path $folder $name;if(!(Test-Path -LiteralPath $path)){$records[$name]=@{present=$false};continue};CheckControl $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt2097152){throw 'Bounded original marker'};$value=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json
$record=@{present=$true;sha256=(Hash $path);bytes=$item.Length}
if($name-ceq'intent.json'){if($value.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$value.request.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.request.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original intent binding'};$record.install_not_before=$value.install_not_before;$record.no_retry=$value.no_retry}
if($name-ceq'publish-intent.json'){if($value.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.create_once-ne$true){throw 'Original publication binding'};$record.staged=$value.staged}
if($name-ceq'directory-acl-intent.json'){$record.old_sddl=$value.old_sddl};if($name-ceq'directory-acl-done.json'){$record.sddl=$value.sddl}
if($name-ceq'publish-failure.json'){$record.failure=@{exception_type=$value.exception_type;hresult_hex=$value.hresult_hex;win32_code=$value.win32_code}}
$records[$name]=$record
}
$activeRecord=@{present=$false};if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active).Length-gt8192){throw 'Bounded active original marker'};$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($a.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$a.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$a.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original active binding'};$activeRecord=@{present=$true;sha256=(Hash $active);id=$a.id;config_sha256=$a.config_sha256;script_sha256=$a.script_sha256}}
@{id='ad9fd154-b2be-4f5d-9e17-65abb721ceaf';read_only=$true;candidate=(ObservePublic (Join-Path $folder 'time-attestation.candidate.json'));target=(ObservePublic (Join-Path $root 'time-attestation.json'));records=$records;active=$activeRecord;root_sddl=(Get-Acl -LiteralPath $root).Sddl;old_move_hresult_unknown=$true;retry_authorized=$false;installation_verified=$false;clock_runtime_qualified=$false;private_key_read=$false;service_action=$false}|ConvertTo-Json -Depth 20 -Compress
'''
reader=header+'\n'+'\n'.join(functions)+'\n'+native+identity+'\n'+body
require(all(token not in reader for token in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory','function State','function Probe')),'read-only original partial observer')
return reader
def diagnose_partial():
# Only a future explicitly authorized maintenance window may call this.
# The original install/read code and original markers stay untouched.
import datetime as dt
import subprocess
raw,manifest=read(PARTIAL_CASE/'manifest.json',PARTIAL_MANIFEST_SHA)
require(manifest['id']==PARTIAL_ID and manifest['generator_sha256']==PARTIAL_GENERATOR_SHA
and manifest['script_sha256']==PARTIAL_SCRIPT_SHA
and manifest['request']['config_sha256']==PARTIAL_CONFIG_SHA,'fixed original failed installation only')
read(PARTIAL_CASE/'InstallPublicTimeProfile.ps1',PARTIAL_SCRIPT_SHA,decode=False)
access=raw_capture.CaptureAccess(MAIN)
grant=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
expiry=dt.datetime.fromisoformat(grant['expires_at'].replace('Z','+00:00'))
require((expiry-dt.datetime.now(dt.timezone.utc)).total_seconds()>=60,'current confirmed access window required for read')
source=partial_reader();digest=sha(source.encode());root=ROOT/'devstate/windows-time-profile-diagnostics';root.mkdir(mode=0o700,parents=True,exist_ok=True)
folder=root/str(uuid.uuid4());folder.mkdir(mode=0o700)
write(folder/'intent.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reader_sha256':digest,'read_only':True,'no_retry':True}))
# A small launcher avoids Windows' command-line limit. The source hash is
# generated from this closed reader, never accepted from a caller.
launcher=r'''$ErrorActionPreference='Stop';$q=([Console]::In.ReadLine()|ConvertFrom-Json);$raw=[Convert]::FromBase64String($q.source_base64);$h=[Security.Cryptography.SHA256]::Create();try{$s=([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()};if($s-cne'READER_SHA'){throw 'Exact original partial reader'};$global:RmmPartialReaderInput=$q.input_record;&([scriptblock]::Create([Text.Encoding]::UTF8.GetString($raw)))'''.replace('READER_SHA',digest)
write(folder/'reader.ps1',source.encode())
try:result=access.powershell(launcher,{'source_base64':base64.b64encode(source.encode()).decode(),'input_record':{'kind':'original-public-time-profile-ad9-readonly'}},timeout=45)
except subprocess.TimeoutExpired:
write(folder/'timeout.json',canonical({'read_only':True,'timeout_seconds':45,'old_move_hresult_unknown':True}));raise RuntimeError('original diagnostic read timed out; no publication attempted') from None
write(folder/'reply.json',canonical(result))
require(result['id']==PARTIAL_ID and result['read_only'] is True and result['retry_authorized'] is False
and result['installation_verified'] is False and result['clock_runtime_qualified'] is False,'diagnostic observation is no installation success or authority')
write(folder/'receipt.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'reader_sha256':digest,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reply_sha256':sha(canonical(result)),'read_only':True,'old_move_hresult_unknown':True}))
print(json.dumps({'id':folder.name,'original_case':PARTIAL_ID,'read_only':True,'receipt_sha256':sha((folder/'receipt.json').read_bytes())}))
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare','stage','install','read'));parser.add_argument('--case');arguments=parser.parse_args()
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare','stage','install','read','diagnose-partial'));parser.add_argument('--case');arguments=parser.parse_args()
if arguments.action=='guards': guards();print('PASS closed public-profile source guards; no target action')
elif arguments.action=='prepare': prepare()
elif arguments.action=='diagnose-partial':
require(arguments.case is None,'diagnostic is fixed to the original ad9 case');diagnose_partial()
else: target(arguments.action,arguments.case)
+203
View File
@@ -179,3 +179,206 @@ anschließend frische Heartbeats/ACKs sowie echte signierte Zeitbelege bleiben
getrennt zu prüfen. Eine spätere Fortsetzung benötigt zuerst eine lesende
Ursachenklärung und einen konkret geprüften Vertrag für den ursprünglichen
Teilfall; ein neuer Fall darf diesen Marker nicht umgehen.
## Unabhängiger lokaler Review des Move-Fehlers und fester Diagnosepfad
Der nachfolgende Review liest ausschließlich Quellen und vorhandene öffentliche
Originalbelege auf dem Entwicklungsrechner. Kein Gast-/Serverzugriff, keine
Installation, kein Retry und keine Freigabe wurden dabei ausgeführt.
Belegt ist der Ablauf bis zum Publish-Intent mit Kandidathash
`2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`,
1177Bytes, Volume9815088561147542064 und FileID6d990300000003000000000000000000.
Der spätere originale Read93143fc0… belegt das fehlende Ziel und fehlendes Resultat.
Er fragt jedoch die Kandidatdatei selbst nicht ab. Ihr aktueller Bestand ist
somit **nicht** nachgewiesen. Original-rootSDDL im Intent, ACL-done-SDDL und spätere
rootSDDL sind bytegleich: die ACL-Phase wurde ausgeführt, ohne effektive Rechte
zu ändern. Bestehende NoRetry-Marker bleiben bestehen.
Die genaue Ursache der IOException ist mit diesen Belegen nicht bestimmbar.
Der alte Fehlerbeleg enthält weder HRESULT noch nativen Fehlercode. Die statisch
geprüften WriteBytes-, FileIdentity- und FileVolume-Handles werden in `finally`
geschlossen; ein eigener Handleleak ist daraus nicht belegt. Das rechtfertigt
weder eine Sharing-Lockerung noch Dienststopp, ACL-Änderung, Antivirusausnahme,
Copy/Delete-Fallback oder erneuten Move. Microsoft beschreibt für
[File.Move](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move)
mehrere IOException-Ursachen; die Regeln für vorhandene Handles stehen getrennt
in [CreateFile](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew).
Sharing, Defender oder ein konkreter Win32-Code bleiben hier ausdrücklich
Hypothesen. Der ursprüngliche HRESULT darf aus späteren Lesefehlern nicht
rückwirkend abgeleitet werden.
Der bestehende Pythonoperator hat deshalb einen **separaten, ausschließlich
lesenden** Originalfallpfad `diagnose-partial` erhalten. Er bindet ausschließlich
Fallad9fd154-b2be-4f5d-9e17-65abb721ceaf, dessen Manifest0c9a3ffe…,
Originalgeneratora8d55b60…, Originalcontrollerd8b4fd4f… und Konfigurationshash2b4a….
Die vorhandenen Marker und Originaldateien werden nicht geändert. `load_case`
wird absichtlich nicht verwendet: dessen Generatorbindung darf nicht auf die
neue Quelle umgedeutet werden. Ebenso wird keine neue Skript-SHA als ursprüngliche
`request.script_sha256` ausgegeben. Der neue Reader hat eine eigene Source-SHA,
die der kleine In-Memory-Launcher vor der Ausführung prüft; genau ausgeführte
Readerbytes, Intent, rohe Antwort und separater Receipt werden ausschließlich
in einem neuen lokalen700/600-Diagnosefall gespeichert.
Geplanter Aufruf, **hier nicht ausgeführt**, erst nach erneut ausdrücklich
bestätigtem Zugang und dessen erfolgreichem Readback:
```sh
python3 /home/kevin/Schreibtisch/Coding/rust-discovery-signed-clock/deploy/windows/time_profile_config.py diagnose-partial
```
Kein `--case`: der Reader akzeptiert keine andere Fall-ID oder frei wählbare
Pfade. Die lokalen Originalbelege liegen weiterhin im Agent-Updater-Worktree.
Die geschützte aktuelle Zugangskonfiguration muss noch mindestens60s zulassen;
sonst erfolgt kein SSHaufruf. Native PowerShell-AST-/VM-Ausführung dieses neuen
Readers sind noch offen. Er enthält keine Publish-/ACL-/Serviceoperation und
fragt weder Uhrqualität noch Dienst-Snapshot ab.
Der Reader liefert nur aktuelle Kandidat-/Zielidentität, Größe, Hash, DACLhash,
Attribute und Zeiten sowie feste Originalmarker/active-Bindung und Root-SDDL.
Aktuelle Lesefehler werden mit Exceptiontyp/HRESULT und nur bei passender
HRESULT-Facility mit Win32-Code aufgezeichnet, ohne freien Fehlertext. Diese
Nummern gehören ausschließlich zum **neuen Leseversuch**. Er setzt immer
`old_move_hresult_unknown=true`, `retry_authorized=false`,
`installation_verified=false` und `clock_runtime_qualified=false`.
Das Ergebnis ist Grundlage einer späteren Entscheidung, keine Retryerlaubnis:
- Kandidat unverändert und Ziel fehlt: Veröffentlichung weiterhin nicht erfolgt;
im nächsten aktiven Wartungsfenster anhand des Originalzustands mit einem
überprüften Finalisierungsbefehl fertigstellen. Das MVP-/Profilvorhaben ist
bereits beauftragt; dafür keine pauschale zusätzliche Chatgenehmigung verlangen.
- Ziel vorhanden: weder Move noch Install erneut aufrufen; zuerst Ziel-/Kandidat-
FileID-/Hash-/ACLbindung und tatsächliche Laufzeitwirkung getrennt beurteilen.
- Fehlender/veränderter Kandidat, widersprüchliche Marker, andere Dateiidentität
oder Lesefehler: Teilzustand erhalten, keine automatische Rekonstruktion,
Löschung oder Rechte-/Dienständerung.
Lokal tatsächlich bestanden: Pythoncompile, bestehende Sourceguards und acht
Vertragsfälle, davon zwei neue für den geschlossenen Reader und seine exakte
Source-/Intent-/Receiptbindung ohne Legacy-Hashadoption. Der Transport ist dabei
vollständig gemockt; dies ist kein nativer Befund. Die Kontrollbelege des alten
fehlgeschlagenen Installationsfalls bleiben bytegleich erhalten. Ein konkreter
Publikationsfix wurde mangels belegter nativer Fehlerursache nicht erfunden.
## Nachlese durch die Bedienperson auf der Windows-VM
In der administrativen VM-Konsole konnte die Bedienperson den Kandidaten
`time-attestation.candidate.json` lesen. SHA-256 stimmte mit dem im
Publish-Intent hinterlegten Wert `2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`
überein. Für den festen Zielpfad unter `RustDiscoverySystem` meldete
PowerShell `ObjectNotFound`. Dieser Konsolenbefund ergänzt den früheren
Readback um den Inhalt des verbliebenen Kandidaten. FileID, DACL und
Dienstgeneration wurden bei dieser Konsolenabfrage nicht erfasst.
Für die Fortsetzung an derselben VM-Konsole liegt
[`Complete-OriginalTimeProfile.ps1`](../deploy/windows/Complete-OriginalTimeProfile.ps1)
bereit. Der Befehl übernimmt die Prüffunktionen aus den SHA-256-geprüften
Bytes des bereits installierten Controllers. Vor der Veröffentlichung prüft er
die ursprüngliche Datei-ID und das Volume, den Inhalt, die DACL, die
ursprünglichen Marker und beide laufenden Dienstgenerationen. Er hält die
beiden Prozesshandles während der Veröffentlichung offen. Ein exklusiv
erstellter zusätzlicher Marker verhindert eine doppelte Ausführung.
Nach der Verschiebung an den festen Zielpfad vergleicht das Skript die
Dateiidentität und die Dienstzustände erneut. Bei einem neuen Move-Fehler erfasst
es Fehlerklasse und HRESULT für diesen Aufruf. Ein erneuter Start trifft auf
den Abschlussmarker oder den vorhandenen Zielpfad und beendet sich. Das
Ergebnis einer erfolgreichen Veröffentlichung hält die separate
Laufzeitprüfung der beiden Dienstrollen ausdrücklich offen.
Lokal geprüft wurden die PowerShell-Syntax, die Bindung an die gespeicherten
Originalbelege und der Vergleich mit der tatsächlichen Kandidatenidentität.
Eine veränderte FileID wurde im lokalen Vergleich abgewiesen. Die Ausführung
des Abschlussbefehls auf der VM und die anschließende Zeitprüfung stehen aus.
## Ergebnis vom Konsolenschritt automatisch abholen
Für den vorbereiteten Profilabschluss steht `Open-TimeProfileReceiptWindow.ps1`
zur Verfügung. Die Bedienperson startet es auf der Windows-VM. Das Skript prüft
die beiden Downloads gegen feste SHA-256-Werte, öffnet den vorhandenen
Reverse-SSH-Transport und führt den festen Abschluss lokal aus. Die
Weiterleitung auf dem Server ist an `127.0.0.1:22240` gebunden. Auf der VM
endet sie an einem temporären Loopback-Port. Der Prozess sendet dort den
Abschlussstatus und die öffentlichen Belege der beiden Zeitdienstrollen.
Er liest keine Befehle vom Socket. Die Gast-Kontofrist und die Aufgabenplanung
werden nicht geändert. Strg+C oder zwölf Minuten beenden das Vordergrundfenster.
Die serverseitige Frist für den vorhandenen Transportschlüssel und der aktive
Abschalttimer wurden für den 15. November 2026, 18:00 Uhr MEZ, geprüft.
Beim Bereitstellen wurden der PowerShell-Parser, die Downloadhashes, die
bestehenden Quellprüfungen und die sechs lokalen Prüffälle für die Zeitbelege
ausgeführt. Ein Ergebnis von der VM liegt bei Bereitstellung noch nicht vor.
Der Ergebnisempfänger auf dem permanenten Server wurde anschließend gestartet.
Seine Anfangsprüfung des laufenden Gateways und der gespeicherten
Windows-Gerätebindung war erfolgreich. Der Server fragt den Loopback-Port
nur bei vorhandenem SSH-Listener ab und legt eingehende Belege im privaten
Fall `time-profile-receipt-f7f56e9f` ab. Für Zeitbelege verwendet er die
bestehende Rollen-, Boot-, Generations- und Altersprüfung mit je einer
Datenbanklesung vor und nach dem Empfang. Die Bereitstellung des Empfängers
belegt noch keine Profilveröffentlichung auf dem Gast.
## Rückmeldung der Windows-VM am 15. November um 17:05:36 Uhr MEZ
Der Empfänger hat im Fall `time-profile-receipt-f7f56e9f` die Antwort
`finalization_failed` gespeichert. Der Abschlussbefehl bestand die Prüfungen
auf Kandidat, Berechtigungen und Dienstgenerationen bis zur Veröffentlichung.
Der Aufruf von `File.Move` meldete HRESULT **0x80070020**
(`ERROR_SHARING_VIOLATION`). Zeile 94 gibt diesen Fehler an den Aufrufer
weiter. Empfangsbeleg SHA-256
`7cc51d44abfbe7949b0896053a463f3bd140b1844229e9ba206683db34d6f2ba`,
Ergebnis `172edeaf54ca08f4e5b1ad3662884da6ec217636ca30bbd8274e73140f6ef35b`.
Der Code des installierten Helpers öffnet das öffentliche Stammverzeichnis
mit Lesezugriff und ausschließlich `FILE_SHARE_READ` und hält diesen Handle
im laufenden Dienst. Ein Rename aus einem anderen Verzeichnis benötigt am
Zielverzeichnis `FILE_ADD_FILE`. Das erklärt einen konkreten Konflikt.
Die VM-Rückmeldung enthält keine Liste der tatsächlich offenen Handles.
Für den älteren Installationsaufruf ohne HRESULT bleibt der Fehlercode
unbekannt. Das laufende Konsolenskript hat keine weitere Veröffentlichung
versucht. Für diesen Lauf liegt keine erfolgreiche Zeitprüfung vor.
[Windows-Dateisystemregeln für Rename](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/87f86c9b-6c2a-4803-84b7-131a74a434fa)
### Erstprovisionierung nach dem belegten Sharingkonflikt
`Complete-OriginalTimeProfile.ps1 -InitialCreate` ist eine eigene Reparatur
für das bislang fehlende Ziel. Sie setzt den vorhandenen Abschlussintent und
den gespeicherten Fehler `File.Move / System.IO.IOException / 0x80070020`
voraus. Die ursprünglichen Quell-, ACL-, Dienst-, Geräte- und
Kandidatenbindungen gelten weiter. Der ursprüngliche Kandidat bleibt als
Referenz erhalten. Der alte Move-Erfolg und dessen `result.json` werden durch
diesen Pfad nicht nachträglich erzeugt.
Der feste neue Name wird genau einmal mit `CreateNew` angelegt. Windows
erhält dabei bereits eine geschützte DACL mit explizitem Leseverbot für die
beiden Service-SIDs. Der kontrollierende Prozess besitzt den einzigen
Datenhandle. Er schreibt und flusht die 1177 qualifizierten Bytes und liest sie
über denselben Handle vollständig zurück. Er prüft Hash, Volume, neue FileID,
einzigen Hardlink, Länge und DACL. Dann prüft er die ursprüngliche
Kandidatenidentität und die laufenden Dienste noch einmal und schreibt einen
Prüfbeleg. Erst jetzt setzt er die bereits gebundene endgültige DACL auf dem
gehaltenen Handle und prüft Identität, Hash und DACL erneut. Nach Schließen
folgt eine separate Prüfung beider Pfade und Dienste. Damit wird eine neue
Ziel-FileID dokumentiert. Die DACL des öffentlichen Ordners bleibt unverändert.
[Windows-Dateierstellung](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/498a5eeb-afc9-445f-99ed-a7e4b73c648b)
[.NET-Framework-Konstruktor mit Erstellungs-DACL](https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=netframework-4.8)
Eine vor der DACL-Freigabe unterbrochene Erstellung kann eine vorhandene
Teildatei mit gesperrtem Dienstzugriff hinterlassen. Nach erfolgter
DACL-Freigabe ist die Datei lesbar, auch wenn der Prozess vor dem
abschließenden Ergebnis ausfällt. Ein neuer Versuch wird in beiden Fällen
verweigert. Die getrennten `console-initial-create-*`-Dateien dokumentieren
Intent, verifizierte neue Zielidentität und tatsächlichen Abschluss oder
Fehlerphase. Das Ergebnis weist `clock_runtime_qualified=false` aus. Für
dessen positive Bewertung sind weiterhin die unabhängigen Zeitbelege der
installierten Dienste erforderlich.
Lokal bestanden Parserprüfung, Kompilierung des kleinen nativen
Handle-Readers, Prüfung seines Strukturlayouts und drei simulierte
Entscheidungsfälle mit echtem beziehungsweise verändertem Fehlerbeleg.
Der frühere lokale Prüfharness wählte beim ersten Strukturlayoutaufruf die
falsche .NET-Überladung; nach Angabe des Typs bestand die Prüfung. Der
Original-Kandidaten-/FileID-Vergleich und die acht bisherigen Profilfixtures
bestanden ebenfalls. Dieser Stand wurde auf der Windows-VM noch nicht
ausgeführt.