diff --git a/crates/agent-windows/src/signed_clock.rs b/crates/agent-windows/src/signed_clock.rs index d3e01d5..9c26fd2 100644 --- a/crates/agent-windows/src/signed_clock.rs +++ b/crates/agent-windows/src/signed_clock.rs @@ -28,6 +28,188 @@ fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32 Ok(time) } +/// Schema1 retains independent numeric platform calibration. Schema2 is an +/// explicit opt-in to the user-approved nominal OS/active-guest trust model. +/// Disjoint deny-unknown-fields records prevent even null mixed-mode fields. +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(untagged)] +pub enum Configuration { + Physical(PhysicalConfiguration), + TrustedOs(TrustedOsConfiguration), +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct PhysicalConfiguration { + pub schema_version: u32, + pub key_generation: u64, + pub server_instance: Uuid, + pub binding: rmm_agent_core::auth::Binding, + pub public_keys_hex: std::collections::BTreeMap, + pub calibrations: Vec, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct Calibration { + pub role: rmm_time_attestation::Role, + pub binary_sha256: String, + pub qualification_sha256: String, + pub base_error_ns: u64, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct TrustedOsConfiguration { + pub schema_version: u32, + pub key_generation: u64, + pub server_instance: Uuid, + pub binding: rmm_agent_core::auth::Binding, + pub public_keys_hex: std::collections::BTreeMap, + pub trusted_os_active_guest: TrustedOsActiveGuest, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct TrustedOsActiveGuest { + pub operating_assumption: ActiveGuestOperation, + pub platform: TrustedPlatform, + pub platform_provenance_sha256: String, + pub qualifications: Vec, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub enum ActiveGuestOperation { + #[serde(rename = "active_guest_no_pause_save_restore_snapshot_migration_host_suspend")] + NoPauseSaveRestoreSnapshotMigrationHostSuspend, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub enum TrustedPlatform { + #[serde(rename = "kvm_qemu_hypervclock")] + KvmQemuHypervClock, +} +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct RoleQualification { + pub role: rmm_time_attestation::Role, + pub binary_sha256: String, + pub qualification_sha256: String, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CaptureMode { + Physical { base_error_ns: u64 }, + TrustedOsActiveGuest, +} +fn digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} +impl Configuration { + #[cfg(all(windows, feature = "system-helper"))] + fn binding(&self) -> &rmm_agent_core::auth::Binding { + match self { + Self::Physical(value) => &value.binding, + Self::TrustedOs(value) => &value.binding, + } + } + fn key_generation(&self) -> u64 { + match self { + Self::Physical(value) => value.key_generation, + Self::TrustedOs(value) => value.key_generation, + } + } + #[cfg(all(windows, feature = "system-helper"))] + fn server_instance(&self) -> Uuid { + match self { + Self::Physical(value) => value.server_instance, + Self::TrustedOs(value) => value.server_instance, + } + } + #[cfg(all(windows, feature = "system-helper"))] + fn public_keys(&self) -> &std::collections::BTreeMap { + match self { + Self::Physical(value) => &value.public_keys_hex, + Self::TrustedOs(value) => &value.public_keys_hex, + } + } + fn capture_mode( + &self, + own_role: rmm_time_attestation::Role, + agent_image: &str, + helper_image: &str, + ) -> Result { + use rmm_time_attestation::Role; + ensure!(self.key_generation() > 0, "TIME_NATIVE_CONFIG_PROFILE"); + let images = [ + (Role::Agent, agent_image), + (Role::SystemHelper, helper_image), + ]; + match self { + Self::Physical(value) => { + ensure!( + value.schema_version == 1 && value.calibrations.len() == 2, + "TIME_NATIVE_CONFIG_PROFILE" + ); + let mut own = None; + for (role, image) in images { + let mut values = value.calibrations.iter().filter(|v| v.role == role); + let item = values + .next() + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CALIBRATION_MISSING"))?; + ensure!( + values.next().is_none() + && digest(&item.binary_sha256) + && digest(&item.qualification_sha256) + && item.base_error_ns > 0 + && item.base_error_ns <= MAX_BASE_ERROR_NS, + "TIME_NATIVE_CALIBRATION_PROFILE" + ); + ensure!(item.binary_sha256 == image, "TIME_NATIVE_CALIBRATION_IMAGE"); + if role == own_role { + own = Some(item.base_error_ns); + } + } + Ok(CaptureMode::Physical { + base_error_ns: own + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CALIBRATION_MISSING"))?, + }) + } + Self::TrustedOs(value) => { + let profile = &value.trusted_os_active_guest; + ensure!( + value.schema_version == 2 + && profile.qualifications.len() == 2 + && digest(&profile.platform_provenance_sha256), + "TIME_NATIVE_TRUSTED_PROFILE" + ); + // Both fields have exactly one accepted, explicit enum value. + // A JSON boolean, missing value or unknown variant cannot opt in. + ensure!( + matches!( + profile.operating_assumption, + ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend + ) && matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock), + "TIME_NATIVE_ACTIVE_GUEST_ASSUMPTION" + ); + for (role, image) in images { + let mut values = profile.qualifications.iter().filter(|v| v.role == role); + let item = values + .next() + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_QUALIFICATION_MISSING"))?; + ensure!( + values.next().is_none() + && digest(&item.binary_sha256) + && digest(&item.qualification_sha256), + "TIME_NATIVE_QUALIFICATION_PROFILE" + ); + ensure!( + item.binary_sha256 == image, + "TIME_NATIVE_QUALIFICATION_IMAGE" + ); + } + Ok(CaptureMode::TrustedOsActiveGuest) + } + } + } +} + #[derive(Default)] struct Continuity { boot_id: Option, @@ -75,6 +257,24 @@ impl Continuity { ensure!(valid, "TIME_NATIVE_DISCONTINUITY_OR_BOOT"); Ok(()) } + fn observe_configuration_raw(&mut self, sha256: &str) -> Result<()> { + ensure!(!self.exhausted, "TIME_NATIVE_CONFIGURATION_EXHAUSTED"); + if self + .configuration + .as_ref() + .is_some_and(|(_, old)| old != sha256) + { + // Observe before decoding: malformed or mixed-profile bytes must + // invalidate old evidence too. Do not adopt a new hash or floor. + self.invalidate(); + } + Ok(()) + } + fn configuration_failure(&mut self) { + if self.configuration.is_some() { + self.invalidate(); + } + } fn accept_configuration(&mut self, generation: u64, sha256: &str) -> Result<()> { ensure!( generation > 0 && !self.exhausted, @@ -144,31 +344,54 @@ impl Continuity { } } -/// All three native clocks are read in one bracket. The qualified base error -/// is a protected installation input, never inferred from 100ns resolution. +// Called only after the installed loader's protected, bounded read. Keeping +// raw observation ahead of serde/profile validation also covers invalid V2. +fn load_configuration( + state: &mut Continuity, + raw: &[u8], + role: rmm_time_attestation::Role, + agent_image: &str, + helper_image: &str, +) -> Result<(Configuration, CaptureMode)> { + state.observe_configuration_raw(&rmm_domain::jobs::hash(raw))?; + let config: Configuration = serde_json::from_slice(raw)?; + let mode = config.capture_mode(role, agent_image, helper_image)?; + Ok((config, mode)) +} + +/// All three native clocks are read in one bracket. The protected mode chooses +/// either actual numeric calibration or the explicit nominal OS trust profile. +/// Neither a 100ns representation nor a bracket claims physical accuracy. fn bracket_sample( wall_filetime: u64, interrupt_before: u64, interrupt_after: u64, unbiased_before: u64, unbiased_after: u64, - base_error_ns: u64, + mode: CaptureMode, ) -> Result { const FILETIME_UNIX: u64 = 116_444_736_000_000_000; - ensure!( - base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS, - "TIME_NATIVE_CALIBRATION_REQUIRED" - ); - let width = raw_widths( + let (width, unbiased_width) = raw_widths( interrupt_before, interrupt_after, unbiased_before, unbiased_after, - )? - .0; - let capture_error_ns = width - .checked_add(base_error_ns) - .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?; + )?; + let capture_error_ns = match mode { + CaptureMode::Physical { base_error_ns } => { + ensure!( + base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS, + "TIME_NATIVE_CALIBRATION_REQUIRED" + ); + width + .checked_add(base_error_ns) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))? + } + // This is a software bracket in trusted nominal OS units, not a + // physical accuracy bound. Checked multiplication by100 is exact, so + // there is no conversion rounding remainder or invented base constant. + CaptureMode::TrustedOsActiveGuest => width.max(unbiased_width), + }; ensure!( capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS, "TIME_NATIVE_CAPTURE_BUDGET" @@ -404,13 +627,11 @@ mod installed { use super::*; use crate::helper_ipc::{self as ipc, PeerProof, PinnedFile}; use anyhow::Context as _; - use rmm_agent_core::auth::Binding; use rmm_domain::jobs::hash; use rmm_time_attestation::{ Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, VerifiedEvidence, Verifier, }; - use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, io::Read, @@ -423,47 +644,36 @@ mod installed { const MAX_CONFIG_BYTES: usize = 16_384; const MAX_REPLY_BYTES: usize = 16_384; - /// Provision only after an independent qualification of these actual - /// native APIs/platform/image. A file field is not a measured accuracy. - #[derive(Debug, Deserialize, Serialize)] - #[serde(deny_unknown_fields)] - pub struct Calibration { - pub role: Role, - pub binary_sha256: String, - pub qualification_sha256: String, - pub base_error_ns: u64, - } - #[derive(Debug, Deserialize, Serialize)] - #[serde(deny_unknown_fields)] - pub struct Configuration { - pub schema_version: u32, - pub key_generation: u64, - pub server_instance: Uuid, - pub binding: Binding, - pub public_keys_hex: BTreeMap, - pub calibrations: Vec, - } - fn digest(value: &str) -> bool { - value.len() == 64 - && value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) - } static PROCESS: OnceLock> = OnceLock::new(); static INCARNATION: OnceLock = OnceLock::new(); fn process() -> &'static Mutex { PROCESS.get_or_init(|| Mutex::new(Continuity::default())) } - fn capture(base_error_ns: u64) -> Result { + // Any constructor failure/cancellation with a known configuration head + // closes process-global authority, including failures before raw bytes can + // be read. Successful same-config constructors do not rotate the epoch. + struct ConstructorFailureFence { + armed: bool, + } + impl Drop for ConstructorFailureFence { + fn drop(&mut self) { + if self.armed + && let Ok(mut state) = process().lock() + { + state.configuration_failure(); + } + } + } + fn capture(mode: CaptureMode) -> Result { let raw = raw_capture()?; - bracket_sample(raw.wall, raw.ib, raw.ia, raw.ub, raw.ua, base_error_ns) + bracket_sample(raw.wall, raw.ib, raw.ia, raw.ub, raw.ua, mode) } - fn observed(boot: Uuid, base_error_ns: u64) -> Result<(Sample, u64)> { + fn observed(boot: Uuid, mode: CaptureMode) -> Result<(Sample, u64)> { let mut state = process() .lock() .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; - let value = match capture(base_error_ns) { + let value = match capture(mode) { Ok(value) => value, Err(error) => { state.invalidate(); @@ -492,7 +702,7 @@ mod installed { config_sha256: String, boot_id: Uuid, connection_generation: u64, - base_error_ns: u64, + capture_mode: CaptureMode, pending: Option, latest: Option, } @@ -501,6 +711,7 @@ mod installed { /// signed server response. It is never itself a ready/sync flag. pub async fn open(role: Role, connection_generation: u64) -> Result { ensure!(connection_generation > 0, "TIME_NATIVE_CONNECTION"); + let mut failure_fence = ConstructorFailureFence { armed: true }; let (settings, mut files) = crate::helper_system::read_settings()?; let own_pin = match role { Role::Agent => &settings.agent, @@ -535,50 +746,25 @@ mod installed { .take(MAX_CONFIG_BYTES as u64 + 1) .read_to_end(&mut raw)?; ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE"); - let config: Configuration = serde_json::from_slice(&raw)?; + let (config, capture_mode) = { + let mut state = process() + .lock() + .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; + load_configuration( + &mut state, + &raw, + role, + &settings.agent.binary_sha256, + &settings.helper.binary_sha256, + )? + }; ensure!( - config.schema_version == 1 - && config.key_generation > 0 - && config.calibrations.len() == 2, - "TIME_NATIVE_CONFIG_PROFILE" - ); - ensure!( - hash(&serde_json::to_vec(&config.binding)?) + hash(&serde_json::to_vec(config.binding())?) == hash(&serde_json::to_vec(&settings.binding)?), "TIME_NATIVE_DEVICE_BINDING" ); - for expected in [Role::Agent, Role::SystemHelper] { - let mut values = config - .calibrations - .iter() - .filter(|value| value.role == expected); - let value = values.next().context("TIME_NATIVE_CALIBRATION_MISSING")?; - ensure!( - values.next().is_none() - && digest(&value.binary_sha256) - && digest(&value.qualification_sha256) - && value.base_error_ns > 0 - && value.base_error_ns <= MAX_BASE_ERROR_NS, - "TIME_NATIVE_CALIBRATION_PROFILE" - ); - let pin = if expected == Role::Agent { - &settings.agent - } else { - &settings.helper - }; - ensure!( - value.binary_sha256 == pin.binary_sha256, - "TIME_NATIVE_CALIBRATION_IMAGE" - ); - } - let base_error_ns = config - .calibrations - .iter() - .find(|value| value.role == role) - .context("TIME_NATIVE_CALIBRATION_MISSING")? - .base_error_ns; let keys = config - .public_keys_hex + .public_keys() .iter() .map(|(id, key)| { ensure!(digest(key), "TIME_NATIVE_PUBLIC_KEY"); @@ -586,11 +772,11 @@ mod installed { Ok((id.clone(), raw)) }) .collect::>>()?; - let pins = Pins::new(config.key_generation, config.server_instance, keys)?; + let pins = Pins::new(config.key_generation(), config.server_instance(), keys)?; process() .lock() .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))? - .accept_configuration(config.key_generation, &hash(&raw))?; + .accept_configuration(config.key_generation(), &hash(&raw))?; // The existing fixed read-only native getter is independent in // each process. It finishes BEFORE challenge/RTT timing begins. @@ -617,7 +803,7 @@ mod installed { config_sha256: hash(&raw), boot_id, connection_generation, - base_error_ns, + capture_mode, pending: None, latest: None, }; @@ -626,7 +812,8 @@ mod installed { .lock() .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))? .accept_connection(connection_generation)?; - observed(boot_id, base_error_ns)?; + observed(boot_id, capture_mode)?; + failure_fence.armed = false; Ok(value) } fn recheck(&mut self) -> Result<()> { @@ -670,7 +857,7 @@ mod installed { .lock() .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; state.require_connection(connection_generation)?; - let sample = match capture(self.base_error_ns) { + let sample = match capture(self.capture_mode) { Ok(value) => value, Err(error) => { state.invalidate(); @@ -705,7 +892,7 @@ mod installed { ) -> Result { let pending = self.pending.take().context("TIME_NATIVE_NO_CHALLENGE")?; let result = (|| { - let (received, epoch) = observed(self.boot_id, self.base_error_ns)?; + let (received, epoch) = observed(self.boot_id, self.capture_mode)?; ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED"); ensure!(bytes.len() <= MAX_REPLY_BYTES, "TIME_NATIVE_REPLY_SIZE"); let signed: SignedAttestation = serde_json::from_slice(bytes)?; @@ -714,7 +901,7 @@ mod installed { let (evidence, interval) = self.verifier .finish_evidence(pending.challenge, &signed, received, || { - let (sample, epoch) = observed(self.boot_id, self.base_error_ns)?; + let (sample, epoch) = observed(self.boot_id, self.capture_mode)?; ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED"); checked = Some(sample); Ok(sample) @@ -762,7 +949,7 @@ mod installed { .epoch; let checked = (|| { self.recheck()?; - let (sample, current_epoch) = observed(self.boot_id, self.base_error_ns)?; + let (sample, current_epoch) = observed(self.boot_id, self.capture_mode)?; ensure!(epoch == current_epoch, "TIME_NATIVE_EVIDENCE_INVALIDATED"); let state = process() .lock() @@ -945,9 +1132,7 @@ mod installed { } } #[cfg(all(windows, feature = "system-helper"))] -pub use installed::{ - BoundClock, CONFIG_PATH, Calibration, Comparison, Configuration, RuntimeClock, SignedClock, -}; +pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock}; #[cfg(test)] mod tests { @@ -1031,13 +1216,256 @@ mod tests { #[test] fn bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters() { let wall = 116_444_736_000_000_000 + 18_000_000_000_000_000; - let result = bracket_sample(wall, 100, 120, 90, 110, 1_000_000).unwrap(); + let result = bracket_sample( + wall, + 100, + 120, + 90, + 110, + CaptureMode::Physical { + base_error_ns: 1_000_000, + }, + ) + .unwrap(); assert_eq!(result.wall_utc_ns, 1_800_000_000_000_000_000); assert_eq!(result.capture_error_ns, 1_002_000); - assert!(bracket_sample(wall, 100, 99, 90, 110, 1_000_000).is_err()); - assert!(bracket_sample(wall, 100, 120, 90, 89, 1_000_000).is_err()); - assert!(bracket_sample(wall, 100, 120, 90, 110, 0).is_err()); - assert!(bracket_sample(wall, 0, 500_000, 0, 500_000, 1_000_000).is_err()); + assert!( + bracket_sample( + wall, + 100, + 99, + 90, + 110, + CaptureMode::Physical { + base_error_ns: 1_000_000 + } + ) + .is_err() + ); + assert!( + bracket_sample( + wall, + 100, + 120, + 90, + 89, + CaptureMode::Physical { + base_error_ns: 1_000_000 + } + ) + .is_err() + ); + assert!( + bracket_sample( + wall, + 100, + 120, + 90, + 110, + CaptureMode::Physical { base_error_ns: 0 } + ) + .is_err() + ); + assert!( + bracket_sample( + wall, + 0, + 500_000, + 0, + 500_000, + CaptureMode::Physical { + base_error_ns: 1_000_000 + } + ) + .is_err() + ); + } + #[test] + fn trusted_profile_requires_explicit_disjoint_schema_and_both_role_images() { + use rmm_time_attestation::Role; + let agent = "ab".repeat(32); + let helper = "cd".repeat(32); + let profile = serde_json::json!({ + "operating_assumption": "active_guest_no_pause_save_restore_snapshot_migration_host_suspend", + "platform": "kvm_qemu_hypervclock", + "platform_provenance_sha256": "ef".repeat(32), + "qualifications": [ + {"role":"agent", "binary_sha256": agent, "qualification_sha256": "12".repeat(32)}, + {"role":"system_helper", "binary_sha256": helper, "qualification_sha256": "34".repeat(32)} + ] + }); + let config = serde_json::json!({ + "schema_version": 2, "key_generation": 3, "server_instance": Uuid::new_v4(), + "binding": {"tenant_id":Uuid::new_v4(), "asset_id":Uuid::new_v4(), "agent_id":Uuid::new_v4(), + "enrollment_generation":1, "assignment_version":1, "public_key_hex":"56".repeat(32)}, + "public_keys_hex": {"time1":"78".repeat(32)}, + "trusted_os_active_guest": profile + }); + let mode = |value: serde_json::Value| -> Result { + serde_json::from_value::(value)?.capture_mode( + Role::Agent, + &agent, + &helper, + ) + }; + assert_eq!( + mode(config.clone()).unwrap(), + CaptureMode::TrustedOsActiveGuest + ); + for mutation in 0..12 { + let mut bad = config.clone(); + match mutation { + 0 => bad["schema_version"] = 1.into(), + 1 => bad["schema_version"] = 3.into(), + 2 => { + bad.as_object_mut() + .unwrap() + .remove("trusted_os_active_guest"); + } + 3 => bad["calibrations"] = serde_json::json!([]), + 4 => bad["calibrations"] = serde_json::Value::Null, + 5 => bad["trusted_os_active_guest"]["operating_assumption"] = "automatic".into(), + 6 => { + bad["trusted_os_active_guest"] + .as_object_mut() + .unwrap() + .remove("platform_provenance_sha256"); + } + 7 => bad["trusted_os_active_guest"]["platform"] = "any_vm".into(), + 8 => { + bad["trusted_os_active_guest"]["qualifications"][1]["binary_sha256"] = + agent.clone().into() + } + 9 => bad["trusted_os_active_guest"]["qualifications"][1]["role"] = "agent".into(), + 10 => { + bad["trusted_os_active_guest"]["qualifications"][1]["qualification_sha256"] = + "".into() + } + _ => { + bad["trusted_os_active_guest"]["qualifications"][0]["base_error_ns"] = 1.into() + } + } + assert!(mode(bad).is_err(), "mutation {mutation}"); + } + // Old configurations keep their positive numeric contract; neither a + // version flip nor a null/mixed profile silently changes that mode. + let mut physical = config.clone(); + physical + .as_object_mut() + .unwrap() + .remove("trusted_os_active_guest"); + physical["schema_version"] = 1.into(); + physical["calibrations"] = serde_json::json!([ + {"role":"agent", "binary_sha256":agent, "qualification_sha256":"12".repeat(32), "base_error_ns":1_000_000}, + {"role":"system_helper", "binary_sha256":helper, "qualification_sha256":"34".repeat(32), "base_error_ns":2_000_000} + ]); + assert_eq!( + mode(physical.clone()).unwrap(), + CaptureMode::Physical { + base_error_ns: 1_000_000 + } + ); + let mut bad = physical.clone(); + bad["trusted_os_active_guest"] = serde_json::Value::Null; + assert!(mode(bad).is_err()); + let mut bad = physical.clone(); + bad["schema_version"] = 2.into(); + assert!(mode(bad).is_err()); + physical["calibrations"][0]["base_error_ns"] = 0.into(); + assert!(mode(physical).is_err()); + } + #[test] + fn trusted_os_capture_uses_both_full_brackets_and_exact_integer_units() { + let wall = 116_444_736_000_000_000 + 18_000_000_000_000_000; + let trusted = CaptureMode::TrustedOsActiveGuest; + let sample = bracket_sample(wall, 100, 120, 90, 130, trusted).unwrap(); + assert_eq!(sample.capture_error_ns, 4_000); + assert_eq!(sample.wall_utc_ns, 1_800_000_000_000_000_000); + assert_eq!(sample.interrupt_ns, 12_000); + assert_eq!(sample.unbiased_ns, 13_000); + let physical = bracket_sample( + wall, + 100, + 120, + 90, + 130, + CaptureMode::Physical { + base_error_ns: 1_000_000, + }, + ) + .unwrap(); + assert_eq!(physical.capture_error_ns, 1_002_000); + // Exact OS-domain conversions add no guessed positive base constant. + assert_eq!( + bracket_sample(wall, 100, 100, 90, 90, trusted) + .unwrap() + .capture_error_ns, + 0 + ); + assert_eq!( + bracket_sample(wall, 1, 500_001, 1, 500_001, trusted) + .unwrap() + .capture_error_ns, + rmm_time_attestation::MAX_CAPTURE_ERROR_NS + ); + assert!(bracket_sample(wall, 1, 100_001, 1, 500_002, trusted).is_err()); + assert!(bracket_sample(wall, 100, 99, 90, 130, trusted).is_err()); + assert!(bracket_sample(wall, u64::MAX - 1, u64::MAX, 1, 2, trusted).is_err()); + assert!(bracket_sample(u64::MAX, 100, 120, 90, 130, trusted).is_err()); + } + #[test] + fn malformed_observed_config_and_failed_reads_cannot_restore_old_authority() { + use rmm_time_attestation::Role; + let agent = "ab".repeat(32); + let helper = "cd".repeat(32); + let old_raw = serde_json::to_vec(&serde_json::json!({ + "schema_version":1, "key_generation":4, "server_instance":Uuid::new_v4(), + "binding":{"tenant_id":Uuid::new_v4(),"asset_id":Uuid::new_v4(),"agent_id":Uuid::new_v4(), + "enrollment_generation":1,"assignment_version":1,"public_key_hex":"56".repeat(32)}, + "public_keys_hex":{"time1":"78".repeat(32)}, + "calibrations":[ + {"role":"agent","binary_sha256":agent,"qualification_sha256":"12".repeat(32),"base_error_ns":1_000_000}, + {"role":"system_helper","binary_sha256":helper,"qualification_sha256":"34".repeat(32),"base_error_ns":1_000_000} + ] + })).unwrap(); + let old_sha = rmm_domain::jobs::hash(&old_raw); + let mut state = Continuity::default(); + assert!(load_configuration(&mut state, &old_raw, Role::Agent, &agent, &helper).is_ok()); + state.accept_configuration(4, &old_sha).unwrap(); + let held_epoch = state.epoch; + let owner = Uuid::new_v4(); + state.reserve(owner).unwrap(); + // This is the actual constructor's pre-parse path, not a valid DTO + // mutation that would accidentally fail only after accepting a head. + assert!( + load_configuration( + &mut state, + b"{malformed", + Role::Agent, + &"ab".repeat(32), + &"cd".repeat(32) + ) + .is_err() + ); + assert_eq!(state.configuration, Some((4, old_sha.clone()))); + assert!(state.require_owner(owner, held_epoch).is_err()); + assert!(state.require_epoch(held_epoch).is_err()); + let fenced_epoch = state.epoch; + assert!(load_configuration(&mut state, &old_raw, Role::Agent, &agent, &helper).is_ok()); + state.accept_configuration(4, &old_sha).unwrap(); + assert_eq!(state.epoch, fenced_epoch); // Same valid head is not a reset. + assert!(state.require_epoch(held_epoch).is_err()); + let fresh = Uuid::new_v4(); + let fresh_epoch = state.reserve(fresh).unwrap(); + state.require_owner(fresh, fresh_epoch).unwrap(); + // The constructor's failure/cancellation guard also covers protected + // pin/read errors before a new raw hash could be obtained. + state.configuration_failure(); + assert!(state.require_owner(fresh, fresh_epoch).is_err()); + assert_eq!(state.configuration, Some((4, old_sha))); + let mut unconfigured = Continuity::default(); + unconfigured.configuration_failure(); + assert_eq!(unconfigured.epoch, 0); } #[test] fn retained_process_fence_rejects_old_challenge_and_boot_substitution() { diff --git a/deploy/windows_trusted_clock_linux_acceptance.py b/deploy/windows_trusted_clock_linux_acceptance.py new file mode 100644 index 0000000..b57643d --- /dev/null +++ b/deploy/windows_trusted_clock_linux_acceptance.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Frozen eight Windows trusted OS profile guards on Linux only; ten other cases filtered; no updater service or Apply. + +Prepare copies the independently reviewed snapshot locally. Execute is one +root-only Cloud-VM fixture run. After any lost reply read the original case; +never execute it again or substitute another binary/source generation. +""" +import argparse +import base64 +import hashlib +import inspect +import json +import os +from pathlib import Path +import stat +import uuid + +import windows_msi_runtime_acceptance as support + +ROOT = Path(__file__).resolve().parents[1] +ACCESS_ROOT = ROOT.parent / 'rust-discovery' +QUALIFICATION = ROOT / 'devstate/windows-signed-clock/trusted-os-qualification-c4679433-b632-4d6e-8668-f0f2fb54a542' +STATE = ROOT / 'devstate/windows-trusted-clock-native-linux' +PROFILE = 'rmm.windows-clock.trusted-os-eight-linux-guards.v1' +RECEIPT_SHA = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d' +INPUTS_SHA = 'e2f0abd2909129554431257b06ae17774c95fb5abd428cbefeba2c4f573ca269' +BINARY_SHA = '0ae3487cff59c349ebde629fce3258c9f298e5cc24562bf2020409865f224912' +BINARY_BYTES = 4245312 +SOURCE_SHA = 'd8594c1eba2c2cc5d5fde4a462b2110aa2e7e64081452b742c4ed81a2cfb477d' +TESTS = ['signed_clock::tests::bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters', 'signed_clock::tests::complete_raw_report_is_bounded_non_authoritative_and_keeps_actual_brackets', 'signed_clock::tests::job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case', 'signed_clock::tests::malformed_observed_config_and_failed_reads_cannot_restore_old_authority', 'signed_clock::tests::raw_capture_denies_backward_wall_counters_and_incomplete_or_expired_series', 'signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution', 'signed_clock::tests::trusted_os_capture_uses_both_full_brackets_and_exact_integer_units', 'signed_clock::tests::trusted_profile_requires_explicit_disjoint_schema_and_both_role_images'] +ALL_TESTS = ['event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits', 'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable', 'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata', 'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes', 'journal::tests::durable_reopen_ack_identity_and_single_process', 'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes', 'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data', 'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority', 'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry', 'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload', 'signed_clock::tests::bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters', 'signed_clock::tests::complete_raw_report_is_bounded_non_authoritative_and_keeps_actual_brackets', 'signed_clock::tests::job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case', 'signed_clock::tests::malformed_observed_config_and_failed_reads_cannot_restore_old_authority', 'signed_clock::tests::raw_capture_denies_backward_wall_counters_and_incomplete_or_expired_series', 'signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution', 'signed_clock::tests::trusted_os_capture_uses_both_full_brackets_and_exact_integer_units', 'signed_clock::tests::trusted_profile_requires_explicit_disjoint_schema_and_both_role_images'] +AGENT_SHA = '0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f' +HELPER_SHA = '79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf' + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def save_local(path, value): + support.save(path, value) + fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def copy_exact(source, destination, digest, size): + metadata = source.lstat() + support.require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1 + and metadata.st_uid in (0, os.getuid()) and not metadata.st_mode & 0o002 + and metadata.st_size == size and size <= (8 if source.name == 'trusted-os-clock-tests' else 2) * 1024 * 1024, 'bounded regular frozen input') + raw = source.read_bytes() + support.require(sha(raw) == digest, 'frozen snapshot input hash') + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + support.private(destination.parent, True) + fd = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600) + with os.fdopen(fd, 'wb') as stream: + stream.write(raw); stream.flush(); os.fsync(stream.fileno()) + fd = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def verify_case(folder): + value = support.load(folder / 'manifest.json') + support.require(value['profile'] == PROFILE and value['tests'] == TESTS and value['all_listed_tests'] == ALL_TESTS + and value['runner_sha256'] == sha(Path(__file__).read_bytes()) + and value['receipt_sha256'] == RECEIPT_SHA and value['binary_sha256'] == BINARY_SHA + and value['binary_bytes'] == BINARY_BYTES, 'same original reviewed manifest') + support.require(sha((folder / 'receipt.json').read_bytes()) == RECEIPT_SHA + and sha((folder / 'inputs.json').read_bytes()) == INPUTS_SHA, 'original qualification provenance') + source = support.load(folder / 'inputs.json') + support.require(len(source) == 202 and source == value['source_files'], 'exact frozen 202 compiler inputs') + for item in source: + path = Path(item['path']) + support.require(not path.is_absolute() and '..' not in path.parts, 'fixed snapshot relative path') + file = folder / 'source' / path + support.private(file) + support.require(file.stat().st_size == item['bytes'] and sha(file.read_bytes()) == item['sha256'], 'retained source freeze') + support.require([item for item in source if item['path']=='crates/agent-windows/src/signed_clock.rs'] + == [dict(path='crates/agent-windows/src/signed_clock.rs', bytes=60822, sha256=SOURCE_SHA)], 'same trusted OS profile and constructor fence source') + binary = folder / 'windows-clock-guard-tests'; support.private(binary) + support.require(binary.stat().st_size == BINARY_BYTES and sha(binary.read_bytes()) == BINARY_SHA, 'original qualified test bytes') + for path, digest in value['transport_sources'].items(): + support.require(sha((ROOT / path).read_bytes()) == digest, 'original strict transport source') + return value + + +def remote(p): + import base64 + import hashlib + import json + import os + from pathlib import Path + import selectors + import signal + import stat + import subprocess + import time + import uuid + + def require(ok, message): + if not ok: + raise RuntimeError(message) + + def enc(value): + return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() + + def create(path, raw, mode=0o600): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode) + with os.fdopen(fd, 'wb') as stream: + stream.write(raw); stream.flush(); os.fsync(stream.fileno()) + fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + def run(args, timeout=20): + # Keep the owned group leader unreaped until its entire group has been + # cleaned up. Its PID therefore cannot be recycled before killpg. + child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, start_new_session=True, + env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'}) + selector = selectors.DefaultSelector() + buffers = {'stdout': bytearray(), 'stderr': bytearray()} + deadline = time.monotonic() + timeout + try: + for stream, name in ((child.stdout, 'stdout'), (child.stderr, 'stderr')): + os.set_blocking(stream.fileno(), False); selector.register(stream, selectors.EVENT_READ, name) + while True: + require(time.monotonic() < deadline, 'owned native command timeout; read original case only') + for key, _ in selector.select(0.02): + raw = os.read(key.fileobj.fileno(), 4096) + if raw: + buffers[key.data].extend(raw) + require(len(buffers[key.data]) <= 65536, 'bounded native output') + else: + selector.unregister(key.fileobj) + ended = os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + if ended is not None: + # Child remains a zombie until finally: no PID/group reuse. + os.killpg(child.pid, signal.SIGKILL) + for key in list(selector.get_map().values()): + while True: + try: + raw = os.read(key.fileobj.fileno(), 4096) + except BlockingIOError: + break + if not raw: + break + buffers[key.data].extend(raw) + require(len(buffers[key.data]) <= 65536, 'bounded native output') + code = ended.si_status if ended.si_code == os.CLD_EXITED else -ended.si_status + return code, bytes(buffers['stdout']), bytes(buffers['stderr']) + finally: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + selector.close(); child.stdout.close(); child.stderr.close() + + def metadata_identity(value): + return (value.st_dev, value.st_ino, value.st_uid, value.st_gid, value.st_mode, + value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns) + + def hashed(path, maximum, process_image=False): + fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | (0 if process_image else os.O_NOFOLLOW)) + with os.fdopen(fd, 'rb') as stream: + before = os.fstat(stream.fileno()); require(stat.S_ISREG(before.st_mode) and before.st_size <= maximum, 'bounded witness file') + digest = hashlib.sha256(); total = 0 + while True: + raw = stream.read(32768) + if not raw: + break + total += len(raw); require(total <= maximum, 'bounded witness hash'); digest.update(raw) + after = os.fstat(stream.fileno()) + require(metadata_identity(before) == metadata_identity(after) and total == before.st_size, 'stable witness hash') + return before, digest.hexdigest() + + def witness(): + out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}} + release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line) + require(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'fixed native Ubuntu24.04') + out['os'] = {'id': 'ubuntu', 'version': '24.04', 'machine': os.uname().machine, 'kernel': os.uname().release} + for name, uid, binary in ( + ('rmm-agent-remote.service', 993, p['agent_sha256']), + ('rmm-helper-cloud.service', 0, p['helper_sha256']), + ('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])): + code, stdout, _ = run(['/usr/bin/systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState', '-p', 'InvocationID']) + require(code == 0, 'existing service read') + service = dict(line.split('=', 1) for line in stdout.decode().splitlines()) + pid = int(service['MainPID']); require(service['ActiveState'] == 'active' and pid > 1, 'three existing services active') + proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] + ids = {line.split(':')[0]: line.split()[1:] for line in (proc / 'status').read_text().splitlines() if line.startswith(('Uid:', 'Gid:'))} + metadata, image = hashed(proc / 'exe', 256 * 1024 * 1024, process_image=True) + current = (proc / 'exe').stat() + require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary + and (metadata.st_dev, metadata.st_ino) == (current.st_dev, current.st_ino) + and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'current generation/account/image') + out['services'][name] = dict(service, birth=birth, image=image, ids=ids) + code, stdout, _ = run(['/usr/bin/systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState']) + apt = dict(line.split('=', 1) for line in stdout.decode().splitlines()) + require(code == 0 and apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed') + out['apt'] = apt + for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json', + '/etc/rmm-remote/full-maintenance-helper-proof.json', '/etc/systemd/system/rmm-full-maintenance-helper.service'): + path = Path(name); metadata = path.lstat() + require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_uid == 0 + and not metadata.st_mode & 0o022 and metadata.st_nlink == 1, 'protected known control') + current, digest = hashed(path, 65536) + require(metadata_identity(current) == metadata_identity(metadata), 'same known control file') + out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode, + metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns, digest] + for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock', + '/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite'): + path = Path(name); metadata = path.lstat() + require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1, 'existing state identity') + out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode] + return out + + require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root contract fixtures') + ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case') + folder = Path('/var/tmp') / ('rmm-windows-trusted-clock-tests-' + ident) + if p['action'] == 'read': + metadata = folder.lstat() + require(stat.S_ISDIR(metadata.st_mode) and not folder.is_symlink() and metadata.st_uid == 0 + and stat.S_IMODE(metadata.st_mode) == 0o700, 'own original case only') + intent = json.loads((folder / 'intent.json').read_bytes()) + require(all(intent.get(key)==value for key,value in p.items() if key!='action'), 'same original read binding') + result = folder / 'result.json' + return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(), + 'result': json.loads(result.read_bytes()) if result.exists() else None, 'current_witness': witness()} + require(p['action'] == 'execute', 'one fixed time contract action') + os.umask(0o077); folder.mkdir(mode=0o700) + create(folder / 'intent.json', enc({key: value for key, value in p.items() if key != 'binary_b64'})) + require(len(p['binary_b64']) == 5660416, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 4245312 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed eight-guard library binary') + binary = folder / 'windows-clock-guard-tests'; create(binary, raw, 0o700) + before = witness(); create(folder / 'before.json', enc(before)) + command = ['/usr/bin/setpriv', '--reuid=0', '--regid=0', '--clear-groups', '--no-new-privs', str(binary)] + code, stdout, stderr = run(command + ['--list', '--format', 'terse']) + create(folder / 'list.stdout', stdout); create(folder / 'list.stderr', stderr) + require(code == 0 and stderr == b'', 'native list succeeded') + lines = stdout.decode().splitlines() + require(len(lines) == 18 and all(line.endswith(': test') for line in lines) and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['all_listed_tests'], 'exact full eighteen-test list before eight targeted tests') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + code, stdout, stderr = run(command + ['signed_clock::tests::', '--test-threads=1', '--nocapture']) + create(folder / 'run.stdout', stdout); create(folder / 'run.stderr', stderr) + after = witness(); create(folder / 'after.json', enc(after)) + require(before == after and code == 0 and stderr == b'' + and b'8 passed; 0 failed; 0 ignored; 0 measured; 10 filtered out' in stdout + and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'eight native guards with ten filtered and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=8, ignored=0, filtered=10, listed=18, execution_uid=0, tests=p['tests'], + before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'], + source_manifest_sha256=p['manifest_sha256'], stdout_sha256=hashlib.sha256(stdout).hexdigest(), + no_rmm_jobs=True, no_apply=True, no_service_control=True) + create(folder / 'result.json', enc(receipt)); return receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare', 'execute', 'read')); parser.add_argument('--case') + args = parser.parse_args(); os.umask(0o077) + STATE.mkdir(mode=0o700, parents=True, exist_ok=True); support.private(STATE, True) + if args.action == 'prepare': + support.require(args.case is None, 'prepare one new local case') + receipt_path = QUALIFICATION / 'receipt.json'; support.private(receipt_path) + support.require(sha(receipt_path.read_bytes()) == RECEIPT_SHA, 'independently reviewed source receipt') + receipt = support.load(receipt_path); original = support.load(QUALIFICATION / 'inputs.json') + support.require(sha((QUALIFICATION / 'inputs.json').read_bytes()) == INPUTS_SHA + and receipt['inputs_sha256'] == INPUTS_SHA and len(original) == 202 + and receipt['profile'] == 'rmm.windows.trusted-os-active-guest.source-qualification.v1' + and receipt['source_sha256'] == SOURCE_SHA and receipt['inputs_verified_before_after'] is True + and receipt['calibration_or_pins_created'] is False and receipt['targets_called'] is False + and receipt['checks']['linux_signed_clock_guards']['complete_test_list'] == ALL_TESTS + and receipt['checks']['linux_signed_clock_guards']['selected'] == TESTS + and receipt['checks']['linux_signed_clock_guards']['passed'] == 8 + and receipt['checks']['linux_signed_clock_guards']['ignored'] == 0 + and receipt['checks']['linux_signed_clock_guards']['filtered'] == 10, + 'reviewed eight-guard trusted OS qualification') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700) + copy_exact(receipt_path, folder / 'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size) + copy_exact(QUALIFICATION / 'inputs.json', folder / 'inputs.json', INPUTS_SHA, (QUALIFICATION / 'inputs.json').stat().st_size) + paths = set() + for item in original: + path = Path(item['path']) + support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique fixed frozen input') + paths.add(str(path)); copy_exact(QUALIFICATION / 'source' / path, folder / 'source' / path, item['sha256'], item['bytes']) + binary = QUALIFICATION / 'trusted-os-clock-tests' + support.require(receipt['checks']['linux_signed_clock_guards']['binary'] == dict(filename='trusted-os-clock-tests', + bytes=BINARY_BYTES, sha256=BINARY_SHA, mode='0500', nlink=1), 'fixed original linked artifact') + copy_exact(binary, folder / 'windows-clock-guard-tests', BINARY_SHA, BINARY_BYTES) + transports = {path: sha((ROOT / path).read_bytes()) for path in ('deploy/windows_msi_runtime_acceptance.py', 'deploy/vm_access_check.py')} + save_local(folder / 'manifest.json', dict(id=ident, profile=PROFILE, runner_sha256=sha(Path(__file__).read_bytes()), + receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_bytes=BINARY_BYTES, + source_files=original, tests=TESTS, all_listed_tests=ALL_TESTS, transport_sources=transports)) + verify_case(folder) + print(json.dumps({'id': ident, 'prepared_locally': True})); return + support.require(args.case is not None, 'original --case required') + ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same canonical original case') + folder = STATE / ident; support.private(folder, True); verify_case(folder) + payload = dict(id=ident, action=args.action, profile=PROFILE, tests=TESTS, all_listed_tests=ALL_TESTS, binary_sha256=BINARY_SHA, + receipt_sha256=RECEIPT_SHA, manifest_sha256=sha((folder / 'manifest.json').read_bytes()), + agent_sha256=AGENT_SHA, helper_sha256=HELPER_SHA) + if args.action == 'execute': + save_local(folder / 'execute-entered.json', {'once': True, 'no_retry': True}) + payload['binary_b64'] = base64.b64encode((folder / 'windows-clock-guard-tests').read_bytes()).decode() + code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n' + response = support.transport(support.access_settings(ACCESS_ROOT, 'linux'), 'python3 -', code.encode(), folder) + save_local(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response) + if args.action == 'read' and response['result'] is not None: + support.require(response['result']['source_manifest_sha256'] == sha((folder / 'manifest.json').read_bytes()) + and response['result']['source_receipt_sha256'] == RECEIPT_SHA + and response['result']['binary_sha256'] == BINARY_SHA and response['result']['tests'] == TESTS + and response['result']['passed'] == 8 and response['result']['ignored'] == 0 + and response['result']['filtered'] == 10 and response['result']['listed'] == 18 + and response['result']['before'] == response['result']['after'] + and response['current_witness'] == response['result']['after'], 'same-case retained native result') + print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'), + 'complete': response.get('result') is not None if args.action == 'read' else True, 'read_only': args.action == 'read'})) + + +if __name__ == '__main__': + main() diff --git a/docs/handover.md b/docs/handover.md index 628441b..26aa70d 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -1,5 +1,11 @@ # Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt +**Zwei reale Schritte bestanden:** freigegebener einmaliger Chronyrestart +und Pin395f mit separatem Read/Erhaltung ([Belege](server-time-source-chrony-generation-bootstrap.md)); +aktives Windows-Zeitprofil nativ Cloud-Linux8/18,10gefiltert, separater Read +([Belege](windows-trusted-os-clock-source.md)). Noch kein echter Server- +Qualitätssample, Signer/Broker oder Windows-Jobgate. + **Chrony-Generationsplan konkret und lesend geprüft:** d5d56b38, tatsächlicher Preflightb7c05714 bestanden (Normal/Stratum3,0.123ms Offset); ursprüngliche Runtime/Config/Pin erhalten. [Plan und Belege](server-time-source-chrony-generation-bootstrap.md). diff --git a/docs/server-time-source-chrony-generation-bootstrap.md b/docs/server-time-source-chrony-generation-bootstrap.md index 0bf385d..7489500 100644 --- a/docs/server-time-source-chrony-generation-bootstrap.md +++ b/docs/server-time-source-chrony-generation-bootstrap.md @@ -127,3 +127,35 @@ engen oben dokumentierten Quellenkorrekturen; kein früherer Misserfolg wird umgeschrieben. Keine Restartphase angelegt, kein Service gestoppt oder Publicpin ersetzt. `host-restart` wartet weiterhin auf ausdrückliche Userfreigabe des konkreten Plans samt möglichem normalen Start-Sync-Effekt. + +## Freigegebener Restart und öffentlicher Pinwechsel tatsächlich bestanden + +Der User genehmigte ausdrücklich „Ja, einmaliger Zeitdienstneustart mit +Pinprüfung“. Danach genau ein `host-restart`, Originalfall +`c9a94f94-eecd-4c66-933d-c45c1a79c7a8`, tatsächlicher Exit0/abgeschlossen. +Rootreceipt +`1173ef78f9ca704afafbf4dbe92e8c654ec47d53f4e9f05fd99be2685991ce59`. +Vorhandene Konfiguration, tatsächliche Images, Boot und RMM-Runtime erhalten; +neue Chrony-Prozess-/Socketgeneration unabhängig geprüft und nach tatsächlicher +Readiness atomar gepinnt. Keine Konfiguration, Pakete oder RMM-Dienste geändert. + +Neuer öffentlicher Pin:195Bytes, Root:Root0600/Singlelink, SHA256 +`395f170aabf9fd01c24cd7d7939a313befdd147e98343ccd383bca861cbf2c4e`. +Alte194Bytes/203f und Metadaten bleiben im neuen Fall archiviert. Keine +Behauptung unveränderter Publicpin-Inode: dieser Wechsel ist ausdrücklich +genehmigt und als eigene CAS-Operation belegt. Die übrigen Identitäten bleiben +erhalten. + +Separater ausschließlich lesender Rückabruf df1fe7b1, Receipt +`58970ef8e89af86b68fdbbf2cb5119210bcb37cec603feb23b4f6030b0b36623`, +bestätigt ursprüngliches Result +`d648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4`, +neuen Pin und Erhaltungsflags. Keine Wiederholung des Restarts. + +`source_quality_qualified=false`: noch kein gemeinsamer NativeTimeSource- +Sample, Signer, Zeitkey, Broker oder Windows-Clockgate. Die historischen +5b-/GROUP-/DAC-/Peerfehler und ihre alte Generation bleiben erhalten. Ihr +altes `Original.fresh()` darf nach diesem absichtlichen Generationswechsel +nicht als aktuelle Authority verwendet oder durch erwartete-Werte-Tausch +„repariert“ werden. Neue reale Qualitätsprobe benötigt einen gesonderten +Originalbuild-/neue-Generationsnachweis. diff --git a/docs/windows-trusted-os-clock-source.md b/docs/windows-trusted-os-clock-source.md new file mode 100644 index 0000000..9855cfa --- /dev/null +++ b/docs/windows-trusted-os-clock-source.md @@ -0,0 +1,81 @@ +# Windows: ausdrücklich genehmigtes aktives OS-Zeitprofil + +Stand2026-11-15, normative Userentscheidung in Spezifikation1.23/Projektentscheidungen (`b761384`). `trusted_os_active_guest` ist nun implementiert und lokal geprüft. Keine Zeitkonfiguration, keine Schlüssel-/Pinprovisionierung, kein VM-Aufruf und keine Gatefreischaltung wurden daraus vorgenommen. Die frühere [KVM-Bewertung und Entscheidungsfrage](windows-kvm-clock-contract-proposal.md) ist der historische Vorschlag; die ausdrückliche Zustimmung gilt nur unter den dort genannten Betriebsannahmen. + +Der neue Modus vertraut den dokumentierten Windows-Zeit-APIs und einer korrekt laufenden Hardware-/KVM-/QEMU-Zeitbasis als nomineller Intervalluhr. Er behauptet keine unabhängig gemessene physikalische Genauigkeit. Vor Pause, Save/Restore, Snapshot-Rückkehr, Migration oder Host-Suspend müssen beide Agent-/Helperprozesse beendet werden; danach sind frische Prozesse, Challenges und unabhängiger Sync erforderlich. Solche Ereignisse mit weiterlaufenden Prozessen werden nicht unterstützt oder durch eine nicht vorhandene VMGenID-Erkennung scheinbar abgedeckt. Der Code verändert keine VM-/Hosteinstellung. + +## Geschützter, disjunkter Loadervertrag + +Die bestehende geschützte Datei bleibt `C:\ProgramData\RustDiscoverySystem\time-attestation.json`. Es existiert hier **keine erzeugte Instanz**. Zwei vollständige `deny_unknown_fields`-Records verhindern eine automatische Übernahme: + +| Eigenschaft | Schema1 | Schema2 | +| --- | --- | --- | +| Modus | bisherige numerische Kalibrierung | ausdrücklich `trusted_os_active_guest` | +| Profilfeld | `calibrations` mit genau2 Rollen | `trusted_os_active_guest` mit genau2 `qualifications` | +| Basisfehler | positiv und höchstens10ms | kein `base_error_ns`-Feld und kein Nullbasis-Trick | +| Plattform-/Betriebsbindung | bisheriger Qualifikationsvertrag | feste KVM/QEMU/Hyper-V-Clock-Kennung, Provenance-SHA und fester aktiver Betriebsvertrag | +| Fremde/gemischte Felder | verweigert, auch `trusted_os_active_guest:null` | verweigert, auch `calibrations:null` | + +Unbekannte Versionen, Profile, Annahmen, Plattformen, fehlende oder doppelte Rollen, falsche Imagehashes und fehlende Qualifikationsreferenzen bleiben geschlossen. Commonfields sind unverändert Schlüsselgeneration, Serverinstanz, vorhandene Gerätebindung und separate öffentliche Zeitkeys. Der Zeitkey bleibt vom konkreten Jobkey unabhängig. Die tatsächlich installierte eigene Dienst-/Token-/Imageidentität wird weiter unabhängig geprüft; ein Konfigurationswert ersetzt diese Prüfung nicht. + +## Softwarebudget und Fences + +Der vollständige native Getterbracket bleibt Interrupt-before, Unbiased-before, Wallclock, Unbiased-after, Interrupt-after. Schema2 verwendet konservativ das Maximum der **beiden vollständigen** Interrupt-/Unbiasedbracketbreiten. Die Umrechnung von100ns-Einheiten nach Nanosekunden erfolgt exakt mit überlaufgeprüfter Ganzzahlmultiplikation; dafür fällt kein Umrechnungsrest an. Es wird keine zusätzliche positive physikalische Fehlerkonstante erfunden. Ein im nominellen OS-Zählerraum gleichwertiger Capture darf deshalb ein Nullbracket liefern; das ist keine physikalische Nullfehlerbehauptung. Schema1 behält unverändert seinen bisherigen Interruptbracket plus tatsächlich qualifizierten positiven Basiswert. + +Die bestehenden Budgets bleiben erhalten: maximal50ms für die konservative Summe der drei Captures; volle selbst gemessene RTT und konservative1s-/100ms-Frischegrenzen. Codec, Wirebytes, Signaturdomäne, getrennte Nonces/Rollen/Inkarnationen, eigener Boot-/Connectionkontext und gesamtes UTC-Intervall ändern sich nicht. Jede spätere Nutzung erfasst die eigenen Getter erneut; keine Belegverlängerung. Serverquellqualität und jeder normale Sync-/Grant-/Verbrauchs-/Ledger-/WebUI-Gate bleiben zusätzliche Voraussetzungen. + +Ein zusätzlich geschlossener Constructorfehlerpfad verhindert Wiederbelebung nach beobachteten fehlerhaften Konfigurationen: Der Rawhash wird **vor** JSON-/Profilprüfung gegen den gehaltenen Prozesshead beobachtet. Unterschiedliche Bytes invalidieren den globalen Epoch ohne Übernahme eines neuen Hashes oder Floors. Ein RAII-Fence schließt bekannte Autorität auch bei geschütztem Lese-/Pinfehler oder abgebrochenem Konstruktor. Erfolgreiche Konstruktoren derselben gültigen Konfiguration drehen den Epoch nicht. Wiederherstellung alter Bytes heilt keine alte Evidenz oder offene Nonce; erst eine neue Challenge ist zulässig. Die bisherige monotone Konfigurationsannahme bleibt erhalten; diese Änderung erfindet kein dauerhaftes neues Floorjournal. + +## Öffentliche Producer-Form für den späteren echten Beleg + +Der konkrete serialisierbare Rust-Vertrag ist `Configuration::TrustedOs(TrustedOsConfiguration { ... })`; er kann ausschließlich aus tatsächlich gelieferten öffentlichen Nachweisen befüllt werden. Die folgende Form benennt Pflichtdaten, enthält keine Dummykeys und erzeugt keine Konfiguration: + +| Feld | Erforderliche echte Quelle | +| --- | --- | +| `schema_version` | exakt2 | +| `key_generation`, `server_instance`, `public_keys_hex` | tatsächlich qualifizierter permanenter Broker-/Signierrollenbeleg; nur öffentliche Zeitkeys | +| `binding` | unveränderte bestehende geschützte Geräte-/Tenant-/Enrollment-/Assignment-/Jobpublickeybindung | +| `trusted_os_active_guest.operating_assumption` | exakt `active_guest_no_pause_save_restore_snapshot_migration_host_suspend` | +| `trusted_os_active_guest.platform` | exakt `kvm_qemu_hypervclock` | +| `trusted_os_active_guest.platform_provenance_sha256` | tatsächlicher selektiver Plattform-/Betriebsannahmenbeleg, separat geschützt durch Root provisioniert | +| `trusted_os_active_guest.qualifications` | genau eine Referenz je `agent` und `system_helper`, jeweils exakter neuer Produktimagehash plus tatsächlicher rollen-/imagegebundener Qualifikationsbeleg-SHA | + +Keine Tabelle, Referenz oder Source-Datei ist selbst eine Kalibrierung oder Jobfreigabe. Der spätere Root-Producer muss Originalbelege, exakte Images und deren unabhängige native Abnahmen prüfen, bevor er diese Form serialisiert und den geschützten Konfigurationswechsel als eigenen überprüften Fall durchführt. Fehlende echte Daten bleiben fehlend; kein automatisches `calibrated=true`, kein beliebiger Betrag und kein privater Keyimport. Die Vorqualifikationsreferenz darf nur die tatsächlich belegten Source-/Image-/Dienstrollen-/Rohcapture-/Plattformbefunde aussagen: Sie behauptet noch keine funktionierende signierte Runtime. Deren unabhängige native Prüfung folgt nach Bereitstellung der echten öffentlichen Zeitkonfiguration; ein clockpflichtiger Helper-Snapshot oder bereits bereiter Clockgate ist keine Voraussetzung des ersten passiven Bootstrapwitness. Die aktuell früher gelinkten Produktpaare sind wegen dieses neuen Modulcodes veraltet; ein neues Paar und neue native Nachweise folgen getrennt. + +## Tatsächliche lokale Qualifikation + +Unveränderlicher202-Input-Fall `trusted-os-qualification-c4679433-b632-4d6e-8668-f0f2fb54a542`, Manifest `e2f0abd2909129554431257b06ae17774c95fb5abd428cbefeba2c4f573ca269`, Modulquelle `d8594c1eba2c2cc5d5fde4a462b2110aa2e7e64081452b742c4ed81a2cfb477d`, Receipt `96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d`. Offline-Docker, Quellen nur lesbar, eigene private Targets, keine Credentials-Mounts. + +- Rustfmt und Linux-Lib/Tests-Clippy mit `-D warnings`: PASS. +- Linux-Release-Link und die acht relevanten `signed_clock`-Guards: PASS. Vollständige Liste18; zehn andere Tests ausdrücklich herausgefiltert. Drei neue Guards prüfen disjunkte Opt-ins und beide Rollenbindungen, beide vollständigen Brackets samt Integer-/Budgetgrenzen sowie den tatsächlichen malformed-Raw-Loaderpfad mit Restore und geschlossenem alten Epoch/Pendingowner. +- Windows-GNU-Alltargetscheck und Clippy mit `system-helper`: PASS. Release-Lib-Test-EXE erfolgreich gelinkt, **nicht ausgeführt**. Kein neues Produktpaar in diesem Beleg. + +Der erste Windowscheck scheiterte vor Crateprüfung an fehlenden Execbits alter kopierter Cache-Buildskripte. Originalfehlerlog/Exit101 sind erhalten. Nach Änderung ausschließlich der eigenen kopierten ELF-Buildskriptmodi bestanden dieselben eingefrorenen Quellen separat; keine Unterdrückung eines Sourcefehlers. + +Linux-ELF `trusted-os-clock-tests`:4245312Bytes, SHA256 `0ae3487cff59c349ebde629fce3258c9f298e5cc24562bf2020409865f224912`. Windows-Lib-Test-EXE:12772565Bytes, SHA256 `ecb57571b8df1b4a178f7d7e2dc1ad21fee11cdb5ea558a2eb35a52f544e64e5`. Beide Übergabedateien Modus0500/ein Hardlink. Lokale Guards/Cross-Link ersetzen nicht die tatsächliche Cloud-Linux-Ausführung und anschließenden Windows-Rollen-/Runtimebelege. Gates bleiben bis dahin geschlossen. Strukturierter EventLog-Kindadapter und übrige Windows-Wirkungsabnahmen bleiben gesondert offen; Windows ist nicht vollständig abgenommen. + +## Getrennte vorbereitete Folgeschritte + +Der neue feste Linux-first-Operator ist `deploy/windows_trusted_clock_linux_acceptance.py`, SHA256 `cbabb7c88bf070bcc3ac6933650a7abf114e00b5bcabe3aefdfc4db213a997a9`. Lokal vorbereiteter Fall `293ecff5-6c6f-47a2-9ce2-60de0ffe99ed`, Manifest `52cda33ccba636adc35fb534e34095be7b3d9d3abc0ff7c9896c29dd433fc373`. Er prüft die vollständige18er-Liste vor den acht festen `signed_clock`-Guards; zehn fremde Cratetests bleiben transparent gefiltert. Die tatsächlichen bestehenden Linuxruntime-Witnesses und der auf die eigene Prozessgruppe begrenzte Runner sind bytegleich zum vorherigen Raw-Clock-Operator. Python-AST, lokale Prepare-/Revalidation und dieser Bytevergleich PASS. Keine Zielausführung durch diesen Agenten; Root führt den einmaligen nativen Lauf und den separaten Originalfall-Read durch. + +Danach separat tatsächlich gebaut: neues Windows-GNU-Produktpaar aus exakt demselben202-Input-Snapshot und derselben Modulquelle `d8594c1e…`, Fall `trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8`. Offline/Netzwerk aus, Quellen nur lesbar, keine Credentials-Mounts, ausschließlich Agent und SYSTEM-Helper. Release-Link Exit0 (17.91s), Quellen vorher/nachher unverändert. Receipt `04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d`, Buildlog `e9437ac94a63d20a68c1af35f1670042fe44407796a03541cdcd7bdb9e16bfaa`. + +| Neuer Profilkandidat | Bytes | SHA256 | +| --- | ---: | --- | +| Agent | 22283627 | `26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b` | +| SYSTEM-Helper | 13143052 | `59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e` | + +Beide sind AMD64-PEs, Modus0500/ein Hardlink. Frühere Paare bleiben historisch erhalten. Kein Paarupgrade, neuer Mainindex, öffentliches Zeitpinfile, Kalibrierungswert oder Clockgatewechsel wurde ausgeführt. Der aktuelle passive Paarcontroller bleibt weiterhin fest geschlossen und bindet noch seine vorige Kandidatengeneration; diese neue Generation erfordert später einen eigenen überprüften Controllerbeleg und frische CAS-/Serverwitnesses. Die öffentliche Producer-Form oben enthält bewusst nur tatsächlich zu belegende Felder und keine Platzhalterkonfiguration. + +## Tatsächlich Linux-first auf der Cloud-VM bestanden + +Originalfall `293ecff5-6c6f-47a2-9ce2-60de0ffe99ed`: vollständige18er-Liste +vor Ausführung geprüft, genau acht signed_clock-Guards bestanden,0failed/ignored, +zehn andere ausdrücklich gefiltert. Execute-Receipt +`98aae935740eb4c9d50366715be9a130791b141681b091af431129d6f833f563`. +Separater Originalread bestätigt gleiche Source-/Artefaktbindungen und erhaltene +aktuelle Runtime-/Control-/Stateidentitäten, Receipt +`06711537d71f436b7776e7c2d47eb6e2963820b7a6c55302bc7786568c23c28b`. +Unabhängiger Quellenreview des Schema-/Bracket-/Constructorfencedeltas ebenfalls +ohne konkreten Befund abgeschlossen. Keine Windows-Rollen-/Zeitkonfiguration, +kein RMM-Job oder Effektgate wurde dadurch aktiviert.