diff --git a/crates/agent-windows/examples/time_route_probe.rs b/crates/agent-windows/examples/time_route_probe.rs new file mode 100644 index 0000000..e01f469 --- /dev/null +++ b/crates/agent-windows/examples/time_route_probe.rs @@ -0,0 +1,496 @@ +//! Fixed passive development route fixture, never an installed-role or clock proof. +//! Existing device mTLS material stays on this VM and is never hashed or exported. +#[cfg(all(windows, feature = "system-helper"))] +#[path = "../../agent/src/https_channel.rs"] +pub mod https_channel; + +#[cfg(all(windows, feature = "system-helper"))] +mod probe { + use anyhow::{Result, ensure}; + use rmm_agent_core::{ + auth::Binding, + crypto::{DalekVerifier, Ed25519Verifier}, + }; + use rmm_agent_windows::{ + helper_ipc::{self as ipc, PinnedFile}, + native, + }; + use rmm_time_attestation::{Context, Payload, Request, Role, SignedAttestation}; + use serde::Deserialize; + use serde_json::{Value, json}; + use sha2::{Digest, Sha256}; + use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + os::windows::{ + fs::{MetadataExt, OpenOptionsExt}, + io::{FromRawHandle, OwnedHandle}, + }, + path::{Path, PathBuf}, + ptr, + time::Duration, + }; + use uuid::Uuid; + use windows_sys::Win32::{ + Foundation::{ERROR_NO_TOKEN, GetLastError}, + Security::{ + CheckTokenMembership, CreateWellKnownSid, TOKEN_QUERY, WinBuiltinAdministratorsSid, + }, + Storage::FileSystem::{ + FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, + }, + System::Threading::{GetCurrentThread, OpenThreadToken}, + }; + + const ROOT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\time-route"; + const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json"; + const STATE: &str = r"C:\ProgramData\RustDiscovery\state"; + const CA: &str = r"C:\ProgramData\RustDiscovery\server-ca.pem"; + const PEER_PIN: &str = r"C:\ProgramData\RustDiscoverySystem\agent-pin.json"; + const CONFIG_SHA: &str = "7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851"; + const PEER_PIN_SHA: &str = "af518db88a6d4a856c32ca9d89d88405689aa2d89163ab0cb638c1abdd8fa118"; + const TIME_PIN_SHA: &str = "c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2"; + const AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3"; + const ASSET: &str = "a176520e-8a91-4e93-a78b-8e7620f430e0"; + const SERVER: &str = "discovery.ease-technologies.de"; + const DOMAIN: &[u8] = b"RMM-TIME-ATTESTATION/v1\0"; + + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct FixtureContext { + schema_version: u32, + case_id: Uuid, + connection_generation: u64, + windows_boot_id: Uuid, + server_boot_id: Uuid, + server_context_evidence_sha256: String, + binding_sha256: String, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct PublicTimePin { + schema_version: u32, + algorithm: String, + server_instance: Uuid, + key_id: String, + key_generation: u64, + public_key_hex: String, + } + fn hash(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) + } + fn digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v)) + } + fn hex(value: &str) -> Result<[u8; N]> { + ensure!( + value.len() == 2 * N && value.bytes().all(|v| v.is_ascii_hexdigit()), + "FIXTURE_HEX" + ); + let mut out = [0; N]; + for (i, b) in out.iter_mut().enumerate() { + *b = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16)?; + } + Ok(out) + } + fn administrator() -> Result<()> { + let mut thread = ptr::null_mut(); + if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 { + let _held = unsafe { OwnedHandle::from_raw_handle(thread) }; + anyhow::bail!("FIXTURE_IMPERSONATION_FORBIDDEN"); + } + ensure!( + unsafe { GetLastError() } == ERROR_NO_TOKEN, + "FIXTURE_THREAD_TOKEN" + ); + let mut sid = [0usize; 16]; + let mut bytes = std::mem::size_of_val(&sid) as u32; + ensure!( + unsafe { + CreateWellKnownSid( + WinBuiltinAdministratorsSid, + ptr::null_mut(), + sid.as_mut_ptr().cast(), + &mut bytes, + ) + } != 0, + "FIXTURE_ADMIN_SID" + ); + let mut enabled = 0; + ensure!( + unsafe { CheckTokenMembership(ptr::null_mut(), sid.as_mut_ptr().cast(), &mut enabled) } + != 0 + && enabled != 0, + "FIXTURE_ADMIN_REQUIRED" + ); + Ok(()) + } + fn public_read( + path: &Path, + maximum: usize, + readers: &[String], + ) -> Result<(PinnedFile, Vec)> { + let mut held = PinnedFile::open(path, false, readers, &[], false)?; + ensure!( + held.file.metadata()?.len() <= maximum as u64, + "FIXTURE_INPUT_LIMIT" + ); + let mut raw = Vec::new(); + (&mut held.file) + .take(maximum as u64 + 1) + .read_to_end(&mut raw)?; + ensure!(raw.len() <= maximum, "FIXTURE_INPUT_LIMIT"); + held.check()?; + Ok((held, raw)) + } + // Do not call sha256() on these credential handles, including on error. + // Share-read only prevents content replacement/write during the held read. + fn credential_read(path: &Path, maximum: usize) -> Result<(File, Vec)> { + native::private_path(path, false)?; + let mut held = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path)?; + let before = held.metadata()?; + ensure!( + before.is_file() + && before.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 + && before.len() <= maximum as u64, + "FIXTURE_CREDENTIAL_TYPE" + ); + let identity = ipc::file_identity(&held)?; + let mut raw = Vec::new(); + (&mut held).take(maximum as u64 + 1).read_to_end(&mut raw)?; + ensure!(raw.len() <= maximum, "FIXTURE_CREDENTIAL_LIMIT"); + native::private_path(path, false)?; + let current = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path)?; + ensure!( + ipc::file_identity(¤t)? == identity && held.metadata()?.len() == before.len(), + "FIXTURE_CREDENTIAL_REPLACED" + ); + Ok((held, raw)) + } + fn create(root: &Path, name: &str, raw: &[u8]) -> Result<()> { + ensure!(raw.len() <= 32768, "FIXTURE_REPORT_LIMIT"); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(root.join(name))?; + file.write_all(raw)?; + file.sync_all()?; + Ok(()) + } + fn verify_signed( + raw: &[u8], + request: &Request, + pin: &PublicTimePin, + context: &FixtureContext, + ) -> Result { + let signed: SignedAttestation = serde_json::from_slice(raw)?; + ensure!( + serde_json::to_vec(&signed)? == raw && signed.payload.len() <= 8192, + "FIXTURE_CANONICAL_RESPONSE" + ); + ensure!( + signed.signature_hex.len() == 128 + && signed + .signature_hex + .bytes() + .all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v)), + "FIXTURE_SIGNATURE_FORMAT" + ); + let payload: Payload = serde_json::from_str(&signed.payload)?; + ensure!( + serde_json::to_string(&payload)? == signed.payload, + "FIXTURE_CANONICAL_PAYLOAD" + ); + ensure!( + payload.version == 1 + && payload.server_instance == pin.server_instance + && payload.server_boot_id == context.server_boot_id + && payload.key_id == pin.key_id + && payload.key_generation == pin.key_generation + && payload.request_sha256 == request.sha256()? + && payload.captured_utc_ns > 0 + && payload.server_error_ns <= rmm_time_attestation::MAX_SERVER_ERROR_NS + && payload.source_sync_age_ns <= rmm_time_attestation::MAX_SYNC_AGE_NS, + "FIXTURE_RESPONSE_BINDING" + ); + let key = hex::<32>(&pin.public_key_hex)?; + let signature = hex::<64>(&signed.signature_hex)?; + let mut message = DOMAIN.to_vec(); + message.extend_from_slice(signed.payload.as_bytes()); + ensure!( + DalekVerifier.validate_key(&key)? + && DalekVerifier.verify(&key, &message, &signature)?, + "FIXTURE_SIGNATURE" + ); + Ok(payload) + } + async fn bounded_response(mut response: reqwest::Response) -> Result<(u16, Vec)> { + let status = response.status().as_u16(); + if status == 200 { + ensure!( + response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + == Some("application/json"), + "FIXTURE_RESPONSE_MEDIA" + ); + } + ensure!( + response.content_length().is_none_or(|n| n <= 16384), + "FIXTURE_RESPONSE_LENGTH" + ); + let mut raw = Vec::new(); + while let Some(chunk) = response.chunk().await? { + ensure!( + raw.len() + .checked_add(chunk.len()) + .is_some_and(|n| n <= 16384), + "FIXTURE_RESPONSE_LIMIT" + ); + raw.extend_from_slice(&chunk); + } + Ok((status, raw)) + } + async fn execute(root: &Path, id: Uuid) -> Result { + let mut directory = PinnedFile::open(root, true, &[], &[], false)?; + let mut root_directory = PinnedFile::open(Path::new(ROOT), true, &[], &[], false)?; + ensure!( + std::env::current_exe()? + .to_string_lossy() + .eq_ignore_ascii_case(&root.join("TimeRouteProbe.exe").to_string_lossy()), + "FIXTURE_OWN_EXECUTABLE_PATH" + ); + let mut leaves = fs::read_dir(root)? + .map(|v| v.map(|v| v.file_name().to_string_lossy().into_owned())) + .collect::>>()?; + leaves.sort(); + ensure!( + leaves == ["TimeRouteProbe.exe", "context.json", "time-public-key.json"], + "FIXTURE_CREATE_ONCE_CASE" + ); + let (mut context_file, context_raw) = public_read(&root.join("context.json"), 4096, &[])?; + let context: FixtureContext = serde_json::from_slice(&context_raw)?; + ensure!( + context.schema_version == 1 + && context.case_id == id + && context.connection_generation > 1 + && !context.windows_boot_id.is_nil() + && !context.server_boot_id.is_nil() + && digest(&context.server_context_evidence_sha256) + && digest(&context.binding_sha256), + "FIXTURE_ROOT_CONTEXT" + ); + let (mut time_file, time_raw) = public_read(&root.join("time-public-key.json"), 4096, &[])?; + ensure!( + hash(&time_raw) == TIME_PIN_SHA, + "FIXTURE_REAL_PUBLIC_TIME_PIN" + ); + let pin: PublicTimePin = serde_json::from_slice(&time_raw)?; + ensure!( + pin.schema_version == 1 + && pin.algorithm == "Ed25519" + && !pin.server_instance.is_nil() + && pin.key_generation > 0 + && !pin.key_id.is_empty() + && pin.key_id.len() <= 64 + && pin + .key_id + .bytes() + .all(|v| v.is_ascii_alphanumeric() || v == b'-' || v == b'_') + && digest(&pin.public_key_hex), + "FIXTURE_PUBLIC_TIME_PROFILE" + ); + let agent_sid = native::service_sid()?; + // The protected peer-pin has read ACEs for both fixed installed services. + let helper_sid = ipc::service_sid("RmmDiscoverySystemHelper")?; + let (mut peer_file, peer_raw) = + public_read(Path::new(PEER_PIN), 16384, &[agent_sid, helper_sid])?; + ensure!(hash(&peer_raw) == PEER_PIN_SHA, "FIXTURE_ORIGINAL_PEER_PIN"); + let peer: ipc::Pin = serde_json::from_slice(&peer_raw)?; + peer.validate()?; + let binding: Binding = peer.binding; + ensure!( + binding.agent_id.to_string() == AGENT + && binding.asset_id.to_string() == ASSET + && hash(&serde_json::to_vec(&binding)?) == context.binding_sha256, + "FIXTURE_EXISTING_DEVICE_BINDING" + ); + ensure!( + hex::<32>(&pin.public_key_hex)? != hex::<32>(&binding.public_key_hex)?, + "FIXTURE_TIME_JOB_KEY_REUSE" + ); + let (config_handle, config_raw) = credential_read(Path::new(CONFIG), 4096)?; + ensure!( + hash(&config_raw) == CONFIG_SHA, + "FIXTURE_ORIGINAL_PASSIVE_CONFIG" + ); + let config: Value = serde_json::from_slice(&config_raw)?; + ensure!( + config["server_name"] == SERVER + && config["connect_address"] == "88.99.80.202:443" + && config["state_directory"] == STATE + && config["ca_file"] == CA + && config["transport"] == "auto", + "FIXTURE_CONFIG_ENDPOINT" + ); + create( + root, + "intent.json", + &serde_json::to_vec(&json!({"case_id":id,"run_once":true, + "context_sha256":hash(&context_raw),"public_time_pin_sha256":TIME_PIN_SHA, + "route":rmm_time_attestation::ENDPOINT,"no_jobs":true,"clock_proof":false}))?, + )?; + let (ca_handle, ca) = credential_read(Path::new(CA), 32768)?; + let state = Path::new(STATE); + let (certificate_handle, certificate) = credential_read(&state.join("device.pem"), 32768)?; + let (private_handle, mut private_key) = credential_read(&state.join("device.key"), 16384)?; + let client = crate::https_channel::mtls_client( + "88.99.80.202:443".parse()?, + &ca, + &certificate, + &private_key, + )?; + private_key.fill(0); + drop(private_key); // Private bytes never enter any JSON, digest or report. + let incarnation = Uuid::new_v4(); + let mut reports = Vec::new(); + for kind in ["positive-agent", "tenant-mismatch", "stale-connection"] { + let mut request = Request { + version: 1, + endpoint: rmm_time_attestation::ENDPOINT.into(), + nonce: rand::random::<[u8; 32]>() + .iter() + .map(|v| format!("{v:02x}")) + .collect(), + context: Context { + tenant_id: binding.tenant_id, + asset_id: binding.asset_id, + agent_id: binding.agent_id, + enrollment_generation: binding.enrollment_generation, + assignment_generation: binding.assignment_version, + connection_generation: context.connection_generation, + windows_boot_id: context.windows_boot_id, + verifier_incarnation: incarnation, + role: Role::Agent, + helper_image_sha256: None, + binding_schema: 1, + }, + }; + if kind == "tenant-mismatch" { + request.context.tenant_id = + Uuid::parse_str("22222222-2222-4222-8222-222222222222")?; + ensure!( + request.context.tenant_id != binding.tenant_id, + "FIXTURE_FOREIGN_TENANT" + ); + } + if kind == "stale-connection" { + request.context.connection_generation -= 1; + } + request.validate()?; + if kind == "positive-agent" { + create( + root, + "positive-request.json", + &serde_json::to_vec(&request)?, + )?; + } + let (status, raw) = tokio::time::timeout(Duration::from_secs(3), async { + let response = client + .post("https://discovery.ease-technologies.de:443/agent/v1/time-attestation") + .timeout(Duration::from_secs(3)) + .json(&request) + .send() + .await?; + bounded_response(response).await + }) + .await??; + let mut report = json!({"kind":kind,"http_status":status,"response_bytes":raw.len(),"response_sha256":hash(&raw),"request_sha256":request.sha256()?}); + if kind == "positive-agent" { + create(root, "positive-response.json", &raw)?; + ensure!(status == 200, "FIXTURE_POSITIVE_STATUS"); + let payload = verify_signed(&raw, &request, &pin, &context)?; + report["signature_verified"] = true.into(); + report["whole_request_context_bound"] = true.into(); + report["server_boot_id"] = payload.server_boot_id.to_string().into(); + } else { + ensure!( + status == if kind == "tenant-mismatch" { 403 } else { 409 }, + "FIXTURE_NEGATIVE_STATUS" + ); + } + create( + root, + &format!("{kind}-result.json"), + &serde_json::to_vec(&report)?, + )?; + reports.push(report); + } + context_file.check()?; + time_file.check()?; + peer_file.check()?; + directory.check()?; + root_directory.check()?; + drop((config_handle, ca_handle, certificate_handle, private_handle)); + let report = json!({"schema_version":1,"case_id":id,"verified":true,"execution_context":"bootstrap_administrator_protocol_probe", + "endpoint":rmm_time_attestation::ENDPOINT,"reports":reports,"shared_existing_device_mtls":true, + "private_key_exported":false,"private_key_hashed":false,"private_key_copied_to_evidence":false, + "certificate_verification_disabled":false,"service_role_proven":false,"trusted_clock_proven":false, + "clock_freshness_qualified":false,"sync_ready":false,"jobs_created":false,"grants_created":false, + "context_sha256":hash(&context_raw),"server_context_evidence_sha256":context.server_context_evidence_sha256, + "public_time_pin_sha256":TIME_PIN_SHA}); + create(root, "report.json", &serde_json::to_vec(&report)?)?; + Ok(report) + } + pub fn run() -> Result { + administrator()?; + let args: Vec = std::env::args().skip(1).collect(); + ensure!( + args.len() == 2 && args[0] == "probe", + "FIXTURE_FIXED_ARGUMENTS" + ); + let id = Uuid::parse_str(&args[1])?; + ensure!( + !id.is_nil() && id.to_string() == args[1], + "FIXTURE_CANONICAL_CASE" + ); + // Before any async runtime/threads, force the one verified DNS identity. + unsafe { + std::env::set_var("RMM_SERVER_NAME", SERVER); + } + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + runtime.block_on(execute(&PathBuf::from(ROOT).join(id.to_string()), id)) + } +} +#[cfg(all(windows, feature = "system-helper"))] +fn main() { + match probe::run() { + Ok(value) => println!("{value}"), + Err(_) => { + println!( + "{}", + serde_json::json!({"verified":false,"code":"WINDOWS_TIME_ROUTE_FIXTURE_INCOMPLETE","service_role_proven":false,"trusted_clock_proven":false}) + ); + std::process::exit(2); + } + } +} +#[cfg(not(all(windows, feature = "system-helper")))] +fn main() { + eprintln!("Fixed time route fixture requires native Windows and system-helper build"); + std::process::exit(1); +} diff --git a/deploy/windows/time_route_acceptance.py b/deploy/windows/time_route_acceptance.py new file mode 100644 index 0000000..bfe7eed --- /dev/null +++ b/deploy/windows/time_route_acceptance.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Fixed once-only passive route fixture operator. All target phases initially closed.""" +import argparse +import base64 +import hashlib +import json +from pathlib import Path +import subprocess +import uuid +import signed_clock_capture_acceptance as original +import time_route_context as collector + +ROOT=original.ROOT +STATE=ROOT/'devstate/windows-time-route-native' +QUAL=ROOT/'devstate/windows-signed-clock/time-route-fixture-qualification-3fdf513e-197b-41ab-b161-9dfc2adc94da' +RECEIPT_SHA='fce8c42cce33a35be1ee0468c97010ac3797a713668503783e449d30ea538678' +EXE_SHA='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088' +EXE_BYTES=19172660 +PIN=ROOT/'devstate/server-time-source-bootstrap/qualified-time-public-key.json' +PIN_SHA='c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2' +# Root pins {id, receipt_sha256} only after the actual post-deploy collector read. +CONTEXT_GATE=None +require,save,load,sha=original.require,original.save,original.load,original.sha + +SCRIPT=r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if(!$p-or$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id){throw 'Exact route action/case'} +if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,context_base64,context_sha256,id,manifest_sha256,pin_base64'-or$p.context_sha256-cnotmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed route payload'} +$base='C:\ProgramData\RustDiscoveryBootstrap';$root=Join-Path $base 'time-route';$controlRoot=Join-Path $base 'time-route-control';$case=Join-Path $root $p.id;$control=Join-Path $controlRoot $p.id +$exe=Join-Path $case 'TimeRouteProbe.exe';$source=Join-Path (Join-Path $base '4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088') 'TimeRouteProbe.exe' +function Check($path,[bool]$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Protected regular route path'};$parent=$i.Directory;if($directory){$parent=$i.Parent};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No route reparse ancestry'};$parent=$parent.Parent};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Route empty DACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route DACL'}}} +function Get-RmmRouteBytesSha256([byte[]]$raw){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}} +function FH($path){Check $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +function WriteNew($path,[byte[]]$raw){if($raw.Length-gt32768){throw 'Route record bound'};$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($raw,0,$raw.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Record($name,$value){WriteNew (Join-Path $control $name) ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 20 -Compress)))} +function DirectoryNew($path){New-Item -ItemType Directory -Path $path|Out-Null;$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $a;Check $path $true} +function ReadOwn{ + $records=[ordered]@{};if(Test-Path -LiteralPath $control){Check $control $true;foreach($name in @('stage-intent.json','stage-complete.json','run-attempt.json','process.json','exit.json','stdout.txt','stderr.txt')){$path=Join-Path $control $name;if(Test-Path -LiteralPath $path){Check $path $false;$i=Get-Item -LiteralPath $path;if($i.Length-gt32768){throw 'Bounded own control read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}} + if(Test-Path -LiteralPath $case){Check $case $true;foreach($name in @('intent.json','report.json','positive-request.json','positive-response.json','positive-agent-result.json','tenant-mismatch-result.json','stale-connection-result.json')){$path=Join-Path $case $name;if(Test-Path -LiteralPath $path){Check $path $false;if((Get-Item -LiteralPath $path).Length-gt32768){throw 'Bounded own result read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}} + return @{id=$p.id;read_only=$true;records=$records;manifest_sha256=$p.manifest_sha256} +} +Check $base $true +if($p.action-ceq'read'){ReadOwn|ConvertTo-Json -Depth 20 -Compress;exit 0} +$context=[Convert]::FromBase64String($p.context_base64);$pin=[Convert]::FromBase64String($p.pin_base64) +if($context.Length-gt4096-or(Get-RmmRouteBytesSha256 $context)-cne$p.context_sha256-or$pin.Length-gt4096-or(Get-RmmRouteBytesSha256 $pin)-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Exact actual public route inputs'} +$c=[Text.Encoding]::UTF8.GetString($context)|ConvertFrom-Json;if($c.case_id-cne$p.id){throw 'Actual context own case'} +if($p.action-ceq'stage'){ + if((Test-Path -LiteralPath $case)-or(Test-Path -LiteralPath $control)){throw 'Original route stage exists; read only'} + foreach($directory in @($root,$controlRoot)){if(Test-Path -LiteralPath $directory){Check $directory $true}else{DirectoryNew $directory}} + DirectoryNew $control;Record 'stage-intent.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;once=$true} + DirectoryNew $case + if((FH $source)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(Get-Item -LiteralPath $source).Length-ne19172660){throw 'Exact route EXE source'} + [IO.File]::Copy($source,$exe,$false);$f=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$f.Flush($true)}finally{$f.Dispose()} + WriteNew (Join-Path $case 'context.json') $context;WriteNew (Join-Path $case 'time-public-key.json') $pin + if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Actual own staged inputs'} + Record 'stage-complete.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;staged=$true} + @{id=$p.id;staged=$true;manifest_sha256=$p.manifest_sha256}|ConvertTo-Json -Compress;exit 0 +} +if($p.action-cne'run'){throw 'Exact run required before process start'} +Check $case $true;Check $control $true;Check (Join-Path $control 'stage-complete.json') $false +$stage=Get-Content -LiteralPath (Join-Path $control 'stage-complete.json') -Raw|ConvertFrom-Json +if($stage.id-cne$p.id-or$stage.manifest_sha256-cne$p.manifest_sha256-or$stage.context_sha256-cne$p.context_sha256-or$stage.staged-ne$true){throw 'Original completed route stage'} +if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Immediate original route input CAS'} +Record 'run-attempt.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;once=$true;no_retry=$true} +$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$exe;$start.Arguments='probe '+$p.id;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true +$process=New-Object Diagnostics.Process;$process.StartInfo=$start;if(!$process.Start()){throw 'Own route probe start failed; read only'} +try{$held=$process.Handle;$birth=$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();Record 'process.json' @{id=$p.id;pid=$process.Id;birth=$birth;held_kernel_handle=$true;exe_sha256='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'} + $output=$process.StandardOutput.ReadToEndAsync();$errors=$process.StandardError.ReadToEndAsync();$timedOut=!$process.WaitForExit(20000) + if($timedOut){$process.Kill();if(!$process.WaitForExit(5000)){throw 'Own held route process exit uncertain'}} + if(!$output.Wait(5000)-or!$errors.Wait(5000)){throw 'Own route pipe drain uncertain'};$stdout=$output.Result;$stderr=$errors.Result + if($stdout.Length-gt32768-or$stderr.Length-gt32768){throw 'Bounded fixed route output'} + WriteNew (Join-Path $control 'stdout.txt') ([Text.Encoding]::UTF8.GetBytes($stdout));WriteNew (Join-Path $control 'stderr.txt') ([Text.Encoding]::UTF8.GetBytes($stderr)) + Record 'exit.json' @{id=$p.id;pid=$process.Id;birth=$birth;kernel_process_exited=$process.HasExited;exit_code=$process.ExitCode;timed_out=$timedOut} + if($timedOut-or$process.ExitCode-ne0-or$stderr.Length){throw 'Actual route probe did not complete successfully; original read only'} + ReadOwn|ConvertTo-Json -Depth 20 -Compress +}finally{$process.Dispose()} +''' + + +def guards(): + require(original.sha(ROOT/'deploy/windows/signed_clock_capture_acceptance.py')=='dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770','fixed prior witnesses') + require("$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')" in SCRIPT + and "if($p.action-cne'run'){throw 'Exact run required before process start'}" in SCRIPT,'no action case fallthrough') + require(all(v not in SCRIPT for v in ('Start-Service','Stop-Service','Restart-Service','Remove-Item','Invoke-Expression','Bypass','Snapshot','TimeBegin')),'own files/process only') + require(sha(QUAL/'receipt.json')==RECEIPT_SHA and sha(QUAL/'TimeRouteProbe.exe')==EXE_SHA + and (QUAL/'TimeRouteProbe.exe').stat().st_size==EXE_BYTES and sha(PIN)==PIN_SHA,'exact actual qualified artifacts and public time key') + + +def gate(): + require(isinstance(CONTEXT_GATE,dict) and set(CONTEXT_GATE)=={'id','receipt_sha256'},'ACTUAL_CONTEXT_GATE_NOT_BOUND') + ident=CONTEXT_GATE['id'];require(str(uuid.UUID(ident))==ident,'actual canonical context case') + folder=collector.STATE/ident;receipt=load(folder/'receipt.json') + require(sha(folder/'receipt.json')==CONTEXT_GATE['receipt_sha256'] and receipt['id']==ident + and receipt['collector_sha256']==sha(Path(collector.__file__)) and receipt['read_only'] is True + and sha(folder/'response.json')==receipt['response_sha256'] and sha(folder/'context.json')==receipt['context_sha256'], + 'original actual postdeploy read context only') + return ident,folder,receipt + + +def prepare(): + guards();ident,context,receipt=gate();STATE.mkdir(mode=0o700,parents=True,exist_ok=True);folder=STATE/ident;folder.mkdir(mode=0o700) + for name,path in [('TimeRouteProbe.exe',QUAL/'TimeRouteProbe.exe'),('time-public-key.json',PIN),('context.json',context/'context.json')]:original.write(folder/name,path.read_bytes()) + original.write(folder/'TimeRouteAcceptance.ps1',SCRIPT.encode()) + save(folder/'manifest.json',dict(id=ident,operator_sha256=sha(__file__),script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(), + fixture_receipt_sha256=RECEIPT_SHA,exe_sha256=EXE_SHA,pin_sha256=PIN_SHA,context_gate=CONTEXT_GATE, + context_sha256=sha(folder/'context.json'),context_response_sha256=receipt['response_sha256'],dependencies=original.dependencies())) + print(json.dumps(dict(id=ident,prepared_locally=True))) + + +def case(ident): + require(str(uuid.UUID(ident))==ident,'original case only');folder=STATE/ident;manifest=load(folder/'manifest.json') + require(manifest['id']==ident and manifest['operator_sha256']==sha(__file__) + and manifest['script_sha256']==hashlib.sha256(SCRIPT.encode()).hexdigest() + and manifest['dependencies']==original.dependencies() and sha(folder/'TimeRouteProbe.exe')==EXE_SHA + and sha(folder/'context.json')==manifest['context_sha256'] and sha(folder/'time-public-key.json')==PIN_SHA,'exact original prepared case') + return folder,manifest + + +def stage_exe(access,folder): + name='TimeRouteProbe.exe';prepare=original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name) + observed=access.powershell(prepare,dict(sha256=EXE_SHA)) + if not observed['already_uploaded']: + credentials=original.pipe.cb.contract.protected_json(access.root/'credentials/windows-dev-access.json');prefix=credentials['ssh_prefix'] + argv=['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]] + target='/C:/ProgramData/RustDiscoveryBootstrap/'+EXE_SHA+'/'+name + result=subprocess.run(argv,input=('put '+json.dumps(str(folder/name))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60) + save(folder/('transfer-'+str(uuid.uuid4())+'.json'),dict(returncode=result.returncode,stdout_b64=base64.b64encode(result.stdout).decode(),stderr_b64=base64.b64encode(result.stderr).decode())) + require(result.returncode==0,'one exact route EXE transfer; lost reply read only') + observed=access.powershell(prepare,dict(sha256=EXE_SHA));require(observed['already_uploaded'] is True and observed['sha256']==EXE_SHA,'actual immutable EXE stage') + + +def validate(response,manifest): + records=response['records'];require('report.json' in records and 'exit.json' in records,'actual report and kernel exit required') + report=json.loads(base64.b64decode(records['report.json'],validate=True));exited=json.loads(base64.b64decode(records['exit.json'],validate=True)) + require(exited['kernel_process_exited'] is True and exited['exit_code']==0 and exited['timed_out'] is False + and report['context_sha256']==manifest['context_sha256'] and report['server_context_evidence_sha256']==manifest['context_response_sha256'] + and report['verified'] is True and report['case_id']==response['id'] and report['public_time_pin_sha256']==PIN_SHA + and [v['http_status'] for v in report['reports']]==[200,403,409] + and report['reports'][0]['signature_verified'] is True and report['reports'][0]['whole_request_context_bound'] is True + and all(report[key] is False for key in ('private_key_exported','private_key_hashed','private_key_copied_to_evidence', + 'certificate_verification_disabled','service_role_proven','trusted_clock_proven','clock_freshness_qualified','sync_ready','jobs_created','grants_created')), + 'actual passive signature/context route only, no role/clock/job claim') + + +def run(action,ident): + guards();folder,manifest=case(ident);access=original.CaptureAccess(original.ACCESS_ROOT) + operation='read-'+str(uuid.uuid4()) if action=='read' else action + require(action in ('stage','run','read'),'fixed local action') + if action=='run': + stage=load(folder/'stage-reply.json');proof=load(folder/'stage-preservation.json') + require(stage.get('staged') is True and stage['id']==ident and stage['manifest_sha256']==sha(folder/'manifest.json') + and proof['id']==ident and proof['operation_id']=='stage' and proof['action']=='stage' and proof['read_only'] is False + and proof['operator_sha256']==sha(__file__) and proof['manifest_sha256']==sha(folder/'manifest.json') + and proof['raw_reply']==dict(filename='stage-reply.json',sha256=sha(folder/'stage-reply.json')),'original complete linked stage before the single run') + for name in ('server','native'): + link=proof[name+'_witness'];require(link['filename']=='stage-'+name+'.json' and sha(folder/link['filename'])==link['sha256'],'original stage witness links') + if action!='read': + gate_id,context,receipt=gate();require(gate_id==ident and manifest['context_gate']==CONTEXT_GATE,'actual original sealed context gate') + fresh=collector.rpc(access,dict(id=ident,deployment_result_sha256=receipt['deployment_result_sha256'],image=collector.IMAGE),folder) + require(fresh==load(context/'response.json'),'actual current DB boot/generation/gateway still exact before action') + save(folder/(operation+'-attempt.json'),dict(action=action,once=True,no_retry=True,operator_sha256=sha(__file__))) + else:save(folder/(operation+'-intent.json'),dict(action='read',read_only=True,operator_sha256=sha(__file__))) + before_server,before_native=original.server_closed(access),original.native_witness(access) + baseline=folder/'baseline.json' + if not baseline.exists():save(baseline,dict(server=before_server,native=before_native)) + original.preserved(load(baseline)['native'],before_native);require(load(baseline)['server']==before_server,'same original closed server scope') + if action=='stage':stage_exe(access,folder) + payload=dict(action=action,id=ident,manifest_sha256=sha(folder/'manifest.json'),context_sha256=manifest['context_sha256'], + context_base64=base64.b64encode((folder/'context.json').read_bytes()).decode(),pin_base64=base64.b64encode((folder/'time-public-key.json').read_bytes()).decode()) + response=access.powershell(SCRIPT,payload,timeout=90) + raw=folder/(operation+'-reply.json');save(raw,response) # raw first, before outcome/witness assertions + after_server,after_native=original.server_closed(access),original.native_witness(access) + require(before_server==after_server,'closed server gates and counters preserved');original.preserved(before_native,after_native) + binding=dict(id=ident,operation_id=operation,action=action,read_only=action=='read',operator_sha256=sha(__file__), + raw_reply=dict(filename=raw.name,sha256=sha(raw)),manifest_sha256=sha(folder/'manifest.json')) + server=folder/(operation+'-server.json');native=folder/(operation+'-native.json') + save(server,dict(binding,before=before_server,after=after_server));save(native,dict(binding,before=before_native,after=after_native)) + save(folder/(operation+'-preservation.json'),dict(binding,server_witness=dict(filename=server.name,sha256=sha(server)), + native_witness=dict(filename=native.name,sha256=sha(native)),no_rmm_jobs=True,no_service_action=True)) + require(response['id']==ident and response['manifest_sha256']==sha(folder/'manifest.json'),'same original route case response') + if action=='stage':require(response['staged'] is True,'actual complete stage') + elif action=='run' or 'report.json' in response.get('records',{}):validate(response,manifest) + print(json.dumps(dict(id=ident,action=action,preserved=True,completed='report.json' in response.get('records',{}),read_only=action=='read'))) + + +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('guards','prepare','stage','run','read'));p.add_argument('--case');a=p.parse_args() + if a.action=='guards':guards();print('PASS source guards; no target call') + elif a.action=='prepare':require(a.case is None,'actual sealed context determines own case');prepare() + else:require(a.case is not None,'original case required');run(a.action,a.case) diff --git a/deploy/windows/time_route_context.py b/deploy/windows/time_route_context.py new file mode 100644 index 0000000..05e6e45 --- /dev/null +++ b/deploy/windows/time_route_context.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""One fixed post-deployment public context read. No SQL/HTTP writes or secrets.""" +import argparse +import base64 +import hashlib +import inspect +import json +import re +from pathlib import Path +import subprocess +import uuid +import signed_clock_capture_acceptance as original + +ROOT=original.ROOT +STATE=ROOT/'devstate/windows-time-route-context' +# Root binds the actual successful deployment result SHA after its separate read. +DEPLOYMENT_RESULT_SHA=None +DEPLOYMENT_PATH='/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/result.json' +IMAGE='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611' +BINDING_SHA='05c5678fed81e0a2a7cdaaeaf18c64f9837cfbe76c140699a47306c9b4598a18' +require,save,load,sha=original.require,original.save,original.load,original.sha + + +def server_read(p): + import hashlib,json,os,stat,subprocess,uuid + from pathlib import Path + def need(v): + if not v:raise RuntimeError('FIXED_READONLY_CONTEXT_INCOMPLETE') + need(set(p)=={'id','deployment_result_sha256','image'}) + need(str(uuid.UUID(p['id']))==p['id'] and isinstance(p['deployment_result_sha256'],str) and len(p['deployment_result_sha256'])==64 + and all(v in '0123456789abcdef' for v in p['deployment_result_sha256']) + and p['image']=='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611') + path=Path('/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/result.json') + metadata=path.lstat();need(stat.S_ISREG(metadata.st_mode) and metadata.st_uid==0 and metadata.st_nlink==1 + and stat.S_IMODE(metadata.st_mode)==0o600 and metadata.st_size<=65536) + def identity(m):return(m.st_dev,m.st_ino,m.st_mode,m.st_uid,m.st_gid,m.st_nlink,m.st_size,m.st_mtime_ns,m.st_ctime_ns) + raw=path.read_bytes();need(identity(path.lstat())==identity(metadata) and hashlib.sha256(raw).hexdigest()==p['deployment_result_sha256']) + deployed=json.loads(raw);need(deployed['deployed'] is True and deployed['rmm_jobs_created'] is False + and deployed['approvals_created'] is False and deployed['gateway_only_readonly_broker_mount'] is True) + def command(args,data=None): + r=subprocess.run(args,input=data,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=10) + need(r.returncode==0 and len(r.stdout)<=65536 and len(r.stderr)<=65536);return r.stdout + def gateway(): + value=json.loads(command(['docker','inspect','rust-discovery-server-gateway-1','--format', + '[{{json .Id}},{{json .Image}},{{json .Config.User}},{{json .State.Running}},{{json .HostConfig.PidMode}}]'])) + need(value[1]==p['image'] and value[2]=='10001:10001' and value[3] is True and value[4]!='host');return value + boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip();need(str(uuid.UUID(boot))==boot) + before=gateway() + query=("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL statement_timeout='3s'; " + "SELECT json_build_object('tenant_id',tenant_id,'agent_id',agent_id,'asset_id',asset_id," + "'enrollment_generation',enrollment_generation,'assignment_generation',assignment_version," + "'connection_generation',connection_generation,'windows_boot_id',connection_boot_id,'capabilities',capabilities) " + "FROM agent_installations WHERE tenant_id='11111111-1111-4111-8111-111111111111' " + "AND agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3' AND revoked_at IS NULL; COMMIT;") + raw=command(['docker','exec','-i','rust-discovery-server-postgres-1','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],query.encode()) + row=json.loads(raw) + need(row['tenant_id']=='11111111-1111-4111-8111-111111111111' and row['agent_id']=='63ea15b2-0643-403d-b5b4-cba1288dbea3' + and row['asset_id']=='a176520e-8a91-4e93-a78b-8e7620f430e0' and row['enrollment_generation']==1 + and row['assignment_generation']==1 and type(row['connection_generation']) is int and row['connection_generation']>1 + and str(uuid.UUID(row['windows_boot_id']))==row['windows_boot_id'] and 'windows.base/1' in row['capabilities']) + need(before==gateway() and Path('/proc/sys/kernel/random/boot_id').read_text().strip()==boot) + return dict(profile='rmm.windows.time-route.actual-public-context.v1',id=p['id'],server_boot_id=boot, + installation=row,gateway=before,deployment_result_sha256=p['deployment_result_sha256'],sql_read_only=True,secrets_read=False) + + +def rpc(access,payload,folder): + # Same strict Main SSH configuration parser as CaptureAccess.server; never source/eval. + cloud=original.pipe.u.transport.cloud + cfg=cloud.bootstrap.access.load_config(access.root/'credentials/server.conf') + prefix=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes', + '-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -'] + code=inspect.getsource(server_read)+'\nimport json\nprint(json.dumps(server_read('+repr(payload)+')))\n' + r=subprocess.run(prefix,input=code.encode(),capture_output=True,timeout=30) + save(folder/('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=r.returncode,stdout_b64=base64.b64encode(r.stdout).decode(),stderr_b64=base64.b64encode(r.stderr).decode())) + require(r.returncode==0 and len(r.stdout)<=65536,'bounded actual context transport; original read only') + return json.loads(r.stdout,object_pairs_hook=original.pipe.cb.contract.strict_object) + + +def collect(): + require(type(DEPLOYMENT_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}',DEPLOYMENT_RESULT_SHA) is not None,'ACTUAL_DEPLOYMENT_GATE_NOT_BOUND') + original.original_main();STATE.mkdir(mode=0o700,parents=True,exist_ok=True) + ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,deployment_result_sha256=DEPLOYMENT_RESULT_SHA,image=IMAGE) + save(folder/'intent.json',dict(id=ident,collector_sha256=sha(__file__),read_only=True,payload=payload)) + response=rpc(original.CaptureAccess(original.ACCESS_ROOT),payload,folder) + save(folder/'response.json',response) + require(response['id']==ident and response['sql_read_only'] is True and response['secrets_read'] is False,'actual original public context only') + context=dict(schema_version=1,case_id=ident,connection_generation=response['installation']['connection_generation'], + windows_boot_id=response['installation']['windows_boot_id'],server_boot_id=response['server_boot_id'], + server_context_evidence_sha256=sha(folder/'response.json'),binding_sha256=BINDING_SHA) + save(folder/'context.json',context) + save(folder/'receipt.json',dict(id=ident,collector_sha256=sha(__file__),deployment_result_sha256=DEPLOYMENT_RESULT_SHA, + response_sha256=sha(folder/'response.json'),context_sha256=sha(folder/'context.json'),gateway=response['gateway'],read_only=True)) + print(json.dumps(dict(id=ident,read_only=True,receipt_sha256=sha(folder/'receipt.json'),context_sha256=sha(folder/'context.json')))) + + +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('collect','guards'));a=parser.parse_args() + if a.action=='collect':collect() + else: + require('READ ONLY' in inspect.getsource(server_read) and 'UPDATE ' not in inspect.getsource(server_read),'fixed SQL read only') + print('PASS source guards; no target action') diff --git a/docs/windows-time-route-fixture.md b/docs/windows-time-route-fixture.md new file mode 100644 index 0000000..0077322 --- /dev/null +++ b/docs/windows-time-route-fixture.md @@ -0,0 +1,43 @@ +# Windows: fester passiver mTLS-Zeitrouteprobe + +Stand2026-11-15: Quelle und lokaler Windows-Cross-Link fertig, **noch keine native Ausführung**. Dieser enge Fixture dient als HTTP-/Broker-Endpunktnachweis vor dem erhaltenden passiven Paarupgrade. Er ist kein installierter Dienstrollen-, Trusted-Clock-, SignedSync-/Ready- oder Jobnachweis. + +`crates/agent-windows/examples/time_route_probe.rs` verwendet ausschließlich die bestehende Geräteidentität der Windows-VM. Gerätecert/-key bleiben in den festen vorhandenen Statepfaden und werden nur intern für den gemeinsamen `https_channel::mtls_client` gelesen. Private Keybytes werden weder ausgegeben noch gehasht oder in Evidence kopiert; der zusätzliche rohe Zwischenbuffer wird nach Clientbau gelöscht. Es gibt kein PFX, Enrollment, neues Gerät, frei wählbares Netzwerkziel, Shellkommando oder Zertifikats-/Namensprüfungs-Bypass. Domain/SAN/SNI, Projekt-CA, TCP-Ziel88.99.80.202:443 und `/agent/v1/time-attestation` bleiben fest. Der Pool wird für die drei Aufrufe wiederverwendet. + +Der Fixture läuft nur als tatsächlich berechtigter Bootstrapadministrator ohne Threadimpersonation. Er behauptet ausdrücklich keine LocalService-/SYSTEM-Ausführung. Eigener fester Fallpfad: `C:\ProgramData\RustDiscoveryBootstrap\time-route\`, darin vor Start genau `TimeRouteProbe.exe`, `context.json`, `time-public-key.json`. Die beiden Kontrollpfade müssen Root-/Administrators-/SYSTEM-geschützt sein. Der tatsächliche EXE-Pfad muss zum eigenen Fall passen; `intent.json` wird create-only **vor** dem ersten Netzwerkaufruf geschrieben. Nach verlorenem Ergebnis werden ausschließlich Originaldateien gelesen, nicht derselbe Lauf wiederholt. + +Die bestehende passive Agentkonfiguration und der bisherige öffentliche Peerpin sind fest an ihre Originalhashes aus14fb gebunden. Die Geräte-/Tenant-/Enrollment-/Assignment-/Jobpublickeybindung stammt aus diesem geschützten Peerpin; Agent-/Asset-ID sind fest. Deshalb ist dieser Fixture absichtlich für den Stand **vor** dem Paarupgrade vorgesehen. Ein später geänderter Peerpin wird nicht still adaptiert. Der echte separate öffentliche Zeitpin ist SHA256 `c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2`, unabhängig vom konkreten Jobkey geprüft. Private Signierdateien wurden nicht gelesen. + +## Feste Protokollfälle und begrenzte Aussage + +Je Aufruf wird eine neue eigene256-Bit-CSPRNG-Nonce verwendet, mit eigener zufälliger Prozessinkarnation und dem fest gebundenen Kontext. Positive Antwort: HTTP200, exakte kanonische Codec-/Signaturbytes, strikte Ed25519-Prüfung mit dem echten öffentlichen Zeitkey, kompletter Originalrequesthash einschließlich Nonce/Context, Serverinstanz/-boot, Key-ID/-generation und begrenzte signierte Qualitätsfelder. Verwendet wird der vorhandene `DalekVerifier`; kein neuer Algorithmus und keine vorgetäuschte `Sample`-/Calibration-/Clockkonstruktion. + +Die beiden weiteren festen Fälle verändern ausschließlich den Tenant zur bekannten anderen Test-Tenant-ID (erwartet403) beziehungsweise die zuvor von Root gelesene aktuelle Connectiongeneration auf deren Vorgänger (erwartet409). Kein Helperrequest, Job-, Grant-, UI-, MCP-, Sync-/Enrollment- oder TimeSetterpfad. Jede Antwort ist begrenzt; drei feste Requests, jeweils höchstens3s. Diese Transporttimeoutgrenze ist **keine** behauptete1s-/100ms-Clockqualifikation. Clock-/Dienstrollen-/SyncReady-Nachweis bleibt ausdrücklich false. + +Nur öffentliche Requests/Signaturantworten, Status-/Hashmetadaten und feste Scopefelder gelangen in den eigenen create-only Fall. Statische „keine Jobs/Grants“-Scopefelder ersetzen keinen unabhängigen tatsächlichen Serverzählersnapshot. Root muss vor/nach dieselben geschlossenen Windows-/Linux-/Policy-/Grantzähler und erhaltene PKI-/DB-/Lockidentitäten separat vergleichen. Erst dieser gekoppelte Beleg darf den Endpunkt als tatsächlich passiv abgenommen ausweisen. + +## Noch fehlende echte Kontextdatei + +Es wurde **keine** `context.json` mit Dummywerten erzeugt. Root liefert nach Gatewaydeployment den tatsächlichen frischen DB-/Bootbeleg; Deployment kann die Verbindungsgeneration ändern. Die enge Datei hat ausschließlich folgende Pflichtfelder: + +| Feld | Bedeutung | +| --- | --- | +| `schema_version` | exakt1 | +| `case_id` | exakte eigene kanonische Fall-UUID | +| `connection_generation` | tatsächlich aktuell aus der Server-DB, größer1 | +| `windows_boot_id` | tatsächliche aktuelle DB-`connection_boot_id` | +| `server_boot_id` | tatsächliche aktuelle permanente Serverboot-ID | +| `server_context_evidence_sha256` | unveränderlicher Root-Originalbeleg dieser frischen Abfrage | +| `binding_sha256` | SHA256 der vorhandenen typisiert serialisierten öffentlichen Gerätebindung | + +Der spätere feste Root-Operator muss Originalbeleg und frisch gerenderte Datei sowie tatsächliches Gateway-/Brokerdeployment vor Ausführung prüfen. Eine beliebige Callerboolean genügt nicht. Der Probe selbst prüft Serverantwort und Kontextbindung; diese vorgelagerte Provenienz ist zusätzlich Root-verantwortet. Der einzelne geplante CLI-Aufruf lautet strukturell `TimeRouteProbe.exe probe `; hier **nicht ausgeführt**. + +## Tatsächlich lokal qualifiziert + +Unveränderlicher Fall `time-route-fixture-qualification-3fdf513e-197b-41ab-b161-9dfc2adc94da`, exakt203 öffentliche Compilerinputs: der erhaltene c467-Produktcheckpoint202 plus genau dieses neue Example. Aktueller fremder Updater-WIP wurde bewusst nicht in diesen Fixture übernommen; es gibt keine Behauptung,203 entspräche dem gesamten gegenwärtigen Workspace. Inputmanifest `1c4ed151efacc60bc3487356fcbdca0b665a02da9b7ceef7454d5eaa4f310d47`; Fixturequelle `808ef3a3fe21ca100fae38250c40c0738c3e4076c686c642776f0aa2bc891d9c`; Receipt `fce8c42cce33a35be1ee0468c97010ac3797a713668503783e449d30ea538678`. + +Rustfmt nur dieses Example (`skip_children`), Windows-Examplecheck, Clippy mit `-D warnings` und Release-Link PASS. Offline-Docker, Quellen nur lesbar, eigene private Targets, keine Credentials-Mounts. Keine zusätzlichen Tests oder VM-Abfragen ausgeführt; vorherige tatsächliche Linux-Codec-/Servernachweise werden separat durch Root gebunden, nicht durch diesen Cross-Build ersetzt. + +`TimeRouteProbe.exe`:19172660Bytes, AMD64-PE, SHA256 `4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088`, Modus0500/ein Hardlink. Enger Readonly-Capabilitymanifest-SHA256 `22ca87604e942b91e68981f694934bc8c933c5fb5ab5858f27a2d3884d64df42`. Der neue Produktpaarbeleg26dc/5967 und dessen Modulquelle d859 bleiben unverändert; dieses Example installiert oder startet keinen Agenten. + +Offen: unabhängiger Fixture-Review, echtes Gateway-/Brokerdeployment und dessen frische Kontextprovenienz, einmalige native Ausführung mit200/403/409, separater lesender Originalfallnachweis und tatsächliche Erhaltungs-/Nulljobwitnesses. Erst danach ist dieser Endpunktgate für die nächste getrennte passive Paarwartung verfügbar. Windows-MVP-Wirkungsabnahmen bleiben offen. diff --git a/docs/windows-time-route-operator.md b/docs/windows-time-route-operator.md new file mode 100644 index 0000000..414cf7d --- /dev/null +++ b/docs/windows-time-route-operator.md @@ -0,0 +1,61 @@ +# Fester passiver Windows-Zeitroutennachweis + +Quellenstand 2026-11-15: `deploy/windows/time_route_context.py` liest ausschließlich +öffentliche aktuelle Installationsmetadaten nach dem getrennten Gatewaydeployment. +`deploy/windows/time_route_acceptance.py` bereitet die bereits gebaute feste +`TimeRouteProbe.exe` vor und besitzt ausschließlich die getrennten Phasen +`stage`, `run` und `read`. Keine Phase verändert RMM-Dienste, Geräteidentitäten, +Zeitdienst, Richtlinien oder Jobgenehmigungen. + +Der Collector bleibt mit `DEPLOYMENT_RESULT_SHA=None` geschlossen. Der Operator +bleibt mit `CONTEXT_GATE=None` geschlossen. Der Operator darf erst den tatsächlich +abgelesenen Collectorfall und dessen BelegSHA binden. Keine Beispielkontexte, +Dummykeys oder Kalibrierungszahlen ersetzen diese Daten. Vor Stage und Run wird +exakt derselbe aktuelle öffentliche Kontext erneut gelesen. Ein Generations-, +Boot- oder Gatewaywechsel verlangt eine gesonderte Bewertung; kein automatischer +Retry und keine Umdeutung eines alten Belegs. + +Die feste SQL-Transaktion ist `READ ONLY` und liest die aktive Windowsinstallation +mit Enrollment, Assignment, Verbindungsgeneration, Windows-Boot und Capabilities. +Zusätzlich werden tatsächlicher Serverboot und Gatewayimage/-identität vor/nach +verglichen. Weder SQL-Zugangsdaten noch Geräteschlüssel werden gelesen oder +exportiert. Auf Windows verwendet ausschließlich die geprüfte EXE den bestehenden +Geräte-mTLS-Schlüssel intern, wie in `windows-time-route-fixture.md` beschrieben. + +Die beiden Windows-Verzeichnisse für Nutzlast und Steuerbelege sind getrennt, +damit die EXE zu Beginn genau ihre drei festen Eingabedateien vorfindet. Alle +Steuerbelege entstehen neu; ein verlorener Run ist ausschließlich lesbar. Der +Controller hält sein gestartetes Prozessobjekt mit Kernelhandle, wartet auf das +tatsächliche Ende und begrenzt ausschließlich diesen eigenen Prozess bei Timeout. +Die tatsächliche positive Signatur-/Kontextantwort sowie HTTP 403 und 409 müssen +im unveränderten Bericht stehen. Die ursprünglichen sechs nativen Windowsfelder, +Journalidentität und geschlossenen Servergates werden vor/nach separat geprüft. +Diese Abnahme beweist Transport und kryptografische Kontextbindung, keine +Dienstrolle, Timerqualität, aktuelle Clockfreigabe oder Jobwirkung. + +Lokal tatsächlich ausgeführt: Pythoncompile, beide Quellguards, geschlossene +Deployment-/Kontextgates, exakte groß-/kleinschreibungssensitive Aktionsgrenze und +Prüfung gegen die PowerShell-Aliaskollision `H`. Alle bestanden. Originalfall +`a324c4e5-d1a9-495e-aba8-cb755a174e98` unter +`devstate/windows-time-route-source/`; ReceiptSHA +`de5fdf7f01b0d0a40c4c8def16eaf87efc8bce2696d35e2097c9e394d52510ad`. +Native PowerShell-AST, unabhängiger Quellenreview, tatsächliche Kontextablesung, +Stage, Run und anschließender eigener Read sind hier noch nicht ausgeführt. +Der Operator führt diese Schritte nicht automatisch aus. + +## Tatsächliche native lesende Vorbereitung + +Nach ausdrücklicher Rootdelegation wurde auf der vorhandenen Windows-VM die +PowerShell-5.1-Quelle ausschließlich im Speicher mit `Parser.ParseInput` geparst. +Tatsächlich: PowerShell5.1.26100.9818, null AST-Fehler, Controller nicht ausgeführt. +Keine Stage-/Route-/Dienstaktion. Davor und danach lief ausschließlich der bereits +angenommene originale14fb-`finish`-Leser mit seinen bestehenden passiven Journal- und +SYSTEM-State-Probes: alle sechs stabilen nativen Felder und Journalidentität +unverändert, Sequenz monoton. Diese Probes rufen keine Clock-/Snapshotoperation +auf; sie ersetzen keinen Zeitrollen- oder aktuellen Frischebeweis. + +Eigener unveränderlicher Fall +`devstate/windows-time-route-native-readonly/a6d61a92-b7f3-4a8d-9df0-569941ab7ccd`, +ReceiptSHA `44504007fa7d0379e608375181b926ff2a20ae248cfeb2fb51d127b858b3536d`. +ScriptSHA bleibt `4c88fdf36f22b0273baaa08bf522bfefbf8482b45317ef852c0e0a331a1fbef2`. +Deployment-/Kontextgates bleiben geschlossen, Stage und Route weiterhin offen.