Compare commits

...
Author SHA1 Message Date
kevin_janssen dc3906272c Resume the verified empty Windows time profile by exclusive handle
Rust development slice / linux (push) Failing after 6s
2026-11-15 20:37:00 +01:00
kevin_janssen 454e08f942 Pin the verified descriptor-aware Windows finalizer in the receipt launcher
Rust development slice / linux (push) Failing after 7s
2026-11-15 20:29:08 +01:00
kevin_janssen 38e6df51ea Merge commit '5adf209'
Rust development slice / linux (push) Failing after 7s
# Conflicts:
#	docs/windows-time-profile-config.md
2026-11-15 20:29:06 +01:00
kevin_janssen 48662f97e3 Keep Windows receipt retries read-only after a recorded or incomplete attempt
Rust development slice / linux (push) Failing after 6s
2026-11-15 20:28:34 +01:00
3 changed files with 197 additions and 24 deletions
+159 -19
View File
@@ -3,8 +3,9 @@
# 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)
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'
@@ -54,8 +55,14 @@ $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) {
$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
@@ -87,6 +94,19 @@ if ($publish.create_once -ne $true -or $publish.config_sha256 -cne $configHash -
(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'
@@ -103,6 +123,7 @@ function Initialize-InitialProfileNative {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
@@ -116,7 +137,82 @@ public static class RmmInitialProfileFile {
[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());
@@ -153,6 +249,13 @@ function Get-HeldProfileIdentity([IO.FileStream]$Stream) {
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'
@@ -168,20 +271,39 @@ function New-OriginalPublicProfile {
$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}
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 {
$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)
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 ($actualSddl -cne $draftSddl) {
if (!(Test-ProfileDescriptor $draftSddl $actualSddl)) {
$descriptorFailure = @{expected_sddl=$draftSddl; actual_sddl=$actualSddl; bytes=$null}
try {
$descriptorFailure.bytes = $stream.Length
@@ -194,13 +316,27 @@ function New-OriginalPublicProfile {
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 -ceq ('0' * 32) -or $new.sha256 -cne $configHash -or
$new.acl_sha256 -cne (BytesHash ([Text.Encoding]::UTF8.GetBytes($draftSddl)))) {
$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)
@@ -209,7 +345,7 @@ function New-OriginalPublicProfile {
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') @{
WriteNew $attemptVerified @{
id=$caseId; utc=$since; original_candidate=$expected; held_target=$new
}
# Change only the DACL by handle after the verified bytes and FileID
@@ -219,7 +355,9 @@ function New-OriginalPublicProfile {
$final.SetSecurityDescriptorSddlForm($stagedAcl.Sddl, $accessOnly)
$stream.SetAccessControl($final)
$stream.Flush($true)
$new.acl_sha256 = $expected.acl_sha256
$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() }
@@ -232,17 +370,19 @@ function New-OriginalPublicProfile {
SameLive $before $after
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
WriteNew $initialResult @{
$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 }
WriteNew $initialError $failure
if ($reserved) { WriteNew $attemptError $failure }
throw
}
}
@@ -253,10 +393,10 @@ try {
try {
$null = Kernel 'agent' $before.service $heldAgent
$null = Kernel 'helper' $before.helper_service $heldHelper
if ($InitialCreate) {
if ($InitialCreate -or $ResumeEmpty) {
$rootAclHash = '186d85132cf0e16cbb9623ad9636b7777741939a8cae3d689a2af1eb267a7f49'
New-OriginalPublicProfile
'Zeitprofil erstmalig erstellt und anhand seiner neuen Dateiidentitaet geprueft.'
'Zeitprofil am gebundenen Dateihandle veroeffentlicht und nachgelesen.'
return
}
# WriteNew uses CreateNew. Concurrent or later invocations cannot republish.
@@ -7,7 +7,7 @@ $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/9a6599fddd6ba08ca92e5675fdfa004895603b04/deploy/windows'
$base = 'https://gitea.incoso.eu/kevin_janssen/rust-discovery/raw/commit/38e6df51ea57a76ec2d5462513d59e855f36c0f4/deploy/windows'
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
$case = Join-Path $bootstrap "time-profile-$caseId"
@@ -24,7 +24,7 @@ $null = New-Item -ItemType Directory -Path $work
$listener = $null
$ssh = $null
$scripts = [ordered]@{
'Complete-OriginalTimeProfile.ps1' = 'a316440d3fc79d3c9350199418ff8d4b0e2215a5c989a16e997784c7ec1c5f7c'
'Complete-OriginalTimeProfile.ps1' = 'c2fb92ebd0f4ab19545b55ad92d7a9b21ec6e3604d33107d0dd78882162be131'
'Read-PassiveTimeSamples.ps1' = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
}
try {
@@ -47,8 +47,14 @@ try {
Write-Host 'Wartungsfenster aktiv. Dieses Fenster offen lassen. Strg+C beendet es.'
$receipt = [ordered]@{session=$session; case_id=$caseId; method='initial_create'; phase='preflight'; read_only_channel=$true}
$result = Join-Path $case 'console-initial-create-result.json'
$intentPath = Join-Path $case 'console-initial-create-intent.json'
$failurePath = Join-Path $case 'console-initial-create-error.json'
$receipt.finalizer_invoked = $false
try {
if (Test-Path -LiteralPath $failurePath) { throw 'Previous profile finalization error recorded' }
if (!(Test-Path -LiteralPath $result)) {
if (Test-Path -LiteralPath $intentPath) { throw 'Previous profile finalization intent without result' }
$receipt.finalizer_invoked = $true
$null = & (Join-Path $work 'Complete-OriginalTimeProfile.ps1') -InitialCreate
}
$record = Get-Content -LiteralPath $result -Raw | ConvertFrom-Json
@@ -57,7 +63,7 @@ try {
$record.initial_create -ne $true -or $record.source_candidate_preserved -ne $true -or
$record.services_changed -ne $false -or $record.private_key_read -ne $false -or $record.clock_runtime_qualified -ne $false -or
$actual.Hash -ne '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b') { throw 'Unexpected publication result' }
$marker = Get-Content -LiteralPath (Join-Path $case 'console-initial-create-intent.json') -Raw | ConvertFrom-Json
$marker = Get-Content -LiteralPath $intentPath -Raw | ConvertFrom-Json
if ($marker.id -cne $caseId -or $marker.utc -cne $record.publication_since -or
$marker.config_sha256 -ne $actual.Hash -or $record.configuration.sha256 -ne $actual.Hash -or
$record.original_candidate.file_id -cne '6d990300000003000000000000000000' -or
@@ -79,10 +85,24 @@ try {
$receipt.line = $_.InvocationInfo.ScriptLineNumber
$receipt.file = [IO.Path]::GetFileName($_.InvocationInfo.ScriptName)
Write-Warning $_.Exception.Message
$failurePath = Join-Path $case 'console-initial-create-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.hresult = $failure.hresult; if ($failure.phase -cmatch '^[A-Za-z][A-Za-z0-9_.-]{0,63}$') { $receipt.failure_phase = $failure.phase } }
if ($failure.id -ceq $caseId -and $failure.hresult -cmatch '^0x[0-9A-Fa-f]{8}$') {
$receipt.hresult = $failure.hresult
if ($failure.phase -cmatch '^[A-Za-z][A-Za-z0-9_.-]{0,63}$') { $receipt.failure_phase = $failure.phase }
$descriptor = $failure.creation_descriptor
if ($failure.phase -ceq 'verify_creation' -and $null -ne $descriptor -and
$descriptor.expected_sddl -is [string] -and $descriptor.expected_sddl.Length -le 4096 -and
$descriptor.actual_sddl -is [string] -and $descriptor.actual_sddl.Length -le 4096) {
$receipt.creation_descriptor = @{
expected_sddl=$descriptor.expected_sddl; actual_sddl=$descriptor.actual_sddl; bytes=$descriptor.bytes
}
if ($descriptor.file_id -cmatch '^[0-9a-f]{32}$' -and $descriptor.volume_serial -cmatch '^[0-9]{1,20}$') {
$receipt.creation_descriptor.file_id = $descriptor.file_id
$receipt.creation_descriptor.volume_serial = $descriptor.volume_serial
}
}
}
}
}
$readScript = Join-Path $work 'Read-PassiveTimeSamples.ps1'
+13
View File
@@ -489,6 +489,19 @@ Gerät, Agent, Assignment, Enrollmentgeneration und authentifiziertes Zertifikat
stimmten mit dem früheren Abnahmebeleg überein. Beleg-SHA-256
`7ea828b42b3c7948956aad56845502ffa52192ce6ca14728203f8574d70a28ec`.
Der Konsolenstarter prüft im aktualisierten Quellstand vor einem Aufruf des
Abschlussbefehls auf einen vorhandenen Fehler oder einen offenen Intent.
In beiden Fällen liest er den vorhandenen Stand. Die Rückmeldung kennzeichnet
mit `finalizer_invoked`, ob dieser Start den Abschlussbefehl aufgerufen hat.
Enthält der Fehlerbeleg die bei der Erstellung verglichenen Deskriptoren,
überträgt der Starter sie mit der Länge und den vorhandenen Datei-IDs an den
Ergebnisempfänger. Ältere Fehlerbelege bleiben ohne diese Angaben lesbar.
Der PowerShell-Parser und fünf lokale Fälle bestanden: erster Aufruf,
vorliegender Fehler, offener Intent, bereits vorliegender Erfolg und
widersprüchliche Erfolgs-/Fehlermarker. Nur der erste Fall rief im Test den
simulierten Abschluss auf. Diese Prüfung lief auf dem Entwicklungsrechner.
### Fehlerbeleg beim ersten Vergleich des Sicherheitsdeskriptors
Unterscheiden sich Soll- und Ist-SDDL an der neu angelegten Datei, erfasst der