#requires -Version 5.1 #requires -RunAsAdministrator [CmdletBinding()] param([Parameter(Mandatory)][ValidateSet('Inspect','Prepare','Activate','Readback')][string]$Mode) $ErrorActionPreference = 'Stop' $caseId = '49c230d8-fb5d-4c64-96b6-e0edce03ed90' $boot = 'C:\ProgramData\RustDiscoveryBootstrap' $case = Join-Path $boot "job-config-$caseId" $root = 'C:\ProgramData\RustDiscovery' $state = Join-Path $root 'state' $config = Join-Path $root 'config.json' $binding = Join-Path $root 'binding.json' $jobs = Join-Path $state 'jobs' $systemRoot = 'C:\ProgramData\RustDiscoverySystem' $pin = Join-Path $systemRoot 'agent-pin.json' $clock = Join-Path $systemRoot 'time-attestation.json' $image = 'C:\Program Files\RustDiscovery\rmm-agent-windows.exe' $helperImage = 'C:\Program Files\RustDiscovery\rmm-helper-windows.exe' $oldConfig = '7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851' $oldConfigAcl = '014e89cc8674259dd9ac7f490ffef056b85ada96c6e3574c23f27668b7a9b991' $expectedBinding = '9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde' $oldAgent = '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c' $newAgent = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f' $helper = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e' $agentSid = ([Security.Principal.NTAccount]::new('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value $utf8 = [Text.UTF8Encoding]::new($false,$true) $sidType = [Security.Principal.SecurityIdentifier] $admins = @('S-1-5-18','S-1-5-32-544') $ready = Join-Path $case 'prepared.json' $entered = Join-Path $case 'activation-intent.json' $done = Join-Path $case 'activated.json' $candidate = Join-Path $case 'job-config.candidate.json' $original = Join-Path $case 'passive-config.original.json' $publicBinding = Join-Path $case 'public-binding.json' $next = Join-Path $root "config-$caseId.next" $backup = Join-Path $case 'replaced.original.json' function Assert-NormalPath([string]$Path,[bool]$Directory) { $item = Get-Item -LiteralPath $Path -Force if ($item.PSIsContainer -ne $Directory) { throw "Unerwarteter Pfadtyp: $Path" } while ($null -ne $item) { if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Reparsepunkt: $Path" } if ($item -is [IO.FileInfo]) { $item = $item.Directory } else { $item = $item.Parent } } } function Get-PublicHash([string]$Path) { Assert-NormalPath $Path $false return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } function Get-BytesDigest([byte[]]$Bytes) { $alg = [Security.Cryptography.SHA256]::Create() try { return [BitConverter]::ToString($alg.ComputeHash($Bytes)).Replace('-','').ToLowerInvariant() } finally { $alg.Dispose() } } function Assert-DirectoryAcl([string]$Path,[bool]$AgentCanRead) { Assert-NormalPath $Path $true $acl = Get-Acl -LiteralPath $Path if ($acl.GetOwner($sidType).Value -notin $admins) { throw "Verzeichniseigentuemer: $Path" } $rules = @($acl.GetAccessRules($true,$true,$sidType)) if (!$rules.Count) { throw "Leere DACL: $Path" } foreach ($rule in $rules) { $sid = $rule.IdentityReference.Value if ($rule.AccessControlType -ne 'Allow' -or ($sid -notin $admins -and !($AgentCanRead -and $sid -ceq $agentSid -and (([long]$rule.FileSystemRights -band (-bnot 0x1200a9)) -eq 0)))) { throw "Verzeichnisrechte: $Path" } } } function Write-Once([string]$Path,[byte[]]$Bytes,[Security.AccessControl.FileSecurity]$Acl) { if ($null -eq $Acl) { $stream = [IO.File]::Open($Path,'CreateNew','Write','None') } else { $stream = [IO.FileStream]::new($Path,[IO.FileMode]::CreateNew,[Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None,4096,[IO.FileOptions]::WriteThrough,$Acl) } try { $stream.Write($Bytes,0,$Bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() } } function Save-Record([string]$Path,$Record) { Write-Once $Path ($utf8.GetBytes(($Record | ConvertTo-Json -Depth 8 -Compress))) $null } function Read-PublicJson([string]$Path) { Assert-NormalPath $Path $false if ((Get-Item -LiteralPath $Path).Length -gt 32768) { throw "Datei zu gross: $Path" } return ($utf8.GetString([IO.File]::ReadAllBytes($Path)) | ConvertFrom-Json) } function Get-OriginalAcl { $acl = Get-Acl -LiteralPath $config if ((Get-BytesDigest ($utf8.GetBytes($acl.Sddl))) -cne $oldConfigAcl) { throw 'Originale Konfigurations-DACL abweichend' } return $acl } function Assert-FileAcl([string]$Path,$Expected) { $sections = [Security.AccessControl.AccessControlSections]'Owner,Group,Access' $actual = (Get-Acl -LiteralPath $Path).GetSecurityDescriptorSddlForm($sections) $wanted = $Expected.GetSecurityDescriptorSddlForm($sections) # File creation can omit the auto-inherited marker on this VM. Owner, # group, protected DACL, access masks and ACE sequence must all match. if ($actual -cne $wanted -and $actual -cne $wanted.Replace('D:PAI(', 'D:P(')) { throw "Dateiberechtigungen abweichend: $Path" } } function Get-ConfigurationInputs { if ((Get-PublicHash $config) -cne $oldConfig) { throw 'Passive Originalkonfiguration abweichend' } $null = Get-OriginalAcl $value = Read-PublicJson $config $names = @($value.PSObject.Properties.Name | Sort-Object) if (($names -join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport' -or $value.server_name -cne 'discovery.ease-technologies.de' -or $value.state_directory -ine $state -or $value.transport -cne 'auto') { throw 'Unerwartete passive Konfigurationsfelder' } $value | Add-Member -NotePropertyName job_binding_file -NotePropertyValue $binding $value | Add-Member -NotePropertyName enable_jobs -NotePropertyValue $true $value | Add-Member -NotePropertyName windows_execution_profile -NotePropertyValue 'powershell_51_remote_signed' $peer = Read-PublicJson $pin $b = $peer.binding $canonical = [ordered]@{agent_id=$b.agent_id;asset_id=$b.asset_id;assignment_version=$b.assignment_version; enrollment_generation=$b.enrollment_generation;public_key_hex=$b.public_key_hex;tenant_id=$b.tenant_id} $bindingBytes = $utf8.GetBytes(($canonical | ConvertTo-Json -Compress)) if ((Get-BytesDigest $bindingBytes) -cne $expectedBinding) { throw 'Oeffentliche Jobbindung abweichend' } return @{config=$utf8.GetBytes(($value | ConvertTo-Json -Compress)); binding=$bindingBytes} } function Get-JobsAcl { $acl = [Security.AccessControl.DirectorySecurity]::new() $acl.SetSecurityDescriptorSddlForm("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$agentSid)") return $acl } function Assert-JobsAcl { Assert-NormalPath $jobs $true $acl = Get-Acl -LiteralPath $jobs if (!$acl.AreAccessRulesProtected -or $acl.GetOwner($sidType).Value -notin $admins) { throw 'Jobverzeichnis nicht geschuetzt' } $expected = (Get-JobsAcl).GetAccessRules($true,$false,$sidType) $rules = $acl.GetAccessRules($true,$true,$sidType) if ($rules.Count -ne $expected.Count) { throw 'Job-DACL Anzahl' } foreach ($e in $expected) { $match = @($rules | Where-Object { !$_.IsInherited -and $_.IdentityReference.Value -ceq $e.IdentityReference.Value -and $_.FileSystemRights -eq $e.FileSystemRights -and $_.AccessControlType -eq $e.AccessControlType -and $_.InheritanceFlags -eq $e.InheritanceFlags -and $_.PropagationFlags -eq $e.PropagationFlags }) if ($match.Count -ne 1) { throw 'Job-DACL abweichend' } } } function Get-Readback { $files = [ordered]@{} foreach ($p in @($config,$binding,$candidate,$publicBinding,$original,$next,$backup,$ready,$entered,$done,$image,$helperImage,$clock)) { $files[$p] = if ([IO.File]::Exists($p)) { Get-PublicHash $p } else { $null } } $jobsAcl = $null if (Test-Path -LiteralPath $jobs) { try { Assert-JobsAcl; $jobsAcl = $true } catch { $jobsAcl = $false } } $aclHashes = [ordered]@{} foreach ($p in @($root,$state,$config,$binding,$jobs,$case)) { if (Test-Path -LiteralPath $p) { Assert-NormalPath $p ([IO.Directory]::Exists($p)) $aclHashes[$p] = Get-BytesDigest ($utf8.GetBytes((Get-Acl -LiteralPath $p).Sddl)) } } $live = Read-PublicJson $config return [ordered]@{case_id=$caseId; agent_state=[string](Get-Service RmmDiscoveryWindows).Status; helper_state=[string](Get-Service RmmDiscoverySystemHelper).Status; files=$files; acl_sha256=$aclHashes; job_profile=$live.windows_execution_profile; jobs_enabled=($live.enable_jobs -eq $true); binding_path_matches=($live.job_binding_file -ceq $binding); jobs_directory=[IO.Directory]::Exists($jobs); jobs_acl_verified=$jobsAcl} } Assert-DirectoryAcl $boot $false Assert-DirectoryAcl $root $true Assert-NormalPath $state $true if (Test-Path -LiteralPath $case) { Assert-DirectoryAcl $case $false } if ($Mode -in @('Inspect','Readback')) { Get-Readback | ConvertTo-Json -Depth 5; return } if ((Get-PublicHash $helperImage) -cne $helper) { throw 'Helper-Build abweichend' } $inputs = Get-ConfigurationInputs $configHash = Get-BytesDigest $inputs.config foreach ($p in @($jobs,$binding,$next,$backup,$entered,$done)) { if (Test-Path -LiteralPath $p) { throw 'Frueherer oder teilweiser Wechsel: Readback verwenden' } } if ($Mode -eq 'Prepare') { if ((Get-PublicHash $image) -cne $oldAgent -or (Get-Service RmmDiscoveryWindows).Status -ne 'Running') { throw 'Passiver Ausgangsagent erforderlich' } if (Test-Path -LiteralPath $case) { throw 'Vorhandener Vorbereitungsfall: Readback verwenden' } $caseAcl = [Security.AccessControl.DirectorySecurity]::new() $caseAcl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)') $null = [IO.Directory]::CreateDirectory($case,$caseAcl) Assert-DirectoryAcl $case $false Write-Once $original ([IO.File]::ReadAllBytes($config)) $null Write-Once $candidate $inputs.config $null Write-Once $publicBinding $inputs.binding $null if ((Get-PublicHash $candidate) -cne $configHash -or (Get-PublicHash $original) -cne $oldConfig -or (Get-PublicHash $publicBinding) -cne $expectedBinding) { throw 'Vorbereitungsdateien abweichend' } Save-Record $ready @{case_id=$caseId; config_sha256=$configHash; original_sha256=$oldConfig; binding_sha256=$expectedBinding} Get-Readback | ConvertTo-Json -Depth 5 return } $prepared = Read-PublicJson $ready if ($prepared.case_id -cne $caseId -or $prepared.config_sha256 -cne $configHash -or (Get-PublicHash $candidate) -cne $configHash -or (Get-PublicHash $original) -cne $oldConfig -or (Get-PublicHash $publicBinding) -cne $expectedBinding) { throw 'Vorbereitungsbeleg abweichend' } if ((Get-PublicHash $image) -cne $newAgent -or (Get-Service RmmDiscoveryWindows).Status -ne 'Stopped') { throw 'Neues Agentimage und gestoppter Dienst erforderlich' } $peer = Read-PublicJson $pin $time = Read-PublicJson $clock $roles = @($time.trusted_os_active_guest.qualifications) if ($peer.agent.binary_sha256 -cne $newAgent -or $peer.helper.binary_sha256 -cne $helper -or $roles.Count -ne 2 -or @($roles | Where-Object { $_.role -ceq 'agent' -and $_.binary_sha256 -ceq $newAgent }).Count -ne 1 -or @($roles | Where-Object { $_.role -ceq 'system_helper' -and $_.binary_sha256 -ceq $helper }).Count -ne 1) { throw 'Paar-Pins und Zeitprofil abweichend' } $acl = Get-OriginalAcl Save-Record $entered @{case_id=$caseId; utc=[DateTime]::UtcNow.ToString('o'); config_sha256=$configHash; binding_sha256=$expectedBinding} Write-Once $binding $inputs.binding $acl Assert-FileAcl $binding $acl $null = [IO.Directory]::CreateDirectory($jobs,(Get-JobsAcl)) Assert-JobsAcl Write-Once $next $inputs.config $acl Assert-FileAcl $next $acl if ((Get-PublicHash $binding) -cne $expectedBinding -or (Get-PublicHash $next) -cne $configHash -or (Get-PublicHash $config) -cne $oldConfig) { throw 'Vor Austausch unerwartete Dateien' } [IO.File]::Replace($next,$config,$backup,$false) Assert-FileAcl $config $acl if ((Get-PublicHash $config) -cne $configHash -or (Get-PublicHash $backup) -cne $oldConfig) { throw 'Konfigurationswechsel nicht bestaetigt' } Save-Record $done @{case_id=$caseId; utc=[DateTime]::UtcNow.ToString('o'); config_sha256=$configHash; binding_sha256=$expectedBinding} Get-Readback | ConvertTo-Json -Depth 5