diff --git a/crates/agent-windows/examples/windows_system_policy_prepare.rs b/crates/agent-windows/examples/windows_system_policy_prepare.rs new file mode 100644 index 0000000..4567610 --- /dev/null +++ b/crates/agent-windows/examples/windows_system_policy_prepare.rs @@ -0,0 +1,122 @@ +//! Offline typed public-metadata renderer for the first approved SYSTEM script. +//! It performs no file write, service operation, IPC, job or policy activation. +#[cfg(all(windows, feature = "system-helper"))] +fn main() -> anyhow::Result<()> { + use anyhow::{Result, ensure}; + use rmm_agent_windows::helper_system::Settings; + use rmm_domain::jobs::{PrivilegedScriptProfile, hash}; + use serde::Deserialize; + use std::io::{Read, Write}; + use uuid::Uuid; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Input { + schema_version: u32, + current_settings: Vec, + current_settings_sha256: String, + agent_binary_sha256: String, + helper_binary_sha256: String, + qualification_reference: Uuid, + native_prerequisite_result: serde_json::Value, + } + fn digest(value: &str) -> bool { + rmm_domain::agent_update::digest(value) + } + fn render(input: Input) -> Result { + ensure!( + input.schema_version == 1 + && input.current_settings.len() <= 32768 + && hash(&input.current_settings) == input.current_settings_sha256 + && digest(&input.agent_binary_sha256) + && digest(&input.helper_binary_sha256) + && !input.qualification_reference.is_nil(), + "SYSTEM_PREPARE_INPUT" + ); + let mut settings: Settings = serde_json::from_slice(&input.current_settings)?; + settings.validate()?; + ensure!( + !settings.enable_effects + && !settings.allow_reboot + && settings.allowed_services.is_empty() + && settings + .allowed_msi_recipe_sha256 + .as_ref() + .is_none_or(|v| v.is_empty()) + && settings.allowed_script_profiles.is_none() + && settings.helper.binary_sha256 == input.helper_binary_sha256, + "SYSTEM_PREPARE_ORIGINAL_PASSIVE_SCRIPT_ONLY_SCOPE" + ); + let evidence = &input.native_prerequisite_result; + ensure!( + evidence["schema_version"] == 1 + && evidence["platform"] == "windows-x86_64" + && evidence["scope"] == "native_prerequisites_only" + && evidence["source"] == "operator_reviewed_native_units_and_peer" + && evidence["status"] == "passed" + && evidence["target_job_executed"] == false + && evidence["qualification_reference"] == input.qualification_reference.to_string() + && evidence["agent_binary_sha256"] == input.agent_binary_sha256 + && evidence["helper_binary_sha256"] == input.helper_binary_sha256 + && evidence["validated_actions"] == serde_json::json!(["run_script"]) + && evidence["evidence_sha256"] + .as_array() + .is_some_and(|items| !items.is_empty() + && items.len() <= 16 + && items.iter().all(|v| v.as_str().is_some_and(digest))), + "SYSTEM_PREPARE_ACTUAL_PREREQUISITE_RESULT_REQUIRED" + ); + settings.schema_version = 3; + settings.agent.binary_sha256 = input.agent_binary_sha256.clone(); + settings.max_runtime_seconds = 30; + settings.enable_effects = true; + settings.allow_reboot = false; + settings.allowed_services.clear(); + settings.allowed_msi_recipe_sha256 = None; + settings.allowed_script_profiles = Some(vec![PrivilegedScriptProfile::FullMaintenanceV1]); + settings.validate()?; + let settings_bytes = serde_json::to_vec(&settings)?; + let pin = settings.pin()?; + let pin_bytes = serde_json::to_vec(&pin)?; + ensure!( + pin.policy_sha256 == hash(&settings_bytes), + "SYSTEM_PREPARE_CANONICAL_POLICY" + ); + let native_result = serde_json::to_vec(evidence)?; + ensure!( + native_result.len() <= 65536, + "SYSTEM_PREPARE_NATIVE_RESULT_LIMIT" + ); + let qualification = serde_json::json!({"schema_version":1, + "tenant_id":settings.binding.tenant_id,"asset_id":settings.binding.asset_id, + "agent_id":settings.binding.agent_id,"enrollment_generation":settings.binding.enrollment_generation, + "assignment_version":settings.binding.assignment_version, + "agent_binary_sha256":input.agent_binary_sha256, + "helper_binary_sha256":input.helper_binary_sha256,"policy_sha256":pin.policy_sha256, + "native_result_sha256":hash(&native_result),"qualification_reference":input.qualification_reference, + "actions":["run_script"]}); + let qualification_bytes = serde_json::to_vec(&qualification)?; + Ok( + serde_json::json!({"schema_version":1,"source":"actual_rust_settings_codec", + "prepared_only":true,"target_mutations":false,"target_job_executed":false, + "settings_bytes":settings_bytes,"settings_sha256":hash(&settings_bytes), + "policy_sha256":pin.policy_sha256,"pin_bytes":pin_bytes,"pin_sha256":hash(&pin_bytes), + "native_result_bytes":native_result,"native_result_sha256":hash(&native_result), + "qualification_bytes":qualification_bytes,"qualification_sha256":hash(&qualification_bytes), + "allowed_actions":["run_script"],"allow_reboot":false,"allow_msi":false,"allow_scm":false}), + ) + } + let mut raw = Vec::new(); + std::io::stdin() + .take(256 * 1024 + 1) + .read_to_end(&mut raw)?; + ensure!(raw.len() <= 256 * 1024, "SYSTEM_PREPARE_FRAME_LIMIT"); + let output = render(serde_json::from_slice(&raw)?)?; + std::io::stdout().write_all(&serde_json::to_vec(&output)?)?; + std::io::stdout().write_all(b"\n")?; + Ok(()) +} +#[cfg(not(all(windows, feature = "system-helper")))] +fn main() { + eprintln!("Windows/system-helper typed renderer only; no operation executed"); + std::process::exit(2); +} diff --git a/deploy/windows/Prepare-CertificateAcceptanceFixture.ps1 b/deploy/windows/Prepare-CertificateAcceptanceFixture.ps1 new file mode 100644 index 0000000..b070cc0 --- /dev/null +++ b/deploy/windows/Prepare-CertificateAcceptanceFixture.ps1 @@ -0,0 +1,80 @@ +# Bootstrap only: stages one separate certificate fixture; never executes it. +# Input is one protected stdin JSON line. Never put the enrollment token in arguments. +$ErrorActionPreference = 'Stop' +$p = [Console]::In.ReadLine() | ConvertFrom-Json +if ((($p.PSObject.Properties.Name | Sort-Object) -join ',') -cne 'ca_base64,ca_sha256,case_id,enrollment_token') { throw 'Fixed certificate fixture input' } +if ([string]([guid]$p.case_id) -cne $p.case_id -or [guid]$p.case_id -eq [guid]::Empty -or $p.ca_sha256 -cnotmatch '^[0-9a-f]{64}$' -or $p.enrollment_token -cnotmatch '^[0-9a-f]{64}$') { throw 'Fixture input format' } +$sys = 'S-1-5-18'; $admin = 'S-1-5-32-544' +$actor = (New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value +$sdkHash = 'c6b581b60ce803318ff946cd3cc8306aa8589d6bff6b022c0bf1d48eb8f5a8e1' +$uploaded = 'C:\ProgramData\RustDiscoveryBootstrap\' + $sdkHash + '\WindowsCertificateAcceptanceSDK.exe' +$artifactRoot = 'C:\Program Files\RustDiscoveryCertificateAcceptance' +$version = Join-Path $artifactRoot $sdkHash +$sdk = Join-Path $version 'WindowsCertificateAcceptanceSDK.exe' +$parent = 'C:\ProgramData\RustDiscovery\certificate-acceptance' +$case = Join-Path $parent $p.case_id +function Hash-Bytes([byte[]]$bytes) { + $h = [Security.Cryptography.SHA256]::Create() + try { return ([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant() } finally { $h.Dispose() } +} +function Check-Path([string]$path,[bool]$directory,[bool]$actorWrites) { + $item = Get-Item -LiteralPath $path -Force + if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Protected regular fixture path' } + if (!$directory -and $item.LinkType) { throw 'Fixture hardlink forbidden' } + $acl = Get-Acl -LiteralPath $path + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($sys,$admin) -or !$acl.AreAccessRulesProtected) { throw 'Protected fixture owner and DACL' } + $seen = @{} + foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) { + $sid = $rule.IdentityReference.Value; $rights = [int64]$rule.FileSystemRights + if ($rule.AccessControlType -ne 'Allow' -or $sid -notin @($sys,$admin,$actor)) { throw 'Fixture principal allowlist' } + $expected = 1179817 + if ($sid -in @($sys,$admin) -or $actorWrites) { $expected = 2032127 } + if ($rights -ne $expected) { throw 'Exact fixture rights' } + $seen[$sid] = $true + } + foreach ($sid in @($sys,$admin,$actor)) { if (!$seen[$sid]) { throw 'Missing fixture principal' } } +} +function Protect-Path([string]$path,[bool]$directory,[bool]$actorWrites) { + if ($directory) { $acl = New-Object Security.AccessControl.DirectorySecurity } else { $acl = New-Object Security.AccessControl.FileSecurity } + $acl.SetAccessRuleProtection($true,$false) + $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin))) + $inherit = 'None'; if ($directory) { $inherit = 'ContainerInherit,ObjectInherit' } + foreach ($sid in @($sys,$admin,$actor)) { + $rights = 'ReadAndExecute'; if ($sid -in @($sys,$admin) -or $actorWrites) { $rights = 'FullControl' } + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,$inherit,'None','Allow'))) + } + Set-Acl -LiteralPath $path -AclObject $acl + Check-Path $path $directory $actorWrites +} +function Ensure-Directory([string]$path,[bool]$actorWrites) { + if (!(Test-Path -LiteralPath $path)) { + New-Item -ItemType Directory -Path $path | Out-Null + Protect-Path $path $true $actorWrites + } else { Check-Path $path $true $actorWrites } +} +function Write-NewPrivate([string]$path,[byte[]]$bytes) { + # Inherited case DACL is checked before any secret byte is written. + $f = [IO.File]::Open($path,'CreateNew','Write','None') + try { + Protect-Path $path $false $true + $f.Write($bytes,0,$bytes.Length); $f.Flush($true) + } finally { $f.Dispose() } +} +$ca = [Convert]::FromBase64String($p.ca_base64) +if ($ca.Length -gt 32768 -or (Hash-Bytes $ca) -cne $p.ca_sha256 -or [Text.Encoding]::ASCII.GetString($ca) -notmatch '^-----BEGIN CERTIFICATE-----') { throw 'Exact public fixture CA' } +if (Test-Path -LiteralPath $case) { throw 'Fixture exists; readback only, never repeat preparation' } +$source = Get-Item -LiteralPath $uploaded -Force +if ($source.PSIsContainer -or ($source.Attributes -band [IO.FileAttributes]::ReparsePoint) -or (Get-FileHash -LiteralPath $uploaded).Hash.ToLowerInvariant() -cne $sdkHash) { throw 'Exact staged SDK required' } +Ensure-Directory $artifactRoot $false +Ensure-Directory $version $false +if (!(Test-Path -LiteralPath $sdk)) { + [IO.File]::Copy($uploaded,$sdk,$false) + Protect-Path $sdk $false $false +} else { Check-Path $sdk $false $false } +if ((Get-FileHash -LiteralPath $sdk).Hash.ToLowerInvariant() -cne $sdkHash) { throw 'Protected SDK hash' } +Ensure-Directory $parent $true +New-Item -ItemType Directory -Path $case | Out-Null +Protect-Path $case $true $true +Write-NewPrivate (Join-Path $case 'ca.pem') $ca +Write-NewPrivate (Join-Path $case 'enrollment-token') ([Text.Encoding]::ASCII.GetBytes($p.enrollment_token)) +[pscustomobject]@{schema_version=1;prepared=$true;executed=$false;separate_fixture=$true;case_id=$p.case_id;root=$case;sdk=$sdk;sdk_sha256=$sdkHash;ca_sha256=$p.ca_sha256;service_sid=$actor;permanent_identity_read=$false;services_changed=$false;jobs_created=$false} | ConvertTo-Json -Compress diff --git a/deploy/windows_certificate_acceptance.py b/deploy/windows_certificate_acceptance.py new file mode 100644 index 0000000..deef3b3 --- /dev/null +++ b/deploy/windows_certificate_acceptance.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Render one local fixed Windows certificate plan; performs no network or target action. + +Actual bootstrap/token staging, MCP submit, UI approval and fixture revocation +are separate coordinated actions. The permanent enrolled device is never revoked. +""" +import argparse +from datetime import timedelta +import hashlib +import json +import os +from pathlib import Path +import uuid + +import cloud_mvp_acceptance as cloud + +SDK_SHA256 = 'c6b581b60ce803318ff946cd3cc8306aa8589d6bff6b022c0bf1d48eb8f5a8e1' +SDK = 'C:\\Program Files\\RustDiscoveryCertificateAcceptance\\' + SDK_SHA256 + '\\WindowsCertificateAcceptanceSDK.exe' +ROOT = 'C:\\ProgramData\\RustDiscovery\\certificate-acceptance' + + +def script(case_id, mode): + assert str(uuid.UUID(case_id)) == case_id and mode in ('renew', 'revoked-read') + return ("$ErrorActionPreference = 'Stop'\r\n" + "$exe = '" + SDK + "'\r\n" + "$guard = [IO.File]::Open($exe,'Open','Read','Read')\r\n" + "try {\r\n" + " $sha = [Security.Cryptography.SHA256]::Create()\r\n" + " try { $hash = ([BitConverter]::ToString($sha.ComputeHash($guard))).Replace('-','').ToLowerInvariant() } finally { $sha.Dispose() }\r\n" + " if ($hash -cne '" + SDK_SHA256 + "') { throw 'Certificate SDK hash mismatch' }\r\n" + " $lines = @(& $exe '" + mode + "' '" + case_id + "')\r\n" + " if ($LASTEXITCODE -ne 0) { throw 'Certificate fixture failed; preserve case and do not retry' }\r\n" + " $result = ($lines -join [Environment]::NewLine) | ConvertFrom-Json\r\n" + " if ($result.verified -ne $true -or $result.execution_sid -cne 'S-1-5-19' -or $result.permanent_identity_read -ne $false) { throw 'Exact LocalService fixture proof required' }\r\n" + " Write-Output 'CertificateAcceptance:" + mode + ":verified'\r\n" + "} finally { $guard.Dispose() }\r\n") + + +def request(case_id, mode): + start = cloud.contract.now() + text = script(case_id, mode) + return dict(tenant_id=cloud.TENANT, action='run_script', targets=dict(asset_ids=[cloud.WINDOWS_ASSET]), + parameters=dict(execution_identity='agent_service', timeout_seconds=120, max_output_bytes=16384, + arguments=[], expected_stdout='CertificateAcceptance:' + mode + ':verified\r\n', + variants=[dict(os_family='windows', interpreter='powershell', encoding='utf-8', script_utf8=text, + windows_execution_profile='powershell_51_remote_signed')]), + schedule=cloud.contract.schedule(start, start + timedelta(minutes=15)), + rollout=dict(max_parallel=1, halt_after_failures=1), + reason='Separate Windows certificate fixture ' + mode + '; permanent identity unchanged; no retry') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--case-id', required=True) + parser.add_argument('--mode', choices=('renew', 'revoked-read'), required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + if str(uuid.UUID(args.case_id)) != args.case_id or uuid.UUID(args.case_id).int == 0: + parser.error('canonical nonempty fixture UUID required') + os.umask(0o077) + rendered = request(args.case_id, args.mode) + result = dict(schema_version=1, prepared_only=True, executed=False, fixture_provisioned=False, + case_id=args.case_id, mode=args.mode, sdk_sha256=SDK_SHA256, + script_sha256=hashlib.sha256(script(args.case_id,args.mode).encode()).hexdigest(), + public_receipt=ROOT + '\\' + args.case_id + '\\' + ('renewal-result.json' if args.mode == 'renew' else 'revocation-result.json'), + bootstrap_input_keys=['case_id','ca_base64','ca_sha256','enrollment_token'], request=rendered) + with args.output.open('x') as out: + json.dump(result,out,indent=2) + print(args.output) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows_system_job_bootstrap.py b/deploy/windows_system_job_bootstrap.py new file mode 100644 index 0000000..45993eb --- /dev/null +++ b/deploy/windows_system_job_bootstrap.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Read-only prerequisite capture and preparation for first approved SYSTEM job. + +No install/service/policy mutation or RMM job approval is implemented here. +Settings/pin candidates must be rendered by the real typed Rust codec, never +PowerShell ConvertTo-Json. Actual effect acceptance is separate from prerequisite +unit/OS/authenticated-peer qualification. +""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import sys +import uuid +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'deploy/windows')) +import client_bootstrap as cb + +INSPECT=r''' +$ErrorActionPreference='Stop' +$files=@{} +foreach($path in @('C:\ProgramData\RustDiscoverySystem\helper.json','C:\ProgramData\RustDiscoverySystem\agent-pin.json','C:\ProgramData\RustDiscoverySystem\system-qualification.json','C:\ProgramData\RustDiscoverySystem\system-native-result.json','C:\ProgramData\RustDiscovery\config.json','C:\ProgramData\RustDiscovery\state\helper-probe.json','C:\ProgramData\RustDiscovery\state\job-readiness.json','C:\ProgramData\RustDiscoverySystem\time-attestation.json','C:\Program Files\RustDiscovery\rmm-agent-windows.exe','C:\Program Files\RustDiscovery\rmm-helper-windows.exe')) { + if(!(Test-Path -LiteralPath $path)){$files[$path]=$null;continue} + $item=Get-Item -LiteralPath $path + if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-ne0){throw 'Fixed regular public metadata path'} + $entry=@{sha256=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant();bytes=$item.Length;sddl=(Get-Acl -LiteralPath $path).Sddl;last_write_utc=$item.LastWriteTimeUtc.ToString('o')} + if($path.EndsWith('.json')){if($item.Length-gt65536){throw 'Public JSON size bound'};$entry.raw_base64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))} + $files[$path]=$entry +} +$services=@{} +foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')) { + $service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") + if(!$service){throw 'Existing fixed service required'} + $pidValue=[int]$service.ProcessId;$created=$null + if($pidValue-gt0){$process=Get-Process -Id $pidValue;try{$created=$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$process.Dispose()}} + $services[$name]=@{state=$service.State;start_mode=$service.StartMode;configured_account=$service.StartName;pid=$pidValue;creation_filetime=$created;path=$service.PathName} +} +$policies=@(Get-ExecutionPolicy -List|ForEach-Object{@{scope=[string]$_.Scope;policy=[string]$_.ExecutionPolicy}}) +@{schema_version=1;read_only=$true;vm_utc=[DateTime]::UtcNow.ToString('o');services=$services;files=$files;execution_policy=$policies;w32time=[string](Get-Service W32Time).Status;target_effects_executed=$false;rmm_jobs_created=$false;approvals_performed=$false}|ConvertTo-Json -Depth 12 -Compress +''' + +def save(path,value): + raw=json.dumps(value,sort_keys=True,indent=2).encode()+b'\n' + fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'wb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno()) + +def inspect_guest(): + result=cb.powershell(INSPECT,timeout=60) + cb.contract.require(result['schema_version']==1 and result['read_only'] is True + and result['rmm_jobs_created'] is False and result['target_effects_executed'] is False, + 'read-only fixed guest metadata') + folder=ROOT/'devstate/windows-system-job-bootstrap'/str(uuid.uuid4());folder.mkdir(mode=0o700,parents=True) + save(folder/'read-only.json',result) + decoded={} + for path,record in result['files'].items(): + if record is not None and 'raw_base64' in record: + raw=base64.b64decode(record['raw_base64'],validate=True) + cb.contract.require(hashlib.sha256(raw).hexdigest()==record['sha256'],'original public JSON bytes') + decoded[path]=json.loads(raw) + settings=decoded[r'C:\ProgramData\RustDiscoverySystem\helper.json'] + print(json.dumps(dict(report=str(folder/'read-only.json'),read_only=True, + services=result['services'],settings=dict(schema_version=settings['schema_version'], + enable_effects=settings['enable_effects'],allow_reboot=settings['allow_reboot'], + allowed_services=settings['allowed_services'],allowed_script_profiles=settings.get('allowed_script_profiles'))))) + +def inspect_server(payload): + import json + import subprocess + import hashlib + import os + import stat + from pathlib import Path + require(payload=={'operation':'windows_system_scope_inspect_v1'},'fixed read-only server operation') + root=Path('/opt/rust-discovery') + compose=['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')] + def run(args,data=None): + return subprocess.run(args,input=data,stdin=None if data is not None else subprocess.DEVNULL, + capture_output=True,check=True,timeout=20).stdout + names=('RMM_PROFILE','RMM_DEV_AUTH','RMM_SERVER_ROLE','RMM_UI_ORIGIN','RMM_DEV_SYSTEM_ENABLED','RMM_DEV_SYSTEM_POLICY_FILE') + select=' '.join('(eq $key "'+name+'")' for name in names) + template='{{range .Config.Env}}{{$key := index (split . "=") 0}}{{if or '+select+'}}{{println .}}{{end}}{{end}}' + roles={} + for role in ('api','gateway'): + cid=run(compose+['ps','-q',role]).decode().strip() + require(cid and '\n' not in cid,'one actual service container') + environment={} + for line in run(['docker','inspect',cid,'--format',template]).decode().splitlines(): + if not line:continue + key,sep,value=line.partition('=');require(sep and key in names and key not in environment,'exact public environment') + environment[key]=value + labels=json.loads(run(['docker','inspect',cid,'--format','{{json .Config.Labels}}'])) + compose_files=labels['com.docker.compose.project.config_files'].split(',') + hashes={} + for value in compose_files: + path=Path(value);metadata=path.lstat() + require(path.is_absolute() and path.is_relative_to(root) and stat.S_ISREG(metadata.st_mode) + and metadata.st_uid==0 and not metadata.st_mode&0o022,'protected actual compose closure') + hashes[value]=hashlib.sha256(path.read_bytes()).hexdigest() + roles[role]=dict(container_id=cid,environment=environment, + image=run(['docker','inspect',cid,'--format','{{.Image}}']).decode().strip(),compose_files_sha256=hashes) + tenant='11111111-1111-4111-8111-111111111111';agent='63ea15b2-0643-403d-b5b4-cba1288dbea3' + scope="tenant_id='"+tenant+"' AND agent_id='"+agent+"'" + selected="'automation:"+tenant+"','simulated-testprincipal-a'" + sql=("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object(" + "'memberships',(SELECT json_agg(q ORDER BY principal) FROM (SELECT tenant_id,principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='"+tenant+"' AND principal IN ("+selected+")) q)," + "'installation',(SELECT json_build_object('tenant_id',tenant_id,'asset_id',asset_id,'agent_id',agent_id,'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities,'last_contact_at',last_contact_at,'sync_ready',sync_ready,'helper_ready',helper_sync_ready,'restore_blocked',restore_blocked) FROM agent_installations WHERE "+scope+")," + "'jobs',(SELECT count(*) FROM jobs WHERE "+scope+")," + "'system_jobs',(SELECT count(*) FROM jobs WHERE "+scope+" AND convert_from(payload,'UTF8')::jsonb->>'execution_identity'='system')," + "'unresolved',(SELECT count(*) FROM jobs WHERE "+scope+" AND state NOT IN ('succeeded','failed','cancelled','expired'))); COMMIT;") + database=json.loads(run(compose+['exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],sql.encode()).strip()) + return dict(schema_version=1,read_only=True,roles=roles,database=database,rmm_jobs_created=False,approvals_performed=False) + +def inspect_central(): + import remote_client_bootstrap as transport + result=transport.rpc('server.conf',inspect_server,{'operation':'windows_system_scope_inspect_v1'}) + folder=ROOT/'devstate/windows-system-job-bootstrap'/str(uuid.uuid4());folder.mkdir(mode=0o700,parents=True) + save(folder/'server-read-only.json',result) + print(json.dumps(dict(report=str(folder/'server-read-only.json'),read_only=True,roles=result['roles'],database=result['database']))) + +def prepare_scope(guest_path,server_path,rendered_path): + import datetime as dt + def protected(path):return cb.contract.protected_json(path) + guest=protected(guest_path);central=protected(server_path);rendered=protected(rendered_path) + require=cb.contract.require + require(guest['read_only'] is True and central['read_only'] is True + and rendered['source']=='actual_rust_settings_codec' and rendered['prepared_only'] is True + and rendered['target_mutations'] is False and rendered['target_job_executed'] is False, + 'actual independent reads plus typed renderer only') + files={} + for name in ('settings','pin','native_result','qualification'): + raw=bytes(rendered[name+'_bytes']);digest=hashlib.sha256(raw).hexdigest() + require(digest==rendered[name+'_sha256'],'exact typed payload hash') + files[name]=dict(base64=base64.b64encode(raw).decode(),sha256=digest) + settings=json.loads(bytes(rendered['settings_bytes']));qualification=json.loads(bytes(rendered['qualification_bytes'])) + require(settings['schema_version']==3 and settings['enable_effects'] is True + and settings['allow_reboot'] is False and settings['allowed_services']==[] + and 'allowed_msi_recipe_sha256' not in settings + and settings['allowed_script_profiles']==['full_maintenance_v1'] + and settings['max_runtime_seconds']==30 and qualification['actions']==['run_script'] + and qualification['policy_sha256']==rendered['policy_sha256']==rendered['settings_sha256'], + 'only typed thirty-second SYSTEM script scope') + target={key:settings['binding'][key] for key in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')} + require(all(central['database']['installation'][key]==value for key,value in target.items()) + and central['database']['system_jobs']==0 and central['database']['unresolved']==0, + 'actual first SYSTEM job target and closed previous work') + tenant=target['tenant_id'];actors=['automation:'+tenant,'simulated-testprincipal-a'] + memberships={row['principal']:row for row in central['database']['memberships']} + require(set(memberships)==set(actors) and all(memberships[name]['revoked_at'] is None + and 'scripts:execute' in memberships[name]['permissions'] for name in actors), + 'two existing explicit current actors') + case=str(uuid.uuid4());folder=ROOT/'devstate/windows-system-job-bootstrap'/case;folder.mkdir(mode=0o700,parents=True) + payload=dict(operation='windows_system_script_scope_stopped_v1',phase='apply-stopped',case_id=case, + old_settings_sha256=guest['files'][r'C:\ProgramData\RustDiscoverySystem\helper.json']['sha256'], + old_pin_sha256=guest['files'][r'C:\ProgramData\RustDiscoverySystem\agent-pin.json']['sha256'], + agent_binary_sha256=settings['agent']['binary_sha256'],helper_binary_sha256=settings['helper']['binary_sha256'], + expected_service_processes=[dict(pid=row['pid'],creation_filetime=row['creation_filetime']) + for row in guest['services'].values()],policy_sha256=rendered['policy_sha256'],files=files) + payload['expected_service_definitions']=guest['services'] + payload['old_config_sha256']=guest['files'][r'C:\ProgramData\RustDiscovery\config.json']['sha256'] + payload['helper_start_transition']=dict(before='Manual',after='Auto') + now=dt.datetime.now(dt.timezone.utc);expiry=now+dt.timedelta(minutes=15) + scope=dict(**target,principals=actors,helper_policy_sha256=rendered['policy_sha256'], + helper_binary_sha256=settings['helper']['binary_sha256'],acceptance_evidence_id=qualification['qualification_reference'], + allowed_services=[],max_runtime_seconds=30,allowed_script_profiles=['full_maintenance_v1']) + policy=dict(schema_version=3,profile='development',expires_at=expiry.isoformat(),scopes=[scope]) + permissions=[dict(principal=name,kind=memberships[name]['kind'], + expected_permissions=memberships[name]['permissions'], + add_permissions=[] if 'system:execute' in memberships[name]['permissions'] else ['system:execute']) for name in actors] + overlay={'services':{role:{'environment':{'RMM_DEV_SYSTEM_ENABLED':'true','RMM_DEV_SYSTEM_POLICY_FILE':'/system-policy/policy.json'}, + 'volumes':['/opt/rust-discovery/devstate/windows-system-policy/'+case+'/mounted:/system-policy:ro']} for role in ('api','gateway')}} + server_intent=dict(operation='windows_system_script_scope_activate_v1',case_id=case, + expected_roles=central['roles'],memberships=[memberships[name] for name in actors],policy=policy) + text=("$ErrorActionPreference = 'Stop'\r\n" + "$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\r\n" + "if ($sid -cne 'S-1-5-18') { throw 'Expected SYSTEM process' }\r\n" + "Write-Output ('Windows-System-MVP:' + $sid)\r\n") + job_request=dict(tenant_id=tenant,action='run_script',targets=dict(asset_ids=[target['asset_id']]), + parameters=dict(execution_identity='system',privileged_script_profile='full_maintenance_v1', + timeout_seconds=30,max_output_bytes=4096,arguments=[],expected_stdout='Windows-System-MVP:S-1-5-18\r\n', + variants=[dict(os_family='windows',interpreter='powershell',encoding='utf-8',script_utf8=text, + windows_execution_profile='powershell_51_remote_signed')]), + schedule=dict(not_before=now.isoformat(),start_before=(expiry-dt.timedelta(minutes=1)).isoformat(),offline_policy='wait_until_deadline'), + rollout=dict(max_parallel=1,halt_after_failures=1),reason='First separately approved Windows SYSTEM PowerShell script; exact SID and stdout, no retry') + manifest=dict(schema_version=1,prepared_only=True,case_id=case,created_at=now.isoformat(),expires_at=expiry.isoformat(), + scope='first_SYSTEM_run_script_only',source_controller_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + stopped_apply_source_sha256=hashlib.sha256(APPLY_STOPPED.encode()).hexdigest(), + server_activation_source_sha256=hashlib.sha256((ROOT/'deploy/windows_system_scope_server.py').read_bytes()).hexdigest(), + reads={str(path):hashlib.sha256(Path(path).read_bytes()).hexdigest() for path in (guest_path,server_path,rendered_path)}, + target_mutations=False,policy_activated=False,actual_SYSTEM_job_completed=False, + permission_changes=permissions,files_owner='same actual UID as mounted RMM_JOB_KEY_FILE; stat metadata only', + files_mode='0600; Root or same owner parent, read-only bind on API and gateway', + root_sequence=['fresh guest/server/source CAS','native quiescent stop and exited PID witnesses', + 'hold both original lifetime locks; apply exact settings/pin/qualification while both services stopped', + 'change only helper StartType Manual to Automatic with exact SCM-definition CAS', + 'independent file/ACL/ledger preservation readback','start helper and agent once', + 'fresh role time proofs and ordinary signed sync plus real authenticated helper probe', + 'only then provision both actor permissions and both-role bounded policy', + 'MCP pending plan, actual simulated WebUI click, exact one SYSTEM script execution', + 'independent original consumption/start/outcome/audit readback and policy closure','document and push']) + for name,value in (('manifest.json',manifest),('windows-payload.json',payload),('server-policy.json',policy), + ('system-policy.compose.json',overlay),('permission-intent.json',permissions), + ('server-activation-intent.json',server_intent),('system-job-request.json',job_request)): + save(folder/name,value) + return folder + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + commands=parser.add_subparsers(dest='operation',required=True) + commands.add_parser('inspect');commands.add_parser('inspect-server') + prepare=commands.add_parser('prepare') + for name in ('guest-report','server-report','rendered'):prepare.add_argument('--'+name,required=True,type=Path) + args=parser.parse_args() + if args.operation=='inspect':inspect_guest() + elif args.operation=='inspect-server':inspect_central() + else:print(json.dumps(dict(package=str(prepare_scope(args.guest_report,args.server_report,args.rendered)),target_mutations=False))) + +# Reviewed source for the coordinating root agent. Deliberately not dispatched +# by this module's CLI. Both existing daemons must already be quiescent/stopped; +# starts and fresh signed-sync/native effect acceptance remain separate steps. +APPLY_STOPPED = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if($p.operation-cne'windows_system_script_scope_stopped_v1'-or$p.phase-cnotin@('apply-stopped','readback')){throw 'Fixed bootstrap operation'} +$caseId=[guid]::ParseExact($p.case_id,'D').ToString('D') +$case=Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' ('system-script-scope-'+$caseId) +$helperRoot='C:\ProgramData\RustDiscoverySystem' +$agentSid='S-1-5-80-2738667961-1084496008-3886777835-2738042298-1934696263' +$helperSid='S-1-5-80-1378800304-2783697212-3564778230-1646893514-1341434273' +$targets=@{settings=(Join-Path $helperRoot 'helper.json');pin=(Join-Path $helperRoot 'agent-pin.json');native_result=(Join-Path $helperRoot 'system-native-result.json');qualification=(Join-Path $helperRoot 'system-qualification.json')} +function HashBytes([byte[]]$bytes){$sha=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($sha.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}} +function HashFile([string]$path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +function CheckPath([string]$path,[bool]$directory){$item=Get-Item -LiteralPath $path;if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-ne0){throw 'Protected regular path'};$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;if($owner-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Privileged owner required'};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){$sid=$rule.IdentityReference.Value;if($rule.AccessControlType-ne[Security.AccessControl.AccessControlType]::Allow){throw 'Unexpected deny ACL'};if($sid-cin@('S-1-5-18','S-1-5-32-544')){continue};if($sid-cnotin@($agentSid,$helperSid)-or([int64]$rule.FileSystemRights-band(-bnot 0x1200a9))-ne0){throw 'Foreign or writable public access'}};return $acl} +function CheckStopped{if($null-eq$p.expected_service_processes-or@($p.expected_service_processes).Count-ne2){throw 'Two actual original process witnesses required'};foreach($old in @($p.expected_service_processes)){if([int]$old.pid-le0-or![string]$old.creation_filetime){throw 'Original kernel creation witness'};$live=Get-Process -Id ([int]$old.pid) -ErrorAction SilentlyContinue;if($null-ne$live){try{if($live.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-ceq$old.creation_filetime-and!$live.HasExited){throw 'Original service process still live'}}finally{$live.Dispose()}}};foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'");if(!$service-or$service.State-cne'Stopped'-or[int]$service.ProcessId-ne0){throw 'Coordinated quiescent pair stop required'}}} +function PublicAcl{$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm(('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;'+$agentSid+')(A;;0x1200a9;;;'+$helperSid+')'));return $acl} +function WritePublicOnce([string]$path,[byte[]]$bytes){ + $rights=[Security.AccessControl.FileSystemRights]::ReadWrite + $stream=New-Object IO.FileStream($path,[IO.FileMode]::CreateNew,$rights,[IO.FileShare]::Read,4096,[IO.FileOptions]::WriteThrough,(PublicAcl)) + try{$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()} + $null=CheckPath $path $false +} +function WritePrivateOnce([string]$path,[byte[]]$bytes){$stream=[IO.File]::Open($path,'CreateNew','Write','Read');try{$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()}} +Add-Type -TypeDefinition @' +using System;using System.IO;using System.Runtime.InteropServices;using Microsoft.Win32.SafeHandles; +public sealed class RmmSystemScopeLocks:IDisposable{ + [StructLayout(LayoutKind.Sequential)]struct Ov{public UIntPtr I,H;public uint L,U;public IntPtr E;} + [StructLayout(LayoutKind.Sequential)]struct Info{public uint A,CL,CH,AL,AH,WL,WH,V,SH,SL,N,IH,IL;} + [DllImport("kernel32.dll",SetLastError=true)]static extern bool LockFileEx(SafeFileHandle h,uint f,uint z,uint l,uint u,ref Ov o); + [DllImport("kernel32.dll",SetLastError=true)]static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i); + [DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr OpenSCManager(string a,string b,uint c); + [DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr OpenService(IntPtr m,string n,uint a); + [DllImport("advapi32.dll",EntryPoint="ChangeServiceConfigW",CharSet=CharSet.Unicode,SetLastError=true)]static extern bool ChangeServiceConfig(IntPtr h,uint type,uint start,uint error,string command,string group,IntPtr tag,string deps,string account,string password,string display); + [DllImport("advapi32.dll")]static extern bool CloseServiceHandle(IntPtr h); + readonly FileStream[] files=new FileStream[2]; + public RmmSystemScopeLocks(){string[] p={@"C:\ProgramData\RustDiscovery\state\agent.lock",@"C:\ProgramData\RustDiscoverySystem\state\executor.lock"};try{for(int i=0;i<2;i++){files[i]=new FileStream(p[i],FileMode.Open,FileAccess.Read,FileShare.ReadWrite);Ov o=new Ov();if(!LockFileEx(files[i].SafeFileHandle,3,0,uint.MaxValue,uint.MaxValue,ref o))throw new InvalidOperationException("ORIGINAL_LOCK_BUSY");}}catch{Dispose();throw;}} + public string[] LockIds(){string[] r=new string[2];for(int n=0;n<2;n++){Info i;if(!GetFileInformationByHandle(files[n].SafeFileHandle,out i)||i.N!=1||(i.A&0x410)!=0)throw new InvalidOperationException("ORIGINAL_LOCK_ID");r[n]=i.V+":"+i.IH+":"+i.IL;}return r;} + public static string Identity(string path){using(FileStream f=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)){Info i;if(!GetFileInformationByHandle(f.SafeFileHandle,out i)||i.N!=1||(i.A&0x410)!=0)throw new InvalidOperationException("PRESERVED_FILE_ID");return i.V+":"+i.IH+":"+i.IL+":"+i.SH+":"+i.SL+":"+i.WH+":"+i.WL;}} + public static void SetHelperAutomatic(){IntPtr m=OpenSCManager(null,null,1);if(m==IntPtr.Zero)throw new InvalidOperationException("SCM_CONNECT");try{IntPtr h=OpenService(m,"RmmDiscoverySystemHelper",2);if(h==IntPtr.Zero)throw new InvalidOperationException("HELPER_CONFIG_OPEN");try{if(!ChangeServiceConfig(h,uint.MaxValue,2,uint.MaxValue,null,null,IntPtr.Zero,null,null,null,null))throw new InvalidOperationException("HELPER_STARTTYPE_CHANGE");}finally{CloseServiceHandle(h);}}finally{CloseServiceHandle(m);}} + public void Dispose(){foreach(FileStream f in files)if(f!=null)f.Dispose();} +} +'@ +function ServiceDefinitions { + $rows=[ordered]@{} + foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){ + $s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") + if(!$s-or$s.State-cne'Stopped'-or[int]$s.ProcessId-ne0-or$s.ServiceType-cne'Own Process'){throw 'Fixed stopped own-process services'} + $old=$p.expected_service_definitions.$name + if(!$old-or$s.PathName-cne$old.path-or$s.StartName-cne$old.configured_account){throw 'Original SCM command/account CAS'} + $rows[$name]=@{path=$s.PathName;configured_account=$s.StartName;start_mode=$s.StartMode} + } + return $rows +} +function PreservedFiles { + $paths=@('C:\ProgramData\RustDiscovery\state\telemetry.sqlite','C:\ProgramData\RustDiscovery\state\consumption.sqlite','C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite','C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite','C:\ProgramData\RustDiscovery\config.json','C:\ProgramData\RustDiscoverySystem\time-attestation.json') + $result=[ordered]@{} + foreach($path in $paths){ + if(!(Test-Path -LiteralPath $path)){throw 'Original retained public/control file missing'} + foreach($candidate in @($path,($path+'-wal'),($path+'-shm'))){if(Test-Path -LiteralPath $candidate){$result[$candidate]=@{identity=[RmmSystemScopeLocks]::Identity($candidate);sddl=(Get-Acl -LiteralPath $candidate).Sddl;sha256=(HashFile $candidate)}}} + } + # Private-key bytes are never read. Only existing namespace/security/FileID metadata. + foreach($item in @(Get-ChildItem -LiteralPath 'C:\ProgramData\RustDiscovery\state' -File|Where-Object{$_.Name-like'device*.key'-or$_.Name-like'device*.pem'-or$_.Name-ceq'identity.json'}|Sort-Object FullName)){ + if($item.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Preserved identity regular file'} + $result[$item.FullName]=@{identity=[RmmSystemScopeLocks]::Identity($item.FullName);sddl=(Get-Acl -LiteralPath $item.FullName).Sddl} + } + return ($result|ConvertTo-Json -Depth 8 -Compress) +} +$null=CheckPath 'C:\ProgramData\RustDiscoveryBootstrap' $true +$null=CheckPath $helperRoot $true +if($p.phase-ceq'readback'){ + $result=@{schema_version=1;read_only=$true;case_present=(Test-Path -LiteralPath $case);files=@{};services=@{}} + foreach($name in $targets.Keys){$path=$targets[$name];$result.files[$name]=if(Test-Path -LiteralPath $path){@{sha256=(HashFile $path);sddl=(Get-Acl -LiteralPath $path).Sddl}}else{$null}} + foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){$result.services[$name]=[string](Get-Service -Name $name).Status} + $result|ConvertTo-Json -Depth 8 -Compress;exit 0 +} +CheckStopped +$definitions=ServiceDefinitions +if($p.helper_start_transition.before-cne'Manual'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Manual'-or$definitions.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Exact Manual to Auto helper transition only'} +if((HashFile 'C:\ProgramData\RustDiscovery\config.json')-cne$p.old_config_sha256){throw 'Preserved active configuration CAS'} +$locks=[RmmSystemScopeLocks]::new() +try { +$lockIds=($locks.LockIds()-join',');$preserved=PreservedFiles +$null=CheckPath $targets.settings $false +$null=CheckPath $targets.pin $false +if(Test-Path -LiteralPath $case){throw 'Existing case means readback only'} +foreach($name in @('native_result','qualification')){if(Test-Path -LiteralPath $targets[$name]){throw 'First script scope requires absent prior qualification files'}} +if((HashFile $targets.settings)-cne$p.old_settings_sha256-or(HashFile $targets.pin)-cne$p.old_pin_sha256){throw 'Fresh original public settings and pin CAS'} +if((HashFile 'C:\Program Files\RustDiscovery\rmm-agent-windows.exe')-cne$p.agent_binary_sha256-or(HashFile 'C:\Program Files\RustDiscovery\rmm-helper-windows.exe')-cne$p.helper_binary_sha256){throw 'Actual image pair required'} +$settings=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($targets.settings))|ConvertFrom-Json +if($settings.enable_effects-ne$false-or$settings.allow_reboot-ne$false-or@($settings.allowed_services).Count-ne0){throw 'First passive-to-script-only transition'} +$payloads=@{} +foreach($name in @('settings','pin','native_result','qualification')){$item=$p.files.$name;$bytes=[Convert]::FromBase64String($item.base64);if($bytes.Length-lt1-or$bytes.Length-gt65536-or(HashBytes $bytes)-cne$item.sha256){throw 'Exact typed-renderer payload bytes'};$payloads[$name]=$bytes} +$next=[Text.Encoding]::UTF8.GetString($payloads.settings)|ConvertFrom-Json +if($next.schema_version-ne3-or$next.enable_effects-ne$true-or$next.allow_reboot-ne$false-or@($next.allowed_services).Count-ne0-or@($next.allowed_msi_recipe_sha256).Count-ne0-or($next.allowed_script_profiles-join',')-cne'full_maintenance_v1'-or$next.max_runtime_seconds-ne30){throw 'Only explicit schema3 script scope'} +if($next.agent.binary_sha256-cne$p.agent_binary_sha256-or$next.helper.binary_sha256-cne$p.helper_binary_sha256){throw 'Exact target code pins'} +$qualification=[Text.Encoding]::UTF8.GetString($payloads.qualification)|ConvertFrom-Json +$native=[Text.Encoding]::UTF8.GetString($payloads.native_result)|ConvertFrom-Json +if(($qualification.actions-join',')-cne'run_script'-or$qualification.policy_sha256-cne$p.policy_sha256-or$qualification.native_result_sha256-cne$p.files.native_result.sha256-or$native.scope-cne'native_prerequisites_only'-or$native.target_job_executed-ne$false-or$native.status-cne'passed'){throw 'Truthful prerequisite qualification only'} +New-Item -ItemType Directory -Path $case|Out-Null +$private=New-Object Security.AccessControl.DirectorySecurity;$private.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)');Set-Acl -LiteralPath $case -AclObject $private +WritePrivateOnce (Join-Path $case 'intent.json') ([Text.Encoding]::UTF8.GetBytes(($p|ConvertTo-Json -Depth 20 -Compress))) +foreach($name in @('settings','pin','native_result','qualification')){WritePublicOnce (Join-Path $case ($name+'.candidate.json')) $payloads[$name]} +foreach($name in @('settings','pin')){ + CheckStopped + $expected=if($name-ceq'settings'){$p.old_settings_sha256}else{$p.old_pin_sha256} + if((HashFile $targets[$name])-cne$expected){throw 'Immediate original file CAS'} + WritePrivateOnce (Join-Path $case ($name+'-replace-intent.json')) ([Text.Encoding]::UTF8.GetBytes('{"create_once":true}')) + $backup=Join-Path $case ($name+'.previous.json') + [IO.File]::Replace((Join-Path $case ($name+'.candidate.json')),$targets[$name],$backup) + if((HashFile $backup)-cne$expected-or(HashFile $targets[$name])-cne$p.files.$name.sha256){throw 'Native replace must retain exact original and candidate'} + $null=CheckPath $targets[$name] $false +} +foreach($name in @('native_result','qualification')){ + CheckStopped + if(Test-Path -LiteralPath $targets[$name]){throw 'Public prerequisite target appeared'} + WritePrivateOnce (Join-Path $case ($name+'-publish-intent.json')) ([Text.Encoding]::UTF8.GetBytes('{"create_once":true}')) + [IO.File]::Move((Join-Path $case ($name+'.candidate.json')),$targets[$name]) + if((HashFile $targets[$name])-cne$p.files.$name.sha256){throw 'Exact published prerequisite bytes'} + $null=CheckPath $targets[$name] $false +} +CheckStopped +$current=ServiceDefinitions +if(($current|ConvertTo-Json -Depth 6 -Compress)-cne($definitions|ConvertTo-Json -Depth 6 -Compress)){throw 'SCM changed before helper Automatic transition'} +WritePrivateOnce (Join-Path $case 'helper-autostart-intent.json') ([Text.Encoding]::UTF8.GetBytes('{"from":"Manual","to":"Auto","no_start":true}')) +[RmmSystemScopeLocks]::SetHelperAutomatic() +$automatic=ServiceDefinitions +if($automatic.RmmDiscoverySystemHelper.start_mode-cne'Auto'-or$automatic.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Actual automatic startup readback'} +if((PreservedFiles)-cne$preserved-or($locks.LockIds()-join',')-cne$lockIds){throw 'Original identities, journals, clock profile and locks must be preserved'} +$result=@{schema_version=1;files_installed=$true;services_started=$false;target_job_executed=$false;approval_performed=$false;state_or_keys_changed=$false;helper_autostart='Auto';services=$automatic;policy_sha256=$p.policy_sha256;next='root must refresh actual SCM/role/time qualification then start pair once and verify fresh signed clock/sync; first actual SYSTEM job requires WebUI approval'} +WritePrivateOnce (Join-Path $case 'completed.json') ([Text.Encoding]::UTF8.GetBytes(($result|ConvertTo-Json -Compress))) +$result|ConvertTo-Json -Compress +} finally {$locks.Dispose()} +''' + +if __name__=='__main__':main() diff --git a/deploy/windows_system_scope_server.py b/deploy/windows_system_scope_server.py new file mode 100644 index 0000000..c5a6be0 --- /dev/null +++ b/deploy/windows_system_scope_server.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Reviewed remote bootstrap source for an explicit 15-minute SYSTEM ceiling. + +No CLI dispatch. Root must review the exact public intent and call this through +the existing protected server transport. Never creates/approves jobs. Partial +results are readback-only, never an automatic retry or rollback. +""" + + +def activate(payload): + import datetime as dt + import fcntl + import hashlib + import json + import os + from pathlib import Path + import re + import stat + import subprocess + import uuid + + def require(value, code): + if not value: + raise RuntimeError(code) + + require(os.geteuid() == 0, 'SYSTEM_SCOPE_ROOT_BOOTSTRAP') + require(set(payload) == {'operation', 'case_id', 'expected_roles', 'memberships', 'policy'}, 'SYSTEM_SCOPE_INPUT') + require(payload['operation'] == 'windows_system_script_scope_activate_v1', 'SYSTEM_SCOPE_OPERATION') + ident = str(uuid.UUID(payload['case_id'])) + require(ident == payload['case_id'], 'SYSTEM_SCOPE_CASE') + tenant = '11111111-1111-4111-8111-111111111111' + agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3' + asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0' + actors = ['automation:' + tenant, 'simulated-testprincipal-a'] + root = Path('/opt/rust-discovery') + base = ['docker', 'compose', '--env-file', str(root / 'devstate/.env')] + + def run(args, data=None): + return subprocess.run(args, input=data, capture_output=True, check=True, timeout=120).stdout + + def enc(value): + return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() + + def create(path, data, uid=0, gid=0): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as out: + os.fchown(out.fileno(), uid, gid) + out.write(data); out.flush(); os.fsync(out.fileno()) + + roles = payload['expected_roles'] + require(set(roles) == {'api', 'gateway'}, 'SYSTEM_SCOPE_BOTH_ROLES') + compose_files = None + config_hashes = None + for role in ('api', 'gateway'): + expected = roles[role] + require(set(expected) == {'container_id', 'image', 'environment', 'compose_files_sha256'}, 'SYSTEM_SCOPE_ROLE_WITNESS') + require(re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_SCOPE_CONTAINER_ID') + info = json.loads(run(['docker', 'inspect', expected['container_id']]))[0] + require(info['State']['Running'] and info['Image'] == expected['image'], 'SYSTEM_SCOPE_IMAGE_CAS') + selected = {} + names = {'RMM_PROFILE', 'RMM_DEV_AUTH', 'RMM_SERVER_ROLE', 'RMM_UI_ORIGIN', 'RMM_DEV_SYSTEM_ENABLED', 'RMM_DEV_SYSTEM_POLICY_FILE'} + for entry in info['Config']['Env']: + key, _, value = entry.partition('=') + if key in names: + require(key not in selected, 'SYSTEM_SCOPE_UNIQUE_ENV') + selected[key] = value + require(selected == expected['environment'] and selected == dict(RMM_PROFILE='development', RMM_DEV_AUTH='true', RMM_SERVER_ROLE=role, RMM_UI_ORIGIN='https://localhost:18443'), 'SYSTEM_SCOPE_EXISTING_PRIVATE_DEV_PROFILE') + labels = info['Config']['Labels'] + require(labels['com.docker.compose.project'] == 'rust-discovery-server' and labels['com.docker.compose.service'] == role, 'SYSTEM_SCOPE_COMPOSE_ROLE') + files = labels['com.docker.compose.project.config_files'].split(',') + require(files and len(files) <= 12 and all(Path(p).is_absolute() and Path(p).is_relative_to(root) for p in files), 'SYSTEM_SCOPE_COMPOSE_PATHS') + hashes = {} + for value in files: + path = Path(value); m = path.lstat() + require(stat.S_ISREG(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022, 'SYSTEM_SCOPE_PROTECTED_COMPOSE') + hashes[value] = hashlib.sha256(path.read_bytes()).hexdigest() + require(hashes == expected['compose_files_sha256'], 'SYSTEM_SCOPE_COMPOSE_CAS') + if compose_files is None: + compose_files = files; config_hashes = hashes + require(files == compose_files and hashes == config_hashes, 'SYSTEM_SCOPE_SAME_COMPOSE_PAIR') + # Bind mounts are deliberately additive; no existing policy/TLS/data + # mount or published port is changed by the generated overlay. + require(not any(m['Destination'] == '/system-policy' for m in info['Mounts']), 'SYSTEM_SCOPE_PREVIOUS_SYSTEM_MOUNT') + compose = base[:] + for path in compose_files: + compose += ['-f', path] + for role in ('api', 'gateway'): + require(run(compose + ['ps', '-q', role]).decode().strip() == roles[role]['container_id'], 'SYSTEM_SCOPE_CURRENT_CONTAINER_CAS') + policy = payload['policy'] + require(set(policy) == {'schema_version', 'profile', 'expires_at', 'scopes'} and policy['schema_version'] == 3 and policy['profile'] == 'development' and len(policy['scopes']) == 1, 'SYSTEM_SCOPE_NARROW_POLICY') + now = dt.datetime.now(dt.timezone.utc) + expiry = dt.datetime.fromisoformat(policy['expires_at'].replace('Z', '+00:00')) + require(dt.timedelta(minutes=5) <= expiry - now <= dt.timedelta(minutes=15), 'SYSTEM_SCOPE_FINITE_WINDOW') + scope = policy['scopes'][0] + require(set(scope) == {'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'principals', 'helper_policy_sha256', 'helper_binary_sha256', 'acceptance_evidence_id', 'allowed_services', 'max_runtime_seconds', 'allowed_script_profiles'}, 'SYSTEM_SCOPE_FIELDS') + require(scope['tenant_id'] == tenant and scope['asset_id'] == asset and scope['agent_id'] == agent and scope['enrollment_generation'] == scope['assignment_version'] == 1 and scope['principals'] == actors and scope['allowed_services'] == [] and scope['max_runtime_seconds'] == 30 and scope['allowed_script_profiles'] == ['full_maintenance_v1'], 'SYSTEM_SCOPE_ONLY_FULL_SCRIPT') + require(all(re.fullmatch('[a-f0-9]{64}', scope[k]) for k in ('helper_policy_sha256', 'helper_binary_sha256')) and str(uuid.UUID(scope['acceptance_evidence_id'])) == scope['acceptance_evidence_id'], 'SYSTEM_SCOPE_NATIVE_PINS') + memberships = payload['memberships'] + require([row['principal'] for row in memberships] == actors, 'SYSTEM_SCOPE_EXISTING_ACTORS') + for n, row in enumerate(memberships): + require(set(row) == {'tenant_id', 'principal', 'kind', 'permissions', 'revoked_at'} and row['tenant_id'] == tenant and row['kind'] == ('automation' if n == 0 else 'test_human') and row['revoked_at'] is None and 'scripts:execute' in row['permissions'] and 'system:execute' not in row['permissions'], 'SYSTEM_SCOPE_MEMBERSHIP_CAS_INPUT') + require(len(set(row['permissions'])) == len(row['permissions']) and all(re.fullmatch('[a-z_:]+', p) for p in row['permissions']), 'SYSTEM_SCOPE_PERMISSION_FORMAT') + sql_read = ("BEGIN READ ONLY; SELECT json_build_object('ready',sync_ready,'helper_ready',helper_sync_ready,'blocked',restore_blocked,'fresh',last_contact_at>clock_timestamp()-interval '45 seconds','same_certificate',certificate_sha256=last_authenticated_certificate_sha256,'capabilities',capabilities) FROM agent_installations WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND asset_id='" + asset + "' AND enrollment_generation=1 AND assignment_version=1 AND revoked_at IS NULL; COMMIT;") + observed = json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql_read.encode())) + require(observed['ready'] and observed['helper_ready'] and not observed['blocked'] and observed['fresh'] and observed['same_certificate'], 'SYSTEM_SCOPE_CURRENT_AUTHENTICATED_PAIR') + needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + scope['helper_binary_sha256'], 'helper.policy.sha256:' + scope['helper_policy_sha256']} + require(needed <= set(observed['capabilities']) and 'linux.base/1' not in observed['capabilities'], 'SYSTEM_SCOPE_ACTUAL_QUALIFIED_CAPABILITIES') + # Resolve only public image names; never build, pull or alter a deployed image. + configured = json.loads(run(compose + ['config', '--format', 'json']))['services'] + for role in ('api', 'gateway'): + actual = run(['docker', 'image', 'inspect', configured[role]['image'], '--format', '{{.Id}}']).decode().strip() + require(actual == roles[role]['image'], 'SYSTEM_SCOPE_NO_IMAGE_CHANGE') + lock = os.open(root / 'devstate/.windows-system-scope.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + parent = root / 'devstate/windows-system-policy' + if not parent.exists(): parent.mkdir(mode=0o700) + m = parent.lstat(); require(stat.S_ISDIR(m.st_mode) and m.st_uid == 0 and m.st_mode & 0o777 == 0o700, 'SYSTEM_SCOPE_PRIVATE_PARENT') + case = parent / ident + case.mkdir(mode=0o700) # create-once: lost response means readback only + create(case / 'intent.json', enc(payload)) + key = (root / 'devstate/jobs/ed25519.pem').lstat() # metadata only, never read signing key + require(stat.S_ISREG(key.st_mode) and not key.st_mode & 0o077, 'SYSTEM_SCOPE_JOB_KEY_OWNER') + mounted = case / 'mounted'; mounted.mkdir(mode=0o700); os.chown(mounted, key.st_uid, key.st_gid) + raw = enc(policy); require(len(raw) <= 65536, 'SYSTEM_SCOPE_POLICY_LIMIT') + create(mounted / 'policy.json', raw, key.st_uid, key.st_gid) + overlay = {'services': {role: {'environment': {'RMM_DEV_SYSTEM_ENABLED': 'true', 'RMM_DEV_SYSTEM_POLICY_FILE': '/system-policy/policy.json'}, 'volumes': [str(mounted) + ':/system-policy:ro']} for role in ('api', 'gateway')}} + overlay_path = case / 'system-policy.compose.json'; create(overlay_path, enc(overlay)) + sql = "BEGIN; LOCK TABLE memberships,jobs,outbox,execution_permits,authorizations IN SHARE ROW EXCLUSIVE MODE; DO $scope$ BEGIN IF EXISTS(SELECT 1 FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')) THEN RAISE EXCEPTION 'SYSTEM_SCOPE_INFLIGHT_JOB'; END IF;" + for row in memberships: + permissions = 'ARRAY[' + ','.join("'" + p + "'" for p in row['permissions']) + ']::text[]' + where = "tenant_id='" + tenant + "' AND principal='" + row['principal'] + "' AND kind='" + row['kind'] + "' AND revoked_at IS NULL AND permissions=" + permissions + sql += " IF (SELECT count(*) FROM memberships WHERE " + where + ")<>1 THEN RAISE EXCEPTION 'SYSTEM_SCOPE_MEMBERSHIP_CAS'; END IF; UPDATE memberships SET permissions=permissions||ARRAY['system:execute'] WHERE " + where + ';' + sql += " END $scope$; SELECT json_build_object('memberships_updated',2,'jobs_created',0,'approvals_created',0); COMMIT;" + create(case / 'permissions-entered.json', b'{"retry_allowed":false}') + reply = run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode()) + create(case / 'permissions-result.json', reply) + create(case / 'recreate-entered.json', b'{"retry_allowed":false}') + run(compose + ['-f', str(overlay_path), 'up', '-d', '--no-deps', '--no-build', '--pull', 'never', 'api', 'gateway']) + after = {} + for role in ('api', 'gateway'): + cid = run(compose + ['-f', str(overlay_path), 'ps', '-q', role]).decode().strip() + info = json.loads(run(['docker', 'inspect', cid]))[0] + require(info['Image'] == roles[role]['image'] and info['State']['Running'], 'SYSTEM_SCOPE_ROLE_RUNNING') + mount = [m for m in info['Mounts'] if m['Destination'] == '/system-policy'] + require(len(mount) == 1 and mount[0]['Type'] == 'bind' and not mount[0]['RW'] and mount[0]['Source'] == str(mounted), 'SYSTEM_SCOPE_READ_ONLY_MOUNT') + after[role] = dict(container_id=cid, image=info['Image']) + result = dict(schema_version=1, activated=True, case_id=ident, expires_at=policy['expires_at'], policy_sha256=hashlib.sha256(raw).hexdigest(), roles=after, jobs_created=False, approvals_created=False, system_target_job_executed=False, automatic_retry=False) + create(case / 'activated.json', enc(result)) + return result + finally: + os.close(lock) diff --git a/docs/evidence/windows-system-script-prerequisites-20261116-linux.json b/docs/evidence/windows-system-script-prerequisites-20261116-linux.json new file mode 100644 index 0000000..e82b4e5 --- /dev/null +++ b/docs/evidence/windows-system-script-prerequisites-20261116-linux.json @@ -0,0 +1,42 @@ +{ + "schema_version": 1, + "scope": "native_policy_and_codec_units_only", + "passed": 2, + "failed": 0, + "verified": true, + "target_job_executed": false, + "services_changed": false, + "platform": "linux", + "tests": [ + { + "name": "system-script-domain-linux", + "original_report_sha256": "5d9b38873a46a74643052ef968f71a5ffc3993c4d567412a30cd0be6114a366e", + "result": { + "exit_code": 0, + "stdout": "\nrunning 1 test\ntest jobs::tests::full_maintenance_is_explicit_strict_identity_and_capability_bound ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 23 filtered out; finished in 0.00s\n\n", + "stderr": "", + "binary_sha256": "4b9e8796f7a86dac76fd43b772e77f9040899ba21a1a841fe81b3837f8dd0089", + "native_platform": "cloud-linux-x86_64", + "uid": 65534, + "isolated_network": true, + "no_new_privs": true, + "verified": true + } + }, + { + "name": "system-script-codec-linux", + "original_report_sha256": "2598e2f6251f7dc5c1ddb283300ef3b20dcc6a83d249abd33274ad8813972bd1", + "result": { + "exit_code": 0, + "stdout": "\nrunning 1 test\ntest jobs::tests::codec_golden_and_exact_script_bytes ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 23 filtered out; finished in 0.00s\n\n", + "stderr": "", + "binary_sha256": "4b9e8796f7a86dac76fd43b772e77f9040899ba21a1a841fe81b3837f8dd0089", + "native_platform": "cloud-linux-x86_64", + "uid": 65534, + "isolated_network": true, + "no_new_privs": true, + "verified": true + } + } + ] +} diff --git a/docs/evidence/windows-system-script-prerequisites-20261116-windows.json b/docs/evidence/windows-system-script-prerequisites-20261116-windows.json new file mode 100644 index 0000000..5d26bf5 --- /dev/null +++ b/docs/evidence/windows-system-script-prerequisites-20261116-windows.json @@ -0,0 +1,40 @@ +{ + "schema_version": 1, + "scope": "native_policy_and_codec_units_only", + "passed": 2, + "failed": 0, + "verified": true, + "target_job_executed": false, + "services_changed": false, + "platform": "windows", + "tests": [ + { + "name": "system-script-proof-windows", + "original_report_sha256": "7ff485fc08a8e326554dc6abefacb62d34636b259e959c470302e0373e18d216", + "result": { + "exit_code": 0, + "product_job": false, + "binary_sha256": "262c302e1164a88b8684819211c4d3e11aa6c9c162d54b290678101062c625e2", + "bootstrap_administrator": true, + "stderr": "", + "native_platform": "windows-11-x86_64", + "stdout": "\nrunning 1 test\ntest helper_runtime::script_tests::system_script_success_requires_exact_profile_identity_bytes_and_raw_output ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 62 filtered out; finished in 0.01s\n\n", + "verified": true + } + }, + { + "name": "system-script-policy-windows", + "original_report_sha256": "47d3c293b6f6116bdb42ba2db4d55b0760edb161ef44dba3a5b4a84fb44a770c", + "result": { + "exit_code": 0, + "product_job": false, + "binary_sha256": "262c302e1164a88b8684819211c4d3e11aa6c9c162d54b290678101062c625e2", + "bootstrap_administrator": true, + "stderr": "", + "native_platform": "windows-11-x86_64", + "stdout": "\nrunning 1 test\ntest helper_system::tests::old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 62 filtered out; finished in 0.00s\n\n", + "verified": true + } + } + ] +} diff --git a/docs/windows-certificate-runtime-acceptance.md b/docs/windows-certificate-runtime-acceptance.md index b292eec..bf755c3 100644 --- a/docs/windows-certificate-runtime-acceptance.md +++ b/docs/windows-certificate-runtime-acceptance.md @@ -90,3 +90,66 @@ Die isolierte Renewalprobe oben verwendet bewusst keine künstlich gealterte Uhr. Der echte Schedulertrigger und die neue aktive Leerlaufzulassung bleiben gesonderte native Gates. Quellen-/Crossbuild-/Unitbelege werden nicht als Dienstabnahme ausgegeben. + +## Konkrete Vorbereitung vom 16. November + +Der bereits gebaute SDK ist lokal erhalten: +`devstate/windows-certificate-acceptance/windows_certificate_acceptance.exe`, +SHA256 `c6b581b60ce803318ff946cd3cc8306aa8589d6bff6b022c0bf1d48eb8f5a8e1`. +Sein Beispielquelltext hat SHA256 +`74b2bc85d3d68d27154e87fcaca0ed313d3d721692473e1a47e577bff34474b7`. +Die Produktionsdateien `certificate_rotation.rs`, `native.rs` und `journal.rs` +stimmen bytegenau mit dem qualifizierten Dienstpaar aus +`devstate/windows-helper-apply-fix/source` überein. Buildreceipt und tatsächliche +Quellen liegen unter `devstate/windows-certificate-acceptance/`; das SDK wurde +bei dieser Vorbereitung weder auf der VM ausgeführt noch dort neu installiert. + +`deploy/windows/Prepare-CertificateAcceptanceFixture.ps1` ist ein expliziter +Bootstrap, der **keinen** SDK-Prozess startet. Er erwartet ausschließlich eine +JSON-Zeile auf stdin mit `case_id`, `ca_base64`, `ca_sha256` und +`enrollment_token`. Der Token muss unmittelbar vor dem koordinierten Test für +eine neue, separate Identität erzeugt werden; bestehende Geräte-/Enrollmentdaten +werden nicht übernommen. Ein vorhandenes Fallverzeichnis verweigert die +Vorbereitung statt Token oder Dateien zu ersetzen. Teilfehler erfordern Lesen +des bestehenden Falls, keine blinde Wiederholung. + +Das SDK wird nach +`C:\Program Files\RustDiscoveryCertificateAcceptance\\WindowsCertificateAcceptanceSDK.exe` +kopiert, mit SYSTEM-/Administrator-Schreibrecht und Agent-Service-SID-Leserecht. +Das Fallverzeichnis liegt getrennt unter dem oben genannten festen Pfad; +nur SYSTEM, Administratoren und die tatsächliche Agent-Service-SID erhalten +Schreibrecht. Die permanente Geräteidentität, RMM-Journale, Helperpolicy, +Dienste und Zeitprofile werden nicht gelesen oder geändert. + +`deploy/windows_certificate_acceptance.py` erzeugt ausschließlich lokal die +vollständigen PowerShell-Pläne für `renew` und `revoked-read`. Es führt keine +Netzwerkanfrage aus, plant keinen MCP-Auftrag und genehmigt nichts. Das Skript +bindet SDK-Hash und Fallkennung, hält das SDK während Prüfung und Ausführung +gegen Schreiben/Löschen geöffnet und verlangt die tatsächliche LocalService- +Quittung. Die vorgesehenen Aufträge laufen mit 120s Laufzeitgrenze, +`powershell_51_remote_signed` und festen Ausgabepostconditions. Der zweite Plan +darf erst nach unabhängig geprüftem Renewal und tatsächlichem WebUI-Widerruf +**ausschließlich der Testidentität** eingereicht/genehmigt werden. Zeitplan beim +tatsächlichen MCP-Antrag neu rendern; ein lokaler Entwurf ist keine Genehmigung. + +Tatsächlich ausgeführt wurden Python-Syntaxprüfung und der rein lesende +PowerShell-5.1-AST-Parser für den Bootstrap: null Syntaxfehler. Es wurden kein +Fixturetoken erzeugt, keine Registrierung/Erneuerung/Widerruf ausgelöst und +keine neuen Jobs erstellt. Die ACL-/I/O-Wirkung des neuen Bootstrap bleibt bis +zur koordinierten nativen Ausführung ausdrücklich **nicht abgenommen**. Der +Linux-Vergleich bleibt die bereits tatsächlich ausgeführte separate +Cloud-Identitätsabnahme in `deploy/cloud_lifecycle_acceptance.py`. + +## Weitere offene Neustartvoraussetzung + +Der tatsächliche lesende SCM-Stand am 16. November nach Installation von +Profil 7: Agent `Running/Auto/LocalService`, Helper `Running/Manual/LocalSystem`. +`system_helper_bootstrap.py` legt den Helper ausdrücklich mit Startart Manual +an. Der Agent besitzt keinen eigenen Helper-Startpfad; der vorhandene +`PreparedService::execute` startet nur separat genehmigte, allowlistgebundene +Dienstaufträge und aktiviert nicht den eigenen SYSTEM-Helper. Ein laufendes +Paar beweist daher noch keinen vollständigen Wiederanlauf nach Windows-Boot. +Eine eng koordinierte automatische Helper-Startkonfiguration und die dazu +gehörenden tatsächlichen SCM-/Rollen-/Zeitbelege sind vor einer vollständigen +Windows-MVP-Neustartabnahme nötig. Diese Vorbereitung hat die Startart nicht +verändert und keinen Neustart ausgeführt. diff --git a/docs/windows-system-first-job-plan.md b/docs/windows-system-first-job-plan.md new file mode 100644 index 0000000..446d484 --- /dev/null +++ b/docs/windows-system-first-job-plan.md @@ -0,0 +1,239 @@ +# Erster SYSTEM-Auftrag: Voraussetzungen und eng begrenzte Vorbereitung + +Stand 16. November 2026. Dieser Schritt bereitet die erste tatsächliche +SYSTEM-Skriptabnahme vor. **Es wurde dabei kein SYSTEM-Auftrag ausgeführt und +keine lokale oder zentrale Wirkungspolicy aktiviert.** Die vorhandenen +LocalService-PowerShell-Ergebnisse bleiben separate Nachweise. + +## Aktualisierung nach Pair7: konkrete Vorbereitung, keine Aktivierung + +Die späteren tatsächlichen Lesebelege vom 16. November liegen unter +`devstate/windows-system-job-bootstrap/80b99f94-d294-4148-8792-1e2473383963/read-only.json` +und `e29a7b62-2ef6-4add-9de8-518043236972/server-read-only.json`. +Sie ersetzen den unten ausdrücklich historischen Stand nicht: +Agent `d6302aa0…`, PID9084, LocalService/Auto; Helper `0502d6c8…`, PID10052, +LocalSystem/Manual. Originalsettings `3902a7d6…` bleiben Schema1, +`enable_effects=false`; Pin `4e098eb3…`. Der authentisierte reale Helperbeleg +bestätigt SID18, dieselben tatsächlichen Ledger-/Lock-FileIDs und eine eigene +qualifizierte Uhr; er behauptet keine bereits ausgeführte SYSTEM-Aktion. +Serverimage `a7fc4243…` auf beiden Rollen, keine SYSTEM-Flags oder +SYSTEM-Berechtigungen, null SYSTEM-Aufträge und null offene Windows-Aufträge. + +Zunächst bestanden auf der tatsächlichen Cloud-Linux-VM zwei gezielte +Domainverträge für explizite FullMaintenance-Identität/Capabilities und exakte +Skriptbytes. Danach bestanden auf Windows genau zwei bereits vorhandene, +wirkungslose JSON-/Policyverträge: + +- `helper_runtime::script_tests::system_script_success_requires_exact_profile_identity_bytes_and_raw_output`, +- `helper_system::tests::old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi`. + +Jeder Fall meldete 1 bestanden, 0 Fehler, 0 ausgelassen. Öffentliche Original- +Ergebniszusammenfassungen: [Linux](evidence/windows-system-script-prerequisites-20261116-linux.json) +und [Windows](evidence/windows-system-script-prerequisites-20261116-windows.json). +Der zweite Windows-Test prüft auch die Abgrenzung alter Schema-/MSI-Konfiguration; +er installiert kein MSI und qualifiziert keine MSI-Wirkung. Alle vier Fälle +sind kontrollierte Unitprozesse, keine SYSTEM- oder PowerShell-Aufträge. + +Der aus dem **tatsächlich installierten Quellstand** gebaute Typ-Renderer +`0f5a4dbc…` wurde auf Windows mit ausschließlich öffentlichen Metadaten +tatsächlich ausgeführt. Er erzeugte die neue reine Skriptpolicy +`cfd126d383ec0a948a73270a8362bd835d79341a079be05ce50088f0dbc5791c` +und zugehörigen Pin/Qualifikationsbytes. NativePrerequisiteResult und alle +Originalquellen-/Nachweis-SHAs liegen unter +`devstate/windows-system-job-bootstrap/2fa63669-7e4d-4376-8735-78612a0c5388`. +Der Beleg heißt ausdrücklich `native_prerequisites_only`, +`target_job_executed=false`. Das ist Voraussetzung für einen ersten genehmigten +Test, kein vorweggenommener SYSTEM-Erfolg. + +Der vorbereitete Controller `APPLY_STOPPED` hält beide ursprünglichen nativen +Lebensdauersperren und verlangt gestoppte Originalprozesse, exakte Image-, +Settings-, Pin- und Aktivkonfigurations-CAS. Er erhält PKI-Metadaten, Journale, +ursprüngliche FileIDs und Zeitprofil; private Schlüsselbytes werden nicht +gelesen. Er publiziert ausschließlich die vier exakt gerenderten öffentlichen +Dateien und ändert separat nur den Starttyp des fest gebundenen Helpers von +Manual auf Automatic. Vorhandene Dienstkonten, Kommandos und ACLs bleiben +erhalten. Jeder Teilintent ist create-only; Teilfehler werden gelesen und +nicht blind wiederholt. Er startet keinen Dienst. Tatsächlicher PS5.1-AST- +Parser: null Fehler; die neuen nativen C#-Deklarationen wurden auf Windows nur +kompiliert, weder konstruiert noch ausgeführt. Dateiaustausch, Sperren und +Starttypänderung dieses Controllers sind damit noch nicht nativ abgenommen. + +Nach der koordinierten Anwendung müssen tatsächliche Auto-SCM-Konfiguration, +neue Rollen-/Prozessbeobachtungen, unabhängige Uhren und regulärer signierter +Sync erneut belegt werden. Profil7 bindet unveränderte Pair-Images; seine alten +Rollenbelege dürfen nicht als bereits gemessene Auto-Konfiguration ausgegeben +werden. Erst der neue tatsächliche Nachweis darf die zusätzliche +Starttypänderung bestätigen. Die vorhandene Runtime startet den Helper nicht +selbst; Automatic beseitigt diese konkrete Wiederanlauflücke. + +`deploy/windows_system_scope_server.py` ist ein getrennter, noch nicht +ausgeführter Root-Bootstrap ohne CLI-Dispatch. Er verlangt die exakten beiden +aktuellen Container und ihre erhaltene Compose-Dateikette, bestehende +Actor-/Berechtigungsbytes sowie einen frischen authentisierten Client mit +bereits tatsächlich qualifizierten SYSTEM-Skript-Capabilities. In einer +Transaktion werden nur den zwei fest gebundenen bestehenden Akteuren +`system:execute` hinzugefügt; keine Job-/Autorisierungszeile wird angelegt. +Er erhält alle bisherigen Compose-Overlays, Images, TLS- und Loopbackports; +nur die zwei SYSTEM-Variablen und ein geschützter read-only Policybind werden +additiv auf API und Gateway ergänzt. Die reine Skriptpolicy läuft spätestens +15 Minuten nach Vorbereitung ab. Fremde aktive Jobs verweigern den Schritt. +Teilwirkung bleibt erhalten und verlangt Lesen statt automatischen Retry. + +Das lokale Paket +`devstate/windows-system-job-bootstrap/8cde774e-46b8-40da-baa9-7d4ecdcbf5c1` +enthält vollständige öffentliche CAS-Inputs, beide Controller-SHAs, ro-Overlay, +Berechtigungsintent und den festen 30s-SYSTEM-Skriptentwurf mit Ausgabe +`Windows-System-MVP:S-1-5-18`. Es wurde **kein MCP-Antrag eingereicht**. +Zeitplan und 15-Minuten-Frist müssen beim tatsächlich koordinierten Schritt +frisch vorbereitet werden. Erst danach folgen ein eigenständiger persistenter +MCP-Antrag, echte simulierte WebUI-Genehmigung und native Einzelausführung. + +## Tatsächlich lesend geprüft + +Der bestehende bestätigte SSH-Entwicklungstransport wurde mit +`deploy/windows_system_job_bootstrap.py inspect` ausschließlich lesend genutzt. +Originalbeleg: +`devstate/windows-system-job-bootstrap/db480794-b2f3-47fa-ba8c-d599f09ca50a/read-only.json`. + +- Agent `9651b2e518b3…`, PID 3956, konfigurierte SCM-Anmeldung LocalService. +- Unveränderter Helper `59675a3cbb3a…`, PID 8084, SCM-Anmeldung LocalSystem. +- Tatsächliche `helper.json`: Schema 1, `enable_effects=false`, + `allow_reboot=false`, leere Dienstliste, kein Skriptprofil. +- Settings-Rawhash `4c073cd3d4badb09d8c0f1c270b4cee9df533df416550f68bf3e336e3da7673c`; + Agent-Pin-Rawhash `9d46dffe88f565b8b04554335d9669f5c83211b32419908a579b1cd4560443ec`. +- `system-qualification.json` und `system-native-result.json` fehlen. +- Der tatsächliche Agent-Probenbeleg um 10:37:44 UTC bestätigt die beidseitig + authentisierte Pipe, denselben Agentprozess, Helperimage/Policy, SYSTEM-SID 18 + und bestehende Ledger-/Lock-Datei-IDs. Er meldet jedoch ausdrücklich + `helper_clock_qualified=false`, `helper_ready=false` und keine qualifizierten + SYSTEM-Capabilities. Dies ist kein positiver Zeit-/Jobbereitschaftsnachweis. + +Der getrennte Serverread (`inspect-server`) liegt unter +`devstate/windows-system-job-bootstrap/a39e7b13-bb2d-400a-a0fd-aad3ee460702/server-read-only.json`. +API-Image `c4c869114a60…` und Gateway `422c2c28a91a…` führen das explizite +Developmentprofil mit `https://localhost:18443` als UI-Origin. Beide haben +**keine** `RMM_DEV_SYSTEM_ENABLED`-/`RMM_DEV_SYSTEM_POLICY_FILE`-Freigabe. +Die vorhandene Automation `automation:11111111-1111-4111-8111-111111111111` +und `simulated-testprincipal-a` besitzen `scripts:execute`, aber beide noch +kein `system:execute`. Für den Windowsgast bestehen zwei Aufträge, null +SYSTEM-Aufträge und null offene Aufträge. Der gespeicherte normale Sync ist +bereit; das ersetzt den oben ausdrücklich negativen nativen Zeitbeleg nicht. +Keine Zugangsdaten, Tokens oder privaten Schlüssel wurden gelesen/exportiert. + +## Was die erste Qualifikation besagt + +Der Capabilityvertrag verlangt vor einem SYSTEM-Job einen administrativ +provisionierten nativen Qualifikationsbeleg, tatsächliche geschützte Settings, +einen aktuellen authentisierten Helper und eine qualifizierte Uhr. Dieser +Beleg ist die **Voraussetzung für einen ersten genehmigten Test**, nicht dessen +vorweggenommenes Ergebnis. Die neue Vorbereitung unterscheidet ausdrücklich: + +- `scope=native_prerequisites_only`, +- `source=operator_reviewed_native_units_and_peer`, +- `target_job_executed=false`, +- nur `validated_actions=["run_script"]`, +- genaue tatsächliche Agent-/Helperhashes und ursprüngliche Beleg-SHA-Referenzen. + +`status=passed` darf ausschließlich die tatsächlich geprüften nativen +Unit-/OS-/Peer-Voraussetzungen bezeichnen. Es darf nicht aus einem bloßen Build, +SCM-Kontonamen oder einem noch negativen Zeitbeleg erfunden werden. Die erste +SYSTEM-Ausführung wird später unter eigenem Job-/Versuchs-/Grant-/Auditbezug +nachgewiesen. Aktuelle Uhr und normaler beidseitiger SignedSync bleiben +unabhängige laufende Gates. Ein Qualifikationsfile schafft keine Ready-Lease, +keine Jobgenehmigung und keinen Startgrant. + +## Konkrete neue Quellen + +`crates/agent-windows/examples/windows_system_policy_prepare.rs` liest nur einen +begrenzten öffentlichen JSON-Eingang von stdin. Es deserialisiert die echten +vorhandenen Settings mit dem **tatsächlichen Rust-Typ** `helper_system::Settings`, +prüft den passiven Ausgangsstand und erzeugt Settings/Pin/Policyhash mit dessen +regulärem `validate`, `policy_sha256` und `pin`. Keine PowerShell-JSON-Reihenfolge +wird als kanonischer Policyhash ausgegeben. + +Der einzige erste Zielzustand ist: + +```json +{ + "schema_version": 3, + "allowed_services": [], + "max_runtime_seconds": 30, + "enable_effects": true, + "allow_reboot": false, + "allowed_script_profiles": ["full_maintenance_v1"] +} +``` + +Dies ist ein Ausschnitt; Binding, beide Peeridentitäten und die tatsächlichen +Imagepfade bleiben Bestandteil der vollständig validierten Settings. MSI wird +nicht konfiguriert. Der Agent-Binärpin muss zum tatsächlich installierten neuen +Agenten passen, der Helper bleibt zunächst `59675…`. Der administrative +Qualifikationsbeleg bindet genau diesen Policy-/Code-/Ergebnisstand. + +Der Pythoncontroller bietet lesende VM-/Serverprüfung und lokale +Paketvorbereitung. Die getrennte Konstante `APPLY_STOPPED` ist ein konkret +reviewbarer Bootstrapquelltext, **nicht automatisch vom CLI aufgerufen**. +Sie verlangt bereits quieszent gestoppte Agent-/Helperdienste und den beendeten +ursprünglichen PID-/Creationzeugen, prüft erneut tatsächliche Binär- und +Originalsettings-/Pinhashes und schreibt create-only einen eigenen privaten +Vorgang. Settings und Pin werden unter Erhalt der alten Dateien ausgetauscht; +Qualifikation und natives Voraussetzungsergebnis werden neu angelegt. Nur +SYSTEM/Administratoren dürfen schreiben, die beiden festen Service-SIDs lesen. +Es gibt keine PKI-/Ledger-/Konfigurationsreparatur und keinen Dienststart durch +diesen Quelltext. Bei Teilfehler oder verlorenem Reply ausschließlich denselben +Vorgang nachlesen; kein zweiter Apply und kein blindes Zurücksetzen. +Der Rootkoordinator muss zusätzlich die vorhandenen Journal-/Datei-ID-Zeugen +vor und nach dem Dienstwechsel unabhängig nachlesen. + +Der PowerShell-Parser auf der tatsächlichen VM hat diesen Quelltext geprüft: +**0 Syntaxfehler**, `parse_only=true`, `target_mutations=false`. Er hat den +Bootstrapinhalt dabei nicht ausgeführt. Beleg `controller-parser.json` im +ursprünglichen lesenden VM-Fall. Python-Syntaxprüfung bestand. Der tatsächliche +Windows-GNU-Check des Rust-Renderers bestand; die strengere Clippyprüfung war +zunächst durch noch nicht verbundene parallele Updaterhandler blockiert. +Diese Warnungen werden nicht unterdrückt und nicht als grüner Lauf ausgegeben. + +## Zentrale Begrenzung und tatsächliche erste Ausführung + +Die Vorbereitung erzeugt eine feste Developmentpolicy mit Schema 3, genau dem +vorhandenen Tenant/Asset/Agent, Generation 1/Assignment 1, beiden bestehenden +Prinzipalen, den tatsächlichen Helper-/Policyhashes und höchstens 30 Sekunden +Laufzeit. Die Policy erlaubt nur das explizite Full-Skriptprofil. Dienstliste +leer, keine MSI-Rezepte und kein Rebootfeld. Die separat befristete Policy gilt +15 Minuten und ist weiterhin keine Genehmigung. + +Der Koordinator muss ausschließlich den beiden bestehenden Mitgliedschaften +`system:execute` hinzufügen, alle bisherigen Rechte/Rollen erhalten und der +Automation niemals `plans:approve` geben. Vor jedem SQL-CAS die tatsächlichen +alten Rechte und unveränderte Widerrufszustände prüfen. Diese administrative +Rechteprovisionierung ist getrennt vom unveränderlichen Jobplan und wird nicht +als Jobgenehmigung dargestellt. + +Sowohl API als auch Gateway brauchen denselben geschützten read-only +Policy-Mount und ausschließlich: + +```text +RMM_DEV_SYSTEM_ENABLED=true +RMM_DEV_SYSTEM_POLICY_FILE=/system-policy/policy.json +``` + +Der Dateibesitzer muss dem tatsächlich per `stat` geprüften Besitzer von +`RMM_JOB_KEY_FILE` entsprechen; Modus 0600 und sichere Elternverzeichnisse sind +Pflicht. Dafür wird nur Schlüsselmetadatum gelesen. Bestehende Image-/Zeitbroker- +Overlays, TLS, Loopbackports, Root-/APT-Policies und Datenbank werden erhalten. +Diese Vorbereitung schaltet weder OIDC noch öffentliche Verwaltungsports frei. + +Erst nach tatsächlichem Dienstwechsel, frischen getrennten Zeitbelegen, +normalem SignedSync, authentisierter neuer Helperprobe und den exakt gespeicherten +SYSTEM-Skriptcapabilities wird der erste feste PowerShell-Identitätstest per +MCP beantragt. Er bleibt bis zum tatsächlichen sichtbar simulierten +WebUI-Klick `pending_approval`. Prozessprofil `powershell_51_remote_signed`, +explizite SYSTEM-Identität und `full_maintenance_v1` werden vorher angezeigt. +Danach müssen echte SID 18, exakte Ausgabe, einmaliger ursprünglicher Verbrauch/ +Start, finales Originaloutcome und `testsimulation`-Audit unabhängig gelesen +werden. Erst das ist die erste SYSTEM-Jobabnahme; danach dokumentieren und pushen. + +SCM- und MSI-Qualifikation folgen jeweils als eigene Erweiterung mit wirklichen +Dienst-/Rezeptpins und eigenen WebUI-Plänen. Sie werden weder aus dem +Skriptprofil noch aus einer Paket-Bauprüfung abgeleitet. Ein Reboot ist kein +Nebeneffekt dieses Schritts.