//! 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); }