diff --git a/Cargo.lock b/Cargo.lock index 01c36d9..7520d86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2252,6 +2252,7 @@ dependencies = [ "rmm-agent-core", "rmm-domain", "rmm-protocol", + "rmm-time-attestation", "rusqlite", "rustls", "rustls-pemfile", @@ -2382,6 +2383,33 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-time-attestation" +version = "0.1.0" +dependencies = [ + "anyhow", + "ed25519-dalek", + "hex", + "rand 0.9.5", + "serde", + "serde_json", + "sha2 0.10.9", + "uuid", +] + +[[package]] +name = "rmm-time-source-linux" +version = "0.1.0" +dependencies = [ + "anyhow", + "hex", + "libc", + "serde", + "serde_json", + "sha2 0.10.9", + "uuid", +] + [[package]] name = "rmm-updater" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a253138..43d0b3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" exclude = ["crates/oidc-auth"] -members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker"] +members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/time-attestation", "crates/time-source-linux"] [workspace.package] version = "0.1.0" diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 06d04c6..f92c63c 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.21 · 2026-11-14 · Sprache: Deutsch +Version 1.22 · 2026-11-14 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -47,6 +47,11 @@ Codepaar, eigener großer Artefaktpfad, WebUI-gebundener Updatejob und erhaltend Helper-/Updater-Übergabe mit geschlossenem Inflight-/Healthkontrollpfad werden präzisiert. Das ist keine native Applyabnahme oder Freigabe weitererM7-Themen. +1.21 → 1.22 (2026-11-14): Der User erlaubt für Windows einen unabhängigen, +signierten Zeitvergleich mit dem festgelegten Server als alternative Trustsource. +Agent und SYSTEM-Helper prüfen unabhängig; fehlende Qualität sperrt Jobs. +Keine Uhrstellung, keine automatische Genehmigung und kein nativer Erfolgsbeleg. + ## Inhaltsverzeichnis - [0 Auftrag und verbindliche Produktanforderungen](#0-auftrag-und-verbindliche-produktanforderungen) @@ -80,6 +85,48 @@ präzisiert. Das ist keine native Applyabnahme oder Freigabe weitererM7-Themen. ## 0 Auftrag und verbindliche Produktanforderungen +**Userentscheidung Version1.22, signierter Windows-Zeitvergleich:** Auf die +konkrete Frage nach der Alternative zur nicht qualifizierbaren W32Time- +Dienstidentitätsbindung hat der User ausdrücklich „Ja, signierten Zeitvergleich +umsetzen“ geantwortet. Ein unabhängiger signierter Onlinevergleich mit +`discovery.ease-technologies.de` darf daher die aktuelle Windows-Wallclock +qualifizieren. Der frühere Ausschluss eines Serverzeitankers im lokalen +Windows-Clockvertrag wird ausschließlich für diesen gebundenen Vergleich ersetzt. +W32Time-Rohstatus bleibt unverfälscht separat; daraus wird kein lokaler NTP-Sync +erfunden. Keine OS-Zeitstellung oder implizite Resyncfreigabe. + +Ein gesondert geschützter Ed25519-Zeitschlüssel, exakte versionierte Codecbytes +und provisionierte Pins müssen unabhängig von TLS-/Job-/Updateschlüsseln sein. +Agent und SYSTEM-Helper erzeugen und prüfen jeweils eigene Nonce, Inkarnation, +Boot-/Verbindungs-/Gerätebindung und lokale monotone/Wallclockbeobachtung; der +Agent ist beim Helper ausschließlich Transport. Serverseitige Gerätezuordnung +kommt aus gültigem mTLS und tatsächlichem Verbindungskontext, nicht aus +ungeprüften Requestfeldern. TLS/SAN/SNI wird auch bei falscher OS-Zeit nicht +umgangen. Jede fehlende Bindung oder Qualität bedeutet CLOCK_UNTRUSTED. + +Der Server muss vor jeder Signatur tatsächlichen synchronisierten Kernelstatus, +höchstens1h altes gutes Quellensync und konservativ höchstens500ms Gesamtfehler +nachweisen. Fehlende Providerbelege sperren; Pollzeit ersetzt kein Syncalter. +Je verifiergehaltener Challenge gelten höchstens1s bis Prüfung und höchstens100ms +seit Empfang; das zusätzliche Capture-/Timerbudget von höchstens50ms benötigt +reale Plattformqualifikation. Für Capture T, Serverfehler epsilon, vollen selbst +gemessenen RTT R und qualifiziertes Budget delta gilt die konservative Spanne +[T-epsilon,T+epsilon+R+delta]. Lokale Wallclock muss zur gesamten Spanne +höchstens2s abweichen. Startfristen müssen die gesamte Spanne erfüllen: +Untergrenze >= not_before, Obergrenze < start_before. Alte Grantbytes und +60s-Startfenster bleiben unverändert; kein Refresh verlängert einen Grant. + +Boot-/Prozess-/Verbindungswechsel, Replay, Rückwärtszähler, Wallstep oder +Sleepdiskontinuität verwerfen Bereitschaft und offene Challenges. Nach einer +Diskontinuität braucht es eine danach erzeugte Challenge; kein Konstruktorreset +oder gespeicherter Beleg darf den Fence umgehen. Kein längerer Holdover. +Ein Zeitbeleg ist weder SignedSync noch Startgrant oder Jobgenehmigung; +WebUI-, Verbrauchs-, Ledger- und Helpergrenzen bleiben zusätzlich erforderlich. +Der konkrete Entwurf und die offenen tatsächlichen Qualifikationsschritte stehen +in docs/windows-clock-attestation-proposal.md. Dies genehmigt Implementierung, +keinen Clockgatewechsel ohne Linux-first-/Windows-Nachweise. + + **Präzisierung Version1.14, zeitgebundener Rebootnachweis:** Die ursprüngliche Wiederverbindungsfrist ab serverseitiger Startreservierung bleibt unverändert. Ein tatsächlich vor Fristende unabhängig empfangener neuer Boot-Inventarbeleg diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index 97f5e6c..3b0804c 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -31,6 +31,7 @@ uuid.workspace = true rmm-domain = { path = "../domain" } rmm-agent-core = { path = "../agent-core" } rmm-protocol = { path = "../protocol" } +rmm-time-attestation = { path = "../time-attestation" } rusqlite = { version = "0.32.1", features = ["bundled"] } fs2 = "0.4.3" rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] } diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs index 064fa52..ff51846 100644 --- a/crates/agent-windows/src/lib.rs +++ b/crates/agent-windows/src/lib.rs @@ -27,6 +27,7 @@ pub mod package; pub mod process; #[cfg(windows)] pub mod service; +pub mod signed_clock; #[cfg(all(windows, feature = "system-helper"))] mod system_script; diff --git a/crates/agent-windows/src/signed_clock.rs b/crates/agent-windows/src/signed_clock.rs new file mode 100644 index 0000000..7ce2473 --- /dev/null +++ b/crates/agent-windows/src/signed_clock.rs @@ -0,0 +1,623 @@ +//! Independent signed time comparison for the Windows agent and SYSTEM helper. +//! This module does not implement SyncClock, advertise a capability, start a job, +//! change W32Time or replace the still-closed legacy NativeClock adapter. +#![cfg(any(test, all(windows, feature = "system-helper")))] +use anyhow::{Result, ensure}; +use rmm_time_attestation::Sample; +use uuid::Uuid; + +const SECOND_NS: u64 = 1_000_000_000; +const MAX_BASE_ERROR_NS: u64 = 10_000_000; + +fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> { + fn decode(value: &str) -> Result<[u8; 32]> { + ensure!( + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()), + "TIME_NATIVE_PUBLIC_KEY" + ); + let mut raw = [0u8; 32]; + for (index, byte) in raw.iter_mut().enumerate() { + *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)?; + } + Ok(raw) + } + let time = decode(time_key_hex)?; + let job = decode(job_key_hex)?; + ensure!(time != job, "TIME_NATIVE_KEY_ROLE_REUSE"); + Ok(time) +} + +#[derive(Default)] +struct Continuity { + boot_id: Option, + previous: Option, + epoch: u64, + exhausted: bool, + active: Option, + configuration: Option<(u64, String)>, + connection_generation: Option, +} +impl Continuity { + fn invalidate(&mut self) { + self.active = None; + match self.epoch.checked_add(1) { + Some(epoch) if !self.exhausted => self.epoch = epoch, + _ => self.exhausted = true, + } + } + fn observe(&mut self, boot_id: Uuid, sample: Sample) -> Result<()> { + let valid = !boot_id.is_nil() + && !self.exhausted + && self.boot_id.is_none_or(|old| old == boot_id) + && sample.wall_utc_ns > 0 + && sample.capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS + && self.previous.is_none_or(|old| { + match ( + sample.wall_utc_ns.checked_sub(old.wall_utc_ns), + sample.interrupt_ns.checked_sub(old.interrupt_ns), + sample.unbiased_ns.checked_sub(old.unbiased_ns), + ) { + (Some(wall), Some(interrupt), Some(unbiased)) if wall >= 0 => { + (wall as u64).abs_diff(interrupt) <= SECOND_NS + && interrupt.abs_diff(unbiased) <= SECOND_NS + } + _ => false, + } + }); + // Never adopt a different boot in a surviving process. A new adapter + // object cannot erase this process-wide identity/continuity history. + self.boot_id.get_or_insert(boot_id); + self.previous = Some(sample); + if !valid { + self.invalidate(); + } + ensure!(valid, "TIME_NATIVE_DISCONTINUITY_OR_BOOT"); + Ok(()) + } + fn accept_configuration(&mut self, generation: u64, sha256: &str) -> Result<()> { + ensure!( + generation > 0 && !self.exhausted, + "TIME_NATIVE_CONFIGURATION_GENERATION" + ); + if let Some((current, hash)) = &self.configuration { + ensure!( + generation >= *current && (generation != *current || hash == sha256), + "TIME_NATIVE_CONFIGURATION_ROLLBACK_OR_FORK" + ); + if generation > *current { + self.invalidate(); + } + } + self.configuration = Some((generation, sha256.into())); + Ok(()) + } + fn accept_connection(&mut self, generation: u64) -> Result<()> { + ensure!( + generation > 0 + && !self.exhausted + && self + .connection_generation + .is_none_or(|old| generation >= old), + "TIME_NATIVE_CONNECTION_ROLLBACK" + ); + if self + .connection_generation + .is_some_and(|old| generation > old) + { + self.invalidate(); + } + self.connection_generation = Some(generation); + Ok(()) + } + fn require_connection(&self, generation: u64) -> Result<()> { + ensure!( + !self.exhausted && self.connection_generation == Some(generation), + "TIME_NATIVE_CONNECTION_CHANGED" + ); + Ok(()) + } + fn reserve(&mut self, owner: Uuid) -> Result { + ensure!( + !self.exhausted && !owner.is_nil() && self.active.is_none(), + "TIME_NATIVE_CHALLENGE_BUSY" + ); + self.active = Some(owner); + Ok(self.epoch) + } + fn require_owner(&self, owner: Uuid, epoch: u64) -> Result<()> { + ensure!( + !self.exhausted && self.active == Some(owner) && self.epoch == epoch, + "TIME_NATIVE_CHALLENGE_INVALIDATED" + ); + Ok(()) + } +} + +/// All three native clocks are read in one bracket. The qualified base error +/// is a protected installation input, never inferred from 100ns resolution. +fn bracket_sample( + wall_filetime: u64, + interrupt_before: u64, + interrupt_after: u64, + unbiased_before: u64, + unbiased_after: u64, + base_error_ns: u64, +) -> 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 = interrupt_after + .checked_sub(interrupt_before) + .and_then(|value| value.checked_mul(100)) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?; + let unbiased_width = unbiased_after + .checked_sub(unbiased_before) + .and_then(|value| value.checked_mul(100)) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?; + ensure!( + width.abs_diff(unbiased_width) <= SECOND_NS, + "TIME_NATIVE_CAPTURE_SUSPEND" + ); + let capture_error_ns = width + .checked_add(base_error_ns) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?; + ensure!( + capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS, + "TIME_NATIVE_CAPTURE_BUDGET" + ); + let wall_utc_ns = wall_filetime + .checked_sub(FILETIME_UNIX) + .and_then(|value| value.checked_mul(100)) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_WALL_RANGE"))? + .try_into()?; + Ok(Sample { + wall_utc_ns, + interrupt_ns: interrupt_after + .checked_mul(100) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?, + unbiased_ns: unbiased_after + .checked_mul(100) + .ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?, + capture_error_ns, + }) +} + +#[cfg(all(windows, feature = "system-helper"))] +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, Verifier, + }; + use serde::{Deserialize, Serialize}; + use std::{ + collections::BTreeMap, + io::Read, + path::Path, + sync::{Mutex, OnceLock}, + }; + + pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\time-attestation.json"; + const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem"; + 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 { + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetSystemTimePreciseAsFileTime(value: *mut u64); + fn QueryInterruptTimePrecise(value: *mut u64); + fn QueryUnbiasedInterruptTimePrecise(value: *mut u64); + } + let (mut ib, mut ia, mut ub, mut ua, mut wall) = (0, 0, 0, 0, 0); + // SAFETY: documented VOID kernel getters with valid aligned u64 + // outputs. Windows 10+ is required; no optional API fallback exists. + unsafe { + QueryInterruptTimePrecise(&mut ib); + QueryUnbiasedInterruptTimePrecise(&mut ub); + GetSystemTimePreciseAsFileTime(&mut wall); + QueryUnbiasedInterruptTimePrecise(&mut ua); + QueryInterruptTimePrecise(&mut ia); + } + bracket_sample(wall, ib, ia, ub, ua, base_error_ns) + } + fn observed(boot: Uuid, base_error_ns: u64) -> Result<(Sample, u64)> { + let mut state = process() + .lock() + .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; + let value = match capture(base_error_ns) { + Ok(value) => value, + Err(error) => { + state.invalidate(); + return Err(error); + } + }; + state.observe(boot, value)?; + Ok((value, state.epoch)) + } + + struct Pending { + owner: Uuid, + epoch: u64, + challenge: Challenge, + } + /// Own-process role proof, protected held configuration, private challenge + /// and native timers. No constructor accepts agent-reported helper times. + pub struct SignedClock { + verifier: Verifier, + own_process: PeerProof, + files: Vec, + config_sha256: String, + boot_id: Uuid, + connection_generation: u64, + base_error_ns: u64, + pending: Option, + } + impl SignedClock { + /// Connection generation is later confirmed by the independently + /// 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 (settings, mut files) = crate::helper_system::read_settings()?; + let own_pin = match role { + Role::Agent => &settings.agent, + Role::SystemHelper => &settings.helper, + }; + own_pin.validate(role == Role::SystemHelper)?; + ipc::require_self(own_pin)?; + let own_process = PeerProof::for_service( + own_pin, + // SAFETY: this getter takes no arguments and returns own PID. + unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessId() }, + )?; + let readers = vec![ + settings.agent.service_sid.clone(), + settings.helper.service_sid.clone(), + ]; + files.push(PinnedFile::open( + Path::new(PUBLIC_ROOT), + true, + &readers, + &[], + false, + )?); + let mut config_file = + PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?; + ensure!( + config_file.file.metadata()?.len() <= MAX_CONFIG_BYTES as u64, + "TIME_NATIVE_CONFIG_SIZE" + ); + let mut raw = Vec::new(); + (&mut config_file.file) + .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)?; + 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(&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 + .iter() + .map(|(id, key)| { + ensure!(digest(key), "TIME_NATIVE_PUBLIC_KEY"); + let raw = independent_time_key(key, &settings.binding.public_key_hex)?; + Ok((id.clone(), raw)) + }) + .collect::>>()?; + 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))?; + + // The existing fixed read-only native getter is independent in + // each process. It finishes BEFORE challenge/RTT timing begins. + let boot_id = Uuid::parse_str(&crate::native::boot_id().await?)?; + let context = Context { + tenant_id: settings.binding.tenant_id, + asset_id: settings.binding.asset_id, + agent_id: settings.binding.agent_id, + enrollment_generation: settings.binding.enrollment_generation, + assignment_generation: settings.binding.assignment_version, + connection_generation, + windows_boot_id: boot_id, + verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4), + role, + helper_image_sha256: (role == Role::SystemHelper) + .then(|| own_pin.binary_sha256.clone()), + binding_schema: 1, + }; + files.push(config_file); + let mut value = Self { + verifier: Verifier::new(context, pins)?, + own_process, + files, + config_sha256: hash(&raw), + boot_id, + connection_generation, + base_error_ns, + pending: None, + }; + value.recheck()?; + process() + .lock() + .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))? + .accept_connection(connection_generation)?; + observed(boot_id, base_error_ns)?; + Ok(value) + } + fn recheck(&mut self) -> Result<()> { + self.own_process.check()?; + for file in &mut self.files { + file.check()?; + } + let config = self.files.last_mut().context("TIME_NATIVE_CONFIG_HELD")?; + ensure!( + config.sha256()? == self.config_sha256, + "TIME_NATIVE_CONFIG_CHANGED" + ); + Ok(()) + } + pub fn begin(&mut self, connection_generation: u64) -> Result { + if connection_generation != self.connection_generation { + self.close(); + anyhow::bail!("TIME_NATIVE_CONNECTION_CHANGED"); + } + ensure!(self.pending.is_none(), "TIME_NATIVE_PENDING"); + self.recheck()?; + let mut state = process() + .lock() + .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; + state.require_connection(connection_generation)?; + let sample = match capture(self.base_error_ns) { + Ok(value) => value, + Err(error) => { + state.invalidate(); + return Err(error); + } + }; + state.observe(self.boot_id, sample)?; + let owner = Uuid::new_v4(); + let epoch = state.reserve(owner)?; + let challenge = match self.verifier.begin(sample) { + Ok(value) => value, + Err(error) => { + state.invalidate(); + return Err(error); + } + }; + let request = challenge.request().clone(); + self.pending = Some(Pending { + owner, + epoch, + challenge, + }); + Ok(request) + } + /// Call immediately after this verifier receives the complete bounded + /// response. The helper's caller supplies bytes only, never timestamps. + /// All failures consume the original request; no transparent retry. + pub fn complete( + &mut self, + bytes: &[u8], + consume: impl FnOnce(&Comparison) -> Result, + ) -> Result { + let pending = self.pending.take().context("TIME_NATIVE_NO_CHALLENGE")?; + let result = (|| { + let (received, epoch) = observed(self.boot_id, self.base_error_ns)?; + 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)?; + self.recheck()?; + let mut checked = None; + let interval = + self.verifier + .finish(pending.challenge, &signed, received, || { + let (sample, epoch) = observed(self.boot_id, self.base_error_ns)?; + ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED"); + checked = Some(sample); + Ok(sample) + })?; + let mut state = process() + .lock() + .map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?; + state.require_owner(pending.owner, pending.epoch)?; + state.active = None; + let comparison = Comparison { + interval, + wall_utc_ns: checked.context("TIME_NATIVE_FINAL_SAMPLE")?.wall_utc_ns, + }; + drop(state); + consume(&comparison) + })(); + if result.is_err() { + self.verifier.invalidate(); + if let Ok(mut state) = process().lock() + && state.active == Some(pending.owner) + { + state.invalidate(); + } + } + result + } + pub fn close(&mut self) { + self.verifier.invalidate(); + if let Some(pending) = self.pending.take() + && let Ok(mut state) = process().lock() + && state.active == Some(pending.owner) + { + state.invalidate(); + } + } + } + impl Drop for SignedClock { + fn drop(&mut self) { + self.close(); + } + } + + /// Borrowed only inside the completion callback, never returned as a + /// storable clock/lease/permit. Runtime callers must retain all job gates. + pub struct Comparison { + interval: Interval, + wall_utc_ns: i64, + } + impl Comparison { + pub fn interval(&self) -> &Interval { + &self.interval + } + pub fn wall_utc_ns(&self) -> i64 { + self.wall_utc_ns + } + } +} +#[cfg(all(windows, feature = "system-helper"))] +pub use installed::{CONFIG_PATH, Calibration, Comparison, Configuration, SignedClock}; + +#[cfg(test)] +mod tests { + use super::*; + fn sample(ns: u64) -> Sample { + Sample { + wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64, + interrupt_ns: 10_000_000_000 + ns, + unbiased_ns: 9_000_000_000 + ns, + capture_error_ns: 1_000_000, + } + } + #[test] + fn job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case() { + assert_eq!( + independent_time_key(&"ab".repeat(32), &"AB".repeat(32)) + .unwrap_err() + .to_string(), + "TIME_NATIVE_KEY_ROLE_REUSE" + ); + assert!(independent_time_key(&"ab".repeat(32), &"cd".repeat(32)).is_ok()); + assert!(independent_time_key(&"ab".repeat(32), "not-a-provisioned-job-key").is_err()); + } + #[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(); + 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()); + } + #[test] + fn retained_process_fence_rejects_old_challenge_and_boot_substitution() { + let boot = Uuid::new_v4(); + let owner = Uuid::new_v4(); + let mut state = Continuity::default(); + state.accept_configuration(4, "one-config").unwrap(); + state.accept_connection(3).unwrap(); + assert!(state.accept_configuration(3, "old-config").is_err()); + assert!(state.accept_configuration(4, "different-config").is_err()); + state.accept_configuration(4, "one-config").unwrap(); + + state.observe(boot, sample(0)).unwrap(); + let original_epoch = state.reserve(owner).unwrap(); + assert!(state.reserve(Uuid::new_v4()).is_err()); + let mut resumed = sample(2_000_000_000); + resumed.unbiased_ns = 9_000_000_000; + assert!(state.observe(boot, resumed).is_err()); + assert!(state.require_owner(owner, original_epoch).is_err()); + // A caller reconstructing its verifier still sees this retained state. + state.observe(boot, resumed).unwrap(); + let next = Uuid::new_v4(); + let epoch = state.reserve(next).unwrap(); + assert!(epoch > original_epoch); + state.require_owner(next, epoch).unwrap(); + state.accept_connection(4).unwrap(); + assert!(state.require_owner(next, epoch).is_err()); + assert!(state.require_connection(3).is_err()); + assert!(state.accept_connection(3).is_err()); + state.require_connection(4).unwrap(); + assert!(state.observe(Uuid::new_v4(), resumed).is_err()); + assert!(state.require_owner(next, epoch).is_err()); + state.epoch = u64::MAX; + state.invalidate(); + assert!(state.exhausted); + state.invalidate(); + assert!(state.exhausted); + assert!(state.reserve(Uuid::new_v4()).is_err()); + } +} diff --git a/crates/time-attestation/Cargo.toml b/crates/time-attestation/Cargo.toml new file mode 100644 index 0000000..15f7461 --- /dev/null +++ b/crates/time-attestation/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "rmm-time-attestation" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +ed25519-dalek = "=2.2.0" +hex.workspace = true +rand.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +uuid.workspace = true diff --git a/crates/time-attestation/src/lib.rs b/crates/time-attestation/src/lib.rs new file mode 100644 index 0000000..7951e37 --- /dev/null +++ b/crates/time-attestation/src/lib.rs @@ -0,0 +1,555 @@ +//! Independent online time comparison, never a sync lease or execution permit. +//! Nanoseconds are signed UTC Unix ns, intervals are unsigned ns. Callers must +//! hold their own native clock observations and protected context/pins. +use anyhow::{Result, ensure}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use uuid::Uuid; + +pub const ENDPOINT: &str = "https://discovery.ease-technologies.de/agent/v1/time-attestation"; +pub const MAX_RTT_NS: u64 = 1_000_000_000; +pub const MAX_RECEIVED_AGE_NS: u64 = 100_000_000; +pub const MAX_CAPTURE_ERROR_NS: u64 = 50_000_000; +pub const MAX_SERVER_ERROR_NS: u64 = 500_000_000; +pub const MAX_SYNC_AGE_NS: u64 = 3_600_000_000_000; +const DOMAIN: &[u8] = b"RMM-TIME-ATTESTATION/v1\0"; +const MAX_BYTES: usize = 8192; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Role { + Agent, + SystemHelper, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Context { + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub enrollment_generation: u64, + pub assignment_generation: u64, + pub connection_generation: u64, + pub windows_boot_id: Uuid, + pub verifier_incarnation: Uuid, + pub role: Role, + pub helper_image_sha256: Option, + pub binding_schema: u32, +} +impl Context { + pub fn validate(&self) -> Result<()> { + ensure!( + [ + self.tenant_id, + self.asset_id, + self.agent_id, + self.windows_boot_id, + self.verifier_incarnation + ] + .iter() + .all(|v| !v.is_nil()), + "TIME_CONTEXT_ID" + ); + ensure!( + self.enrollment_generation > 0 + && self.assignment_generation > 0 + && self.connection_generation > 0 + && self.binding_schema == 1, + "TIME_CONTEXT_GENERATION" + ); + match self.role { + Role::Agent => ensure!( + self.helper_image_sha256.is_none(), + "TIME_AGENT_HELPER_IMAGE" + ), + Role::SystemHelper => { + exact_hex(self.helper_image_sha256.as_deref().unwrap_or(""), 32)?; + } + } + Ok(()) + } +} +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Request { + pub version: u32, + pub endpoint: String, + pub nonce: String, + pub context: Context, +} +impl Request { + pub fn validate(&self) -> Result<()> { + ensure!( + self.version == 1 && self.endpoint == ENDPOINT, + "TIME_REQUEST_PROFILE" + ); + exact_hex(&self.nonce, 32)?; + self.context.validate() + } + pub fn sha256(&self) -> Result { + self.validate()?; + Ok(hex::encode(Sha256::digest(serde_json::to_vec(self)?))) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Payload { + pub version: u32, + pub request_sha256: String, + pub server_instance: Uuid, + pub server_boot_id: Uuid, + pub key_id: String, + pub key_generation: u64, + pub captured_utc_ns: i64, + pub server_error_ns: u64, + pub source_sync_age_ns: u64, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SignedAttestation { + /// Exact canonical JSON bytes (UTF-8); verification never normalizes input. + pub payload: String, + pub signature_hex: String, +} +fn exact_hex(value: &str, bytes: usize) -> Result<()> { + ensure!( + value.len() == bytes * 2 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "TIME_HEX_FORMAT" + ); + Ok(()) +} +fn validate_payload(p: &Payload) -> Result<()> { + ensure!( + p.version == 1 && !p.server_instance.is_nil() && !p.server_boot_id.is_nil(), + "TIME_SERVER_CONTEXT" + ); + ensure!( + !p.key_id.is_empty() + && p.key_id.len() <= 64 + && p.key_id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + && p.key_generation > 0, + "TIME_KEY_CONTEXT" + ); + exact_hex(&p.request_sha256, 32)?; + ensure!( + p.captured_utc_ns > 0 + && p.server_error_ns <= MAX_SERVER_ERROR_NS + && p.source_sync_age_ns <= MAX_SYNC_AGE_NS, + "TIME_SERVER_QUALITY" + ); + Ok(()) +} +/// Only server code which has independently qualified the native source may +/// construct/sign this payload. This codec is not a provider qualification. +pub fn sign(payload: &Payload, key: &SigningKey) -> Result { + validate_payload(payload)?; + let raw = serde_json::to_string(payload)?; + let mut message = DOMAIN.to_vec(); + message.extend_from_slice(raw.as_bytes()); + Ok(SignedAttestation { + payload: raw, + signature_hex: hex::encode(key.sign(&message).to_bytes()), + }) +} +/// Loaded through the verifier's protected configuration, never an HTTP reply. +pub struct Pins { + generation: u64, + server_instance: Uuid, + keys: BTreeMap, +} +impl Pins { + pub fn new( + generation: u64, + server_instance: Uuid, + keys: BTreeMap, + ) -> Result { + ensure!( + generation > 0 && !server_instance.is_nil() && !keys.is_empty() && keys.len() <= 8, + "TIME_PINS" + ); + let keys = keys + .into_iter() + .map(|(id, raw)| Ok((id, VerifyingKey::from_bytes(&raw)?))) + .collect::>()?; + Ok(Self { + generation, + server_instance, + keys, + }) + } +} +/// A native, locally captured observation; ns counters share one process's OS +/// clock domains. capture_error_ns must come from platform qualification. +#[derive(Clone, Copy, Debug)] +pub struct Sample { + pub wall_utc_ns: i64, + pub interrupt_ns: u64, + pub unbiased_ns: u64, + pub capture_error_ns: u64, +} +impl Sample { + fn validate(self) -> Result<()> { + ensure!( + self.wall_utc_ns > 0 && self.capture_error_ns <= MAX_CAPTURE_ERROR_NS, + "TIME_LOCAL_SAMPLE" + ); + Ok(()) + } +} +/// Opaque, noncloneable request authority: one attempt consumes it even when +/// signature/quality checks fail. A transported Request alone is no authority. +pub struct Challenge { + request: Request, + begin: Sample, + epoch: u64, + verifier_id: Uuid, +} +impl Challenge { + pub fn request(&self) -> &Request { + &self.request + } +} +/// Lives with the verifier process; callers must not reconstruct it to clear a +/// discontinuity. Native adapters additionally preserve the process-wide fence. +pub struct Verifier { + context: Context, + pins: Pins, + previous: Option, + epoch: u64, + pending_nonce: Option, + verifier_id: Uuid, +} +impl Verifier { + pub fn new(context: Context, pins: Pins) -> Result { + context.validate()?; + Ok(Self { + context, + pins, + previous: None, + epoch: 1, + pending_nonce: None, + verifier_id: Uuid::new_v4(), + }) + } + pub fn invalidate(&mut self) { + self.pending_nonce = None; + self.epoch = if self.epoch == 0 { + 0 + } else { + self.epoch.checked_add(1).unwrap_or(0) + }; + } + pub fn observe(&mut self, sample: Sample) -> Result<()> { + if let Err(error) = sample.validate() { + self.invalidate(); + return Err(error); + } + let continuous = self.previous.is_none_or(|p| { + match ( + sample.wall_utc_ns.checked_sub(p.wall_utc_ns), + sample.interrupt_ns.checked_sub(p.interrupt_ns), + sample.unbiased_ns.checked_sub(p.unbiased_ns), + ) { + (Some(w), Some(i), Some(u)) if w >= 0 => { + (w as u64).abs_diff(i) <= MAX_RTT_NS && i.abs_diff(u) <= MAX_RTT_NS + } + _ => false, + } + }); + self.previous = Some(sample); + if !continuous { + self.invalidate(); + } + ensure!(continuous, "TIME_DISCONTINUITY"); + Ok(()) + } + pub fn begin(&mut self, sample: Sample) -> Result { + self.observe(sample)?; + ensure!( + self.epoch > 0 && self.pending_nonce.is_none(), + "TIME_CHALLENGE_OUTSTANDING_OR_EXHAUSTED" + ); + let nonce: [u8; 32] = rand::random(); + let request = Request { + version: 1, + endpoint: ENDPOINT.into(), + nonce: hex::encode(nonce), + context: self.context.clone(), + }; + request.validate()?; + self.pending_nonce = Some(request.nonce.clone()); + Ok(Challenge { + request, + begin: sample, + epoch: self.epoch, + verifier_id: self.verifier_id, + }) + } + pub fn finish( + &mut self, + challenge: Challenge, + signed: &SignedAttestation, + received: Sample, + capture_checked: impl FnOnce() -> Result, + ) -> Result { + let owned = challenge.verifier_id == self.verifier_id + && self.pending_nonce.as_deref() == Some(challenge.request.nonce.as_str()) + && challenge.epoch == self.epoch + && challenge.request.context == self.context; + self.pending_nonce = None; + ensure!(owned, "TIME_CHALLENGE_NOT_OWNED"); + self.observe(received)?; + ensure!(signed.payload.len() <= MAX_BYTES, "TIME_PAYLOAD_LIMIT"); + let p: Payload = serde_json::from_str(&signed.payload)?; + ensure!( + serde_json::to_string(&p)? == signed.payload, + "TIME_NONCANONICAL_PAYLOAD" + ); + validate_payload(&p)?; + ensure!( + p.request_sha256 == challenge.request.sha256()? + && p.server_instance == self.pins.server_instance + && p.key_generation == self.pins.generation, + "TIME_BINDING" + ); + let key = self + .pins + .keys + .get(&p.key_id) + .ok_or_else(|| anyhow::anyhow!("TIME_KEY_NOT_PINNED"))?; + exact_hex(&signed.signature_hex, 64)?; + let signature = Signature::from_slice(&hex::decode(&signed.signature_hex)?)?; + let mut message = DOMAIN.to_vec(); + message.extend_from_slice(signed.payload.as_bytes()); + key.verify_strict(&message, &signature)?; + let checked = capture_checked()?; + self.observe(checked)?; + let elapsed = checked + .interrupt_ns + .checked_sub(challenge.begin.interrupt_ns) + .ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?; + let age = checked + .interrupt_ns + .checked_sub(received.interrupt_ns) + .ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?; + ensure!( + elapsed <= MAX_RTT_NS && age <= MAX_RECEIVED_AGE_NS, + "TIME_STALE_RESPONSE" + ); + // Include every local capture budget conservatively, never RTT/2. + let delta = challenge + .begin + .capture_error_ns + .checked_add(received.capture_error_ns) + .and_then(|d| d.checked_add(checked.capture_error_ns)) + .ok_or_else(|| anyhow::anyhow!("TIME_ERROR_OVERFLOW"))?; + ensure!(delta <= MAX_CAPTURE_ERROR_NS, "TIME_CAPTURE_BUDGET"); + ensure!( + p.source_sync_age_ns + .checked_add(elapsed) + .and_then(|v| v.checked_add(delta)) + .is_some_and(|v| v <= MAX_SYNC_AGE_NS), + "TIME_SOURCE_AGE_AT_CHECK" + ); + let lower = i128::from(p.captured_utc_ns) - i128::from(p.server_error_ns); + let upper = i128::from(p.captured_utc_ns) + + i128::from(p.server_error_ns) + + i128::from(elapsed) + + i128::from(delta); + let wall = i128::from(checked.wall_utc_ns); + ensure!( + (wall - lower).abs().max((wall - upper).abs()) <= 2_000_000_000, + "TIME_LOCAL_WALL_OUTSIDE_BOUND" + ); + Ok(Interval { + lower_utc_ns: lower.try_into()?, + upper_utc_ns: upper.try_into()?, + }) + } +} +/// Fresh result only. Adapters must recapture/reverify for later use; this type +/// carries no lease, serialization or execution authorization. +#[derive(Debug)] +pub struct Interval { + lower_utc_ns: i64, + upper_utc_ns: i64, +} +impl Interval { + pub fn lower_utc_ns(&self) -> i64 { + self.lower_utc_ns + } + pub fn upper_utc_ns(&self) -> i64 { + self.upper_utc_ns + } + pub fn allows_start(&self, not_before_ns: i64, start_before_ns: i64) -> bool { + self.lower_utc_ns >= not_before_ns && self.upper_utc_ns < start_before_ns + } +} + +#[cfg(test)] +mod tests { + use super::*; + const T: i64 = 1_800_000_000_000_000_000; + fn sample(elapsed: u64) -> Sample { + Sample { + wall_utc_ns: T + elapsed as i64, + interrupt_ns: 10_000_000_000 + elapsed, + unbiased_ns: 9_000_000_000 + elapsed, + capture_error_ns: 1_000_000, + } + } + fn context(role: Role) -> Context { + Context { + tenant_id: Uuid::new_v4(), + asset_id: Uuid::new_v4(), + agent_id: Uuid::new_v4(), + enrollment_generation: 1, + assignment_generation: 1, + connection_generation: 2, + windows_boot_id: Uuid::new_v4(), + verifier_incarnation: Uuid::new_v4(), + role, + helper_image_sha256: (role == Role::SystemHelper).then(|| "ab".repeat(32)), + binding_schema: 1, + } + } + fn fixture(context: Context) -> (Verifier, SigningKey, Uuid) { + let key = SigningKey::from_bytes(&rand::random()); + let server = Uuid::new_v4(); + let pins = Pins::new( + 4, + server, + BTreeMap::from([("time1".into(), key.verifying_key().to_bytes())]), + ) + .unwrap(); + (Verifier::new(context, pins).unwrap(), key, server) + } + fn reply(c: &Challenge, key: &SigningKey, server: Uuid) -> SignedAttestation { + sign( + &Payload { + version: 1, + request_sha256: c.request().sha256().unwrap(), + server_instance: server, + server_boot_id: Uuid::new_v4(), + key_id: "time1".into(), + key_generation: 4, + captured_utc_ns: T + 20_000_000, + server_error_ns: 10_000_000, + source_sync_age_ns: 100_000_000_000, + }, + key, + ) + .unwrap() + } + #[test] + fn signed_roundtrip_uses_entire_rtt_and_strict_deadline_interval() { + let (mut v, key, server) = fixture(context(Role::SystemHelper)); + let c = v.begin(sample(0)).unwrap(); + let signed = reply(&c, &key, server); + let result = v + .finish(c, &signed, sample(70_000_000), || Ok(sample(80_000_000))) + .unwrap(); + assert_eq!(result.lower_utc_ns(), T + 10_000_000); + assert_eq!(result.upper_utc_ns(), T + 113_000_000); + assert!(result.allows_start(T, T + 114_000_000)); + assert!(!result.allows_start(T, T + 113_000_000)); + assert!(!result.allows_start(T + 11_000_000, T + 114_000_000)); + } + #[test] + fn tampering_wrong_role_nonce_key_and_delays_never_open() { + for mutation in 0..7 { + let (mut v, key, server) = fixture(context(Role::Agent)); + let c = v.begin(sample(0)).unwrap(); + let mut signed = reply(&c, &key, server); + let mut received = sample(70_000_000); + let mut checked = sample(80_000_000); + match mutation { + 0 => { + let mut bytes = hex::decode(&signed.signature_hex).unwrap(); + bytes[0] ^= 1; + signed.signature_hex = hex::encode(bytes); + } + 1 => { + let mut p: Payload = serde_json::from_str(&signed.payload).unwrap(); + p.request_sha256 = "cd".repeat(32); + signed = sign(&p, &key).unwrap(); + } + 2 => { + let other = SigningKey::from_bytes(&rand::random()); + signed = reply(&c, &other, server); + } + 3 => checked = sample(MAX_RTT_NS + 1), + 4 => { + received = sample(10_000_000); + checked = sample(110_000_001); + } + 5 => { + let mut p: Payload = serde_json::from_str(&signed.payload).unwrap(); + p.key_generation = 3; + signed = sign(&p, &key).unwrap(); + } + _ => signed.payload.push(' '), + } + assert!( + v.finish(c, &signed, received, || Ok(checked)).is_err(), + "mutation {mutation}" + ); + assert!(v.pending_nonce.is_none()); + } + let ctx = context(Role::Agent); + let (mut a, key, server) = fixture(ctx.clone()); + let (mut b, _, _) = fixture(ctx); + let ca = a.begin(sample(0)).unwrap(); + let signed = reply(&ca, &key, server); + let _cb = b.begin(sample(0)).unwrap(); + assert!( + b.finish(ca, &signed, sample(20_000_000), || Ok(sample(30_000_000))) + .is_err() + ); + } + #[test] + fn foreign_reply_cannot_reenable_an_older_own_challenge() { + let (mut a, key_a, server_a) = fixture(context(Role::Agent)); + let (mut b, key_b, server_b) = fixture(context(Role::Agent)); + let ca = a.begin(sample(0)).unwrap(); + let reply_a = reply(&ca, &key_a, server_a); + let old_b = b.begin(sample(0)).unwrap(); + let old_reply_b = reply(&old_b, &key_b, server_b); + assert!( + b.finish(ca, &reply_a, sample(10_000_000), || Ok(sample(20_000_000))) + .is_err() + ); + let _current_b = b.begin(sample(30_000_000)).unwrap(); + assert!( + b.finish(old_b, &old_reply_b, sample(40_000_000), || Ok(sample( + 50_000_000 + ))) + .is_err() + ); + } + #[test] + fn discontinuity_invalidates_outstanding_and_requires_new_challenge() { + let (mut v, key, server) = fixture(context(Role::SystemHelper)); + let c = v.begin(sample(0)).unwrap(); + let signed = reply(&c, &key, server); + let mut resumed = sample(2_000_000_000); + resumed.unbiased_ns = 9_000_000_000; + assert!(v.observe(resumed).is_err()); + assert!(v.finish(c, &signed, resumed, || Ok(resumed)).is_err()); + // A new post-discontinuity challenge is permitted, no old nonce reuse. + let c = v.begin(resumed).unwrap(); + let mut p: Payload = serde_json::from_str(&reply(&c, &key, server).payload).unwrap(); + p.captured_utc_ns = resumed.wall_utc_ns; + let signed = sign(&p, &key).unwrap(); + assert!(v.finish(c, &signed, resumed, || Ok(resumed)).is_ok()); + } +} diff --git a/crates/time-source-linux/Cargo.toml b/crates/time-source-linux/Cargo.toml new file mode 100644 index 0000000..93a3627 --- /dev/null +++ b/crates/time-source-linux/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rmm-time-source-linux" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +libc = "0.2" +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +hex.workspace = true +uuid.workspace = true diff --git a/crates/time-source-linux/src/lib.rs b/crates/time-source-linux/src/lib.rs new file mode 100644 index 0000000..56ba278 --- /dev/null +++ b/crates/time-source-linux/src/lib.rs @@ -0,0 +1,58 @@ +//! Native, read-only Chrony + Linux kernel quality observation. +//! This is a source sample, never a job grant or a clock-setting interface. +#[cfg(target_os = "linux")] +mod native; +#[cfg(any(target_os = "linux", test))] +mod tracking; +#[cfg(target_os = "linux")] +pub use native::NativeTimeSource; + +use uuid::Uuid; + +/// Constructible only by the native authenticated observation. Consumers must +/// account for all further elapsed time before signing a response; no holdover. +#[derive(Debug)] +pub struct QualifiedSample { + captured_utc_ns: i64, + server_error_ns: u64, + source_sync_age_ns: u64, + server_boot_id: Uuid, + captured_monotonic_ns: u64, + sampled_boottime_ns: u64, + kernel_state: i32, +} +impl QualifiedSample { + pub fn captured_utc_ns(&self) -> i64 { + self.captured_utc_ns + } + pub fn server_error_ns(&self) -> u64 { + self.server_error_ns + } + pub fn source_sync_age_ns(&self) -> u64 { + self.source_sync_age_ns + } + pub fn server_boot_id(&self) -> Uuid { + self.server_boot_id + } + pub fn captured_monotonic_ns(&self) -> u64 { + self.captured_monotonic_ns + } + pub fn sampled_boottime_ns(&self) -> u64 { + self.sampled_boottime_ns + } + pub fn kernel_state(&self) -> i32 { + self.kernel_state + } +} + +#[cfg(not(target_os = "linux"))] +pub struct NativeTimeSource; +#[cfg(not(target_os = "linux"))] +impl NativeTimeSource { + pub fn open() -> anyhow::Result { + anyhow::bail!("TIME_SOURCE_LINUX_REQUIRED") + } + pub fn sample(&mut self) -> anyhow::Result { + anyhow::bail!("TIME_SOURCE_LINUX_REQUIRED") + } +} diff --git a/crates/time-source-linux/src/native.rs b/crates/time-source-linux/src/native.rs new file mode 100644 index 0000000..21f23d8 --- /dev/null +++ b/crates/time-source-linux/src/native.rs @@ -0,0 +1,868 @@ +use crate::{QualifiedSample, tracking}; +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::ffi::CString; +use std::fs::File; +use std::io::Read; +use std::mem::{self, size_of, size_of_val}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::fs::MetadataExt; +use uuid::Uuid; + +const PIN: &str = "/etc/rmm-time-source/chrony-pin.json"; +const DAEMON: &str = "/usr/sbin/chronyd"; +const SERVER_DIR: &str = "/run/chrony"; +const SERVER: &str = "/run/chrony/chronyd.sock"; +const CLIENT_DIR: &str = "/run/rmm-time-source/clients"; +const QUERY_NS: u64 = 100_000_000; +const CAPTURE_NS: u64 = 10_000_000; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Pin { + schema_version: u32, + daemon_pid: i32, + daemon_birth_ticks: u64, + daemon_uid: u32, + daemon_gid: u32, + daemon_image_sha256: String, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Identity { + dev: u64, + ino: u64, + uid: u32, + gid: u32, + mode: u32, + links: u64, +} +fn identity(fd: RawFd) -> Result { + let mut st = mem::MaybeUninit::::uninit(); + // SAFETY: fstat initializes the supplied stat on success. + ensure!( + unsafe { libc::fstat(fd, st.as_mut_ptr()) } == 0, + "TIME_FSTAT" + ); + let st = unsafe { st.assume_init() }; + Ok(Identity { + dev: st.st_dev, + ino: st.st_ino, + uid: st.st_uid, + gid: st.st_gid, + mode: st.st_mode, + links: st.st_nlink, + }) +} +fn cstr(value: &str) -> Result { + Ok(CString::new(value)?) +} +fn fd_result(value: i32) -> Result { + if value < 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: every caller passes a newly allocated descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(value) }) +} +fn openat(dir: RawFd, name: &str, flags: i32) -> Result { + let name = cstr(name)?; + // SAFETY: name is NUL terminated, dir remains held by the caller. + fd_result(unsafe { + libc::openat( + dir, + name.as_ptr(), + flags | libc::O_CLOEXEC | libc::O_NOFOLLOW, + ) + }) +} +fn open_dir(path: &str, chrony: Option<(u32, u32)>) -> Result { + ensure!( + path.starts_with('/') && !path.contains(".."), + "TIME_FIXED_DIRECTORY" + ); + let slash = cstr("/")?; + let mut fd = fd_result(unsafe { + libc::open( + slash.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW, + ) + })?; + let root = identity(fd.as_raw_fd())?; + ensure!( + root.uid == 0 && root.mode & libc::S_IFMT == libc::S_IFDIR && root.mode & 0o022 == 0, + "TIME_ROOT_DIRECTORY" + ); + let parts: Vec<_> = path.split('/').filter(|v| !v.is_empty()).collect(); + for (index, part) in parts.iter().enumerate() { + fd = openat(fd.as_raw_fd(), part, libc::O_RDONLY | libc::O_DIRECTORY)?; + let m = identity(fd.as_raw_fd())?; + // The daemon-owned /run/chrony leaf is the sole permitted non-root owner. + let daemon_leaf = path == SERVER_DIR + && index + 1 == parts.len() + && chrony.is_some_and(|(uid, gid)| m.uid == uid && m.gid == gid); + ensure!( + m.mode & libc::S_IFMT == libc::S_IFDIR + && (m.uid == 0 || daemon_leaf) + && m.mode & 0o022 == 0, + "TIME_PROTECTED_DIRECTORY" + ); + } + Ok(fd) +} +fn bound_dir(path: &str, held: &OwnedFd, chrony: Option<(u32, u32)>) -> Result<()> { + let current = open_dir(path, chrony)?; + ensure!( + identity(current.as_raw_fd())? == identity(held.as_raw_fd())?, + "TIME_DIRECTORY_REPLACED" + ); + Ok(()) +} +fn read_bounded(fd: OwnedFd, limit: usize) -> Result> { + let mut raw = Vec::new(); + File::from(fd) + .take((limit + 1) as u64) + .read_to_end(&mut raw)?; + ensure!(raw.len() <= limit, "TIME_READ_BOUND"); + Ok(raw) +} +fn pin() -> Result { + let dir = open_dir("/etc/rmm-time-source", None)?; + let fd = openat(dir.as_raw_fd(), "chrony-pin.json", libc::O_RDONLY)?; + let m = identity(fd.as_raw_fd())?; + ensure!( + m.uid == 0 + && m.mode & libc::S_IFMT == libc::S_IFREG + && m.mode & 0o7777 == 0o600 + && m.links == 1, + "TIME_PIN_PROTECTION" + ); + let before = File::from(fd.try_clone()?).metadata()?; + let raw = read_bounded(fd.try_clone()?, 4096)?; + let after = File::from(fd.try_clone()?).metadata()?; + ensure!( + before.dev() == after.dev() + && before.ino() == after.ino() + && before.len() == after.len() + && before.mtime_nsec() == after.mtime_nsec() + && before.mtime() == after.mtime() + && before.ctime_nsec() == after.ctime_nsec() + && before.ctime() == after.ctime(), + "TIME_PIN_CHANGED" + ); + let p: Pin = serde_json::from_slice(&raw)?; + ensure!( + p.schema_version == 1 + && p.daemon_pid > 1 + && p.daemon_birth_ticks > 0 + && p.daemon_image_sha256.len() == 64 + && p.daemon_image_sha256 + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "TIME_PIN_SCHEMA" + ); + bound_dir("/etc/rmm-time-source", &dir, None)?; + let current = openat(dir.as_raw_fd(), "chrony-pin.json", libc::O_RDONLY)?; + ensure!( + identity(fd.as_raw_fd())? == identity(current.as_raw_fd())?, + "TIME_PIN_REPLACED" + ); + Ok(p) +} +fn digest(fd: &OwnedFd) -> Result { + let before = File::from(fd.try_clone()?).metadata()?; + ensure!( + before.is_file() + && before.uid() == 0 + && before.mode() & 0o022 == 0 + && before.nlink() == 1 + && before.len() <= 16 * 1024 * 1024, + "TIME_DAEMON_IMAGE_PROTECTED" + ); + let mut hasher = Sha256::new(); + let mut total = 0; + let mut buf = [0u8; 16384]; + // pread avoids shared seek offsets in retained descriptors. + loop { + let got = unsafe { libc::pread(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), total) }; + ensure!(got >= 0, "TIME_IMAGE_READ"); + if got == 0 { + break; + } + total += i64::try_from(got)?; + ensure!(total <= 16 * 1024 * 1024, "TIME_IMAGE_BOUND"); + hasher.update(&buf[..got as usize]); + } + let after = File::from(fd.try_clone()?).metadata()?; + ensure!( + before.len() == total as u64 + && before.len() == after.len() + && before.dev() == after.dev() + && before.ino() == after.ino() + && before.mtime() == after.mtime() + && before.mtime_nsec() == after.mtime_nsec() + && before.ctime() == after.ctime() + && before.ctime_nsec() == after.ctime_nsec(), + "TIME_IMAGE_CHANGED" + ); + Ok(hex::encode(hasher.finalize())) +} +struct Daemon { + pin: Pin, + proc: OwnedFd, + image: OwnedFd, + pidfd: OwnedFd, + image_id: Identity, +} +impl Daemon { + fn open(pin: Pin) -> Result { + let proc = openat( + libc::AT_FDCWD, + &format!("/proc/{}", pin.daemon_pid), + libc::O_RDONLY | libc::O_DIRECTORY, + )?; + let pidfd = + fd_result(unsafe { libc::syscall(libc::SYS_pidfd_open, pin.daemon_pid, 0) } as i32)?; + let dir = open_dir("/usr/sbin", None)?; + let image = openat(dir.as_raw_fd(), "chronyd", libc::O_RDONLY)?; + let image_id = identity(image.as_raw_fd())?; + let value = Self { + pin, + proc, + image, + pidfd, + image_id, + }; + value.verify()?; + Ok(value) + } + fn exe(&self) -> Result { + let name = cstr("exe")?; + // /proc/PID/exe is intentionally a kernel symlink; procdir is retained. + fd_result(unsafe { + libc::openat( + self.proc.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_CLOEXEC, + ) + }) + } + fn verify(&self) -> Result<()> { + let mut poll = libc::pollfd { + fd: self.pidfd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + ensure!( + unsafe { libc::poll(&mut poll, 1, 0) } == 0 && poll.revents == 0, + "TIME_DAEMON_EXITED" + ); + let first = self.exe()?; + ensure!( + identity(first.as_raw_fd())? == self.image_id, + "TIME_DAEMON_EXEC_CHANGED" + ); + let stat = String::from_utf8(read_bounded( + openat(self.proc.as_raw_fd(), "stat", libc::O_RDONLY)?, + 8192, + )?)?; + let rest = stat.rsplit_once(") ").context("TIME_PROC_STAT")?.1; + ensure!( + rest.split_whitespace() + .nth(19) + .context("TIME_PROC_BIRTH")? + .parse::()? + == self.pin.daemon_birth_ticks, + "TIME_DAEMON_BIRTH" + ); + let status = String::from_utf8(read_bounded( + openat(self.proc.as_raw_fd(), "status", libc::O_RDONLY)?, + 16384, + )?)?; + for (label, expected) in [("Uid:", self.pin.daemon_uid), ("Gid:", self.pin.daemon_gid)] { + let line = status + .lines() + .find(|v| v.starts_with(label)) + .context("TIME_PROC_CREDENTIALS")?; + let ids: Vec = line + .split_whitespace() + .skip(1) + .map(str::parse) + .collect::>()?; + ensure!(ids == [expected; 4], "TIME_DAEMON_ACCOUNT"); + } + ensure!( + digest(&self.image)? == self.pin.daemon_image_sha256 + && digest(&first)? == self.pin.daemon_image_sha256, + "TIME_DAEMON_IMAGE" + ); + let fixed = openat(libc::AT_FDCWD, DAEMON, libc::O_RDONLY)?; + ensure!( + identity(fixed.as_raw_fd())? == self.image_id + && identity(self.exe()?.as_raw_fd())? == self.image_id, + "TIME_DAEMON_IMAGE_REPLACED" + ); + ensure!( + unsafe { libc::poll(&mut poll, 1, 0) } == 0 && poll.revents == 0, + "TIME_DAEMON_EXITED" + ); + Ok(()) + } +} + +#[derive(Clone, Copy)] +struct Capture { + mono: u64, + end: u64, + boot: u64, + utc: i64, +} +fn clock(id: libc::clockid_t) -> Result { + let mut ts = mem::MaybeUninit::::uninit(); + ensure!( + unsafe { libc::clock_gettime(id, ts.as_mut_ptr()) } == 0, + "TIME_CLOCK_GETTIME" + ); + let ts = unsafe { ts.assume_init() }; + ensure!( + ts.tv_sec >= 0 && (0..1_000_000_000).contains(&ts.tv_nsec), + "TIME_CLOCK_RANGE" + ); + Ok(i128::from(ts.tv_sec) * 1_000_000_000 + i128::from(ts.tv_nsec)) +} +fn capture() -> Result { + let mono = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?; + let boot = u64::try_from(clock(libc::CLOCK_BOOTTIME)?)?; + let utc = i64::try_from(clock(libc::CLOCK_REALTIME)?)?; + let end = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?; + ensure!( + end >= mono && end - mono <= CAPTURE_NS && utc > 0, + "TIME_CAPTURE_BOUND" + ); + Ok(Capture { + mono, + end, + boot, + utc, + }) +} +#[derive(Clone, Copy)] +struct Kernel { + state: i32, + maxerror_ns: u64, +} +fn kernel() -> Result { + let mut tx: libc::timex = unsafe { mem::zeroed() }; // modes=0: query only, never set time. + let state = unsafe { libc::adjtimex(&mut tx) }; + ensure!( + (0..=4).contains(&state) + && tx.status & (libc::STA_UNSYNC | libc::STA_CLOCKERR) == 0 + && (0..=500_000).contains(&tx.maxerror), + "TIME_KERNEL_UNQUALIFIED" + ); + Ok(Kernel { + state, + maxerror_ns: u64::try_from(tx.maxerror)? + .checked_mul(1000) + .context("TIME_KERNEL_OVERFLOW")?, + }) +} +fn elapsed(before: Capture, after: Capture) -> Result { + ensure!( + after.mono >= before.end && after.boot >= before.boot && after.utc >= before.utc, + "TIME_CLOCK_BACKWARD" + ); + let span = after + .end + .checked_sub(before.mono) + .context("TIME_MONOTONIC_OVERFLOW")?; + ensure!(span <= QUERY_NS, "TIME_SOURCE_TOTAL_TIMEOUT"); + let mono = after.mono - before.mono; + let boot = after.boot - before.boot; + let wall = u64::try_from(after.utc - before.utc)?; + let tolerance = (before.end - before.mono) + (after.end - after.mono); + ensure!( + mono.abs_diff(boot) <= tolerance && mono.abs_diff(wall) <= tolerance, + "TIME_SOURCE_DISCONTINUITY" + ); + Ok(span) +} +fn boot_id() -> Result { + let raw = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?; + let id = Uuid::parse_str(raw.trim())?; + ensure!(!id.is_nil(), "TIME_BOOT_ID"); + Ok(id) +} + +fn socket_identity(dir: RawFd, name: &str) -> Result { + let name = cstr(name)?; + let mut st = mem::MaybeUninit::::uninit(); + ensure!( + unsafe { + libc::fstatat( + dir, + name.as_ptr(), + st.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } == 0, + "TIME_SOCKET_STAT" + ); + let st = unsafe { st.assume_init() }; + Ok(Identity { + dev: st.st_dev, + ino: st.st_ino, + uid: st.st_uid, + gid: st.st_gid, + mode: st.st_mode, + links: st.st_nlink, + }) +} +fn address(path: &str) -> Result<(libc::sockaddr_un, libc::socklen_t)> { + let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() }; + addr.sun_family = libc::AF_UNIX as _; + ensure!(path.len() < addr.sun_path.len(), "TIME_SOCKET_PATH_BOUND"); + for (dst, src) in addr.sun_path.iter_mut().zip(path.bytes()) { + *dst = src as _; + } + Ok(( + addr, + (mem::offset_of!(libc::sockaddr_un, sun_path) + path.len() + 1) as _, + )) +} +struct Client { + fd: OwnedFd, + dir: OwnedFd, + name: String, + own: Option, +} +impl Client { + fn open(gid: u32) -> Result { + let dir = open_dir(CLIENT_DIR, None)?; + let d = identity(dir.as_raw_fd())?; + ensure!( + d.uid == 0 && d.gid == gid && d.mode & 0o7777 == 0o710, + "TIME_CLIENT_DIRECTORY_PROFILE" + ); + ensure!( + unsafe { libc::flock(dir.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, + "TIME_CLIENT_SINGLE_OWNER" + ); + // A leftover from an unknown cleanup blocks all future instances. Only + // an operator may investigate it; no automatic deletion or new UUID loop. + let mut entries = std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd()))?; + ensure!(entries.next().is_none(), "TIME_CLIENT_DIRECTORY_NOT_EMPTY"); + let fd = fd_result(unsafe { + libc::socket( + libc::AF_UNIX, + libc::SOCK_DGRAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, + 0, + ) + })?; + let name = format!("tracking-{}.sock", Uuid::new_v4().simple()); + let mut value = Self { + fd, + dir, + name, + own: None, + }; + let (addr, len) = address(&format!("{CLIENT_DIR}/{}", value.name))?; + bound_dir(CLIENT_DIR, &value.dir, None)?; + ensure!( + unsafe { + libc::bind( + value.fd.as_raw_fd(), + (&addr as *const libc::sockaddr_un).cast(), + len, + ) + } == 0, + "TIME_CLIENT_BIND_ONCE" + ); + let mut own = socket_identity(value.dir.as_raw_fd(), &value.name)?; + ensure!( + own.uid == 0 && own.mode & libc::S_IFMT == libc::S_IFSOCK && own.links == 1, + "TIME_CLIENT_INITIAL_IDENTITY" + ); + value.own = Some(own); + let name = cstr(&value.name)?; + ensure!( + unsafe { + libc::fchownat( + value.dir.as_raw_fd(), + name.as_ptr(), + 0, + gid, + libc::AT_SYMLINK_NOFOLLOW, + ) + } == 0, + "TIME_CLIENT_GROUP" + ); + // Parent is root-write-only: no daemon or unprivileged process can swap + // the leaf between this identity capture and chmod. + ensure!( + unsafe { libc::fchmodat(value.dir.as_raw_fd(), name.as_ptr(), 0o660, 0) } == 0, + "TIME_CLIENT_MODE" + ); + let next = socket_identity(value.dir.as_raw_fd(), &value.name)?; + ensure!( + next.dev == own.dev + && next.ino == own.ino + && next.uid == 0 + && next.gid == gid + && next.mode & 0o7777 == 0o660 + && next.links == 1, + "TIME_CLIENT_READY_IDENTITY" + ); + own = next; + value.own = Some(own); + value.verify()?; + let yes: libc::c_int = 1; + ensure!( + unsafe { + libc::setsockopt( + value.fd.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PASSCRED, + (&yes as *const libc::c_int).cast(), + size_of::() as _, + ) + } == 0, + "TIME_PASSCRED_REQUIRED" + ); + let (server, len) = address(SERVER)?; + ensure!( + unsafe { + libc::connect( + value.fd.as_raw_fd(), + (&server as *const libc::sockaddr_un).cast(), + len, + ) + } == 0, + "TIME_CHRONY_CONNECT" + ); + Ok(value) + } + fn verify(&self) -> Result<()> { + bound_dir(CLIENT_DIR, &self.dir, None)?; + ensure!( + Some(socket_identity(self.dir.as_raw_fd(), &self.name)?) == self.own, + "TIME_CLIENT_REPLACED" + ); + Ok(()) + } + fn cleanup(&mut self) -> Result<()> { + // Consume cleanup authority before any fallible work. Unknown cleanup + // never retries from Drop and never adopts a newly observed leaf. + let expected = self + .own + .take() + .context("TIME_CLIENT_CLEANUP_ALREADY_ATTEMPTED")?; + bound_dir(CLIENT_DIR, &self.dir, None)?; + unlink_owned(self.dir.as_raw_fd(), &self.name, expected) + } + fn exchange(&self, sequence: u32, daemon: &Pin, start: Capture) -> Result { + let request = tracking::request(sequence); + ensure!( + unsafe { + libc::send( + self.fd.as_raw_fd(), + request.as_ptr().cast(), + request.len(), + libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL, + ) + } == request.len() as isize, + "TIME_CHRONY_SEND_ONCE" + ); + let now = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?; + let left = QUERY_NS + .checked_sub(now.checked_sub(start.mono).context("TIME_QUERY_CLOCK")?) + .context("TIME_QUERY_TIMEOUT")?; + let timeout = libc::timespec { + tv_sec: 0, + tv_nsec: left as _, + }; + let mut poll = libc::pollfd { + fd: self.fd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + ensure!( + unsafe { libc::ppoll(&mut poll, 1, &timeout, std::ptr::null()) } == 1 + && poll.revents == libc::POLLIN, + "TIME_CHRONY_TIMEOUT" + ); + let mut packet = [0u8; tracking::PACKET_BYTES]; + let mut iov = libc::iovec { + iov_base: packet.as_mut_ptr().cast(), + iov_len: packet.len(), + }; + let mut control = [0usize; 16]; + let mut msg: libc::msghdr = unsafe { mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr().cast(); + msg.msg_controllen = size_of_val(&control); + let got = unsafe { libc::recvmsg(self.fd.as_raw_fd(), &mut msg, libc::MSG_DONTWAIT) }; + ensure!( + got == tracking::PACKET_BYTES as isize + && msg.msg_flags & (libc::MSG_TRUNC | libc::MSG_CTRUNC) == 0, + "TIME_CHRONY_TRUNCATED" + ); + ensure!( + msg.msg_controllen <= size_of_val(&control), + "TIME_CREDENTIALS_CONTROL_BOUND" + ); + let control_start = msg.msg_control as usize; + let control_end = control_start + .checked_add(msg.msg_controllen) + .context("TIME_CREDENTIALS_CONTROL_OVERFLOW")?; + let mut count = 0; + let mut header = unsafe { libc::CMSG_FIRSTHDR(&msg) }; + while !header.is_null() { + let position = header as usize; + ensure!( + position >= control_start + && position + .checked_add(size_of::()) + .is_some_and(|n| n <= control_end), + "TIME_CREDENTIALS_HEADER_BOUND" + ); + let h = unsafe { &*header }; + ensure!( + h.cmsg_len >= unsafe { libc::CMSG_LEN(0) } as usize + && h.cmsg_len <= control_end - position, + "TIME_CREDENTIALS_LENGTH_BOUND" + ); + ensure!( + h.cmsg_level == libc::SOL_SOCKET + && h.cmsg_type == libc::SCM_CREDENTIALS + && h.cmsg_len + == unsafe { libc::CMSG_LEN(size_of::() as _) } as usize, + "TIME_CREDENTIALS_FORMAT" + ); + let credentials = + unsafe { std::ptr::read_unaligned(libc::CMSG_DATA(header).cast::()) }; + ensure!( + credentials.pid == daemon.daemon_pid + && credentials.uid == daemon.daemon_uid + && credentials.gid == daemon.daemon_gid, + "TIME_CREDENTIALS_MISMATCH" + ); + count += 1; + header = unsafe { libc::CMSG_NXTHDR(&msg, header) }; + } + ensure!(count == 1, "TIME_CREDENTIALS_REQUIRED"); + tracking::reply(&packet, sequence) + } +} +fn unlink_owned(dir: RawFd, name: &str, expected: Identity) -> Result<()> { + ensure!( + socket_identity(dir, name)? == expected, + "TIME_CLIENT_CLEANUP_IDENTITY" + ); + let name = cstr(name)?; + ensure!( + unsafe { libc::unlinkat(dir, name.as_ptr(), 0) } == 0, + "TIME_CLIENT_UNLINK" + ); + Ok(()) +} +impl Drop for Client { + fn drop(&mut self) { + // Lost identity is intentionally retained, never recursively removed. + if self.own.is_some() { + let _ = self.cleanup(); + } + } +} + +/// Root-only source broker primitive. No daemon discovery, adoption, commands, +/// configurable endpoint, retry, IP transport or time-setting entrypoint. +pub struct NativeTimeSource { + daemon: Daemon, + server_dir: OwnedFd, + server_identity: Identity, + boot: Uuid, + poisoned: bool, +} +impl NativeTimeSource { + pub fn open() -> Result { + ensure!( + unsafe { libc::geteuid() } == 0, + "TIME_SOURCE_ROOT_BROKER_REQUIRED" + ); + let pin = pin().with_context(|| format!("TIME_PROTECTED_PIN {PIN}"))?; + let daemon = Daemon::open(pin)?; + let server_dir = open_dir( + SERVER_DIR, + Some((daemon.pin.daemon_uid, daemon.pin.daemon_gid)), + )?; + let server_identity = socket_identity(server_dir.as_raw_fd(), "chronyd.sock")?; + ensure!( + server_identity.mode & libc::S_IFMT == libc::S_IFSOCK + && server_identity.links == 1 + && server_identity.uid == daemon.pin.daemon_uid + && server_identity.gid == daemon.pin.daemon_gid + && server_identity.mode & 0o007 == 0, + "TIME_CHRONY_SOCKET_PROTECTION" + ); + Ok(Self { + daemon, + server_dir, + server_identity, + boot: boot_id()?, + poisoned: false, + }) + } + fn verify(&self) -> Result<()> { + self.daemon.verify()?; + bound_dir( + SERVER_DIR, + &self.server_dir, + Some((self.daemon.pin.daemon_uid, self.daemon.pin.daemon_gid)), + )?; + ensure!( + socket_identity(self.server_dir.as_raw_fd(), "chronyd.sock")? == self.server_identity + && boot_id()? == self.boot, + "TIME_SOURCE_GENERATION_CHANGED" + ); + Ok(()) + } + pub fn sample(&mut self) -> Result { + ensure!(!self.poisoned, "TIME_SOURCE_CLEANUP_UNCERTAIN"); + let before = capture()?; + let first = kernel()?; + self.verify()?; + self.poisoned = true; + let mut client = Client::open(self.daemon.pin.daemon_gid)?; + let random = Uuid::new_v4(); + let sequence = u32::from_ne_bytes(random.as_bytes()[..4].try_into()?); + let report = client.exchange(sequence, &self.daemon.pin, before)?; + client.verify()?; + self.verify()?; + let last = kernel()?; + let after = capture()?; + let span = elapsed(before, after)?; + let error = report + .error_ns + .checked_add(first.maxerror_ns.max(last.maxerror_ns)) + .and_then(|v| v.checked_add(span)) + .context("TIME_SOURCE_ERROR_OVERFLOW")?; + ensure!(error <= tracking::MAX_ERROR_NS, "TIME_SOURCE_ERROR_LIMIT"); + ensure!( + report.reference_utc_ns <= after.utc, + "TIME_SOURCE_FUTURE_REFERENCE" + ); + let age = u64::try_from(after.utc - report.reference_utc_ns)? + .checked_add(error) + .context("TIME_SOURCE_AGE_OVERFLOW")?; + ensure!(age <= tracking::MAX_AGE_NS, "TIME_SOURCE_STALE_REFERENCE"); + // Cleanup is explicit and part of successful observation, not an ignored + // Drop error. The returned sample is already aged by this final work. + client.cleanup()?; + self.poisoned = false; + let final_capture = capture()?; + let total = elapsed(before, final_capture)?; + let post = total.checked_sub(span).context("TIME_SOURCE_FINAL_CLOCK")?; + let error = error.checked_add(post).context("TIME_SOURCE_FINAL_ERROR")?; + let age = age.checked_add(post).context("TIME_SOURCE_FINAL_AGE")?; + ensure!( + error <= tracking::MAX_ERROR_NS && age <= tracking::MAX_AGE_NS, + "TIME_SOURCE_FINAL_QUALITY" + ); + Ok(QualifiedSample { + captured_utc_ns: after.utc, + server_error_ns: error, + source_sync_age_ns: age, + server_boot_id: self.boot, + captured_monotonic_ns: after.mono, + sampled_boottime_ns: after.boot, + kernel_state: last.state, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn clock_brackets_reject_suspend_step_backwards_and_total_timeout() { + let a = Capture { + mono: 1_000_000, + end: 1_000_100, + boot: 2_000_000, + utc: 1_800_000_000_000_000_000, + }; + let b = Capture { + mono: 2_000_000, + end: 2_000_100, + boot: 3_000_000, + utc: a.utc + 1_000_000, + }; + assert!(elapsed(a, b).is_ok()); + assert!( + elapsed( + a, + Capture { + boot: b.boot + 1_000_000, + ..b + } + ) + .is_err() + ); + assert!( + elapsed( + a, + Capture { + utc: b.utc + 1_000_000, + ..b + } + ) + .is_err() + ); + assert!( + elapsed( + a, + Capture { + utc: a.utc - 1, + ..b + } + ) + .is_err() + ); + assert!( + elapsed( + a, + Capture { + end: a.mono + QUERY_NS + 1, + ..b + } + ) + .is_err() + ); + } + #[test] + fn socket_cleanup_preserves_replaced_name_and_removes_only_exact_own_inode() { + use std::os::unix::{fs::PermissionsExt, net::UnixDatagram}; + let path = std::env::temp_dir().join(format!("rmm-time-source-unit-{}", Uuid::new_v4())); + std::fs::create_dir(&path).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); + let dir = openat( + libc::AT_FDCWD, + path.to_str().unwrap(), + libc::O_RDONLY | libc::O_DIRECTORY, + ) + .unwrap(); + let old = UnixDatagram::bind(path.join("own.sock")).unwrap(); + let expected = socket_identity(dir.as_raw_fd(), "own.sock").unwrap(); + std::fs::rename(path.join("own.sock"), path.join("held.sock")).unwrap(); + let new = UnixDatagram::bind(path.join("own.sock")).unwrap(); + assert!(unlink_owned(dir.as_raw_fd(), "own.sock", expected).is_err()); + assert!(path.join("own.sock").exists()); + let current = socket_identity(dir.as_raw_fd(), "own.sock").unwrap(); + unlink_owned(dir.as_raw_fd(), "own.sock", current).unwrap(); + assert!(!path.join("own.sock").exists()); + unlink_owned(dir.as_raw_fd(), "held.sock", expected).unwrap(); + drop((old, new)); + std::fs::remove_dir(&path).unwrap(); + } +} diff --git a/crates/time-source-linux/src/tracking.rs b/crates/time-source-linux/src/tracking.rs new file mode 100644 index 0000000..97f2b0c --- /dev/null +++ b/crates/time-source-linux/src/tracking.rs @@ -0,0 +1,204 @@ +use anyhow::{Result, ensure}; +pub(crate) const PACKET_BYTES: usize = 104; +pub(crate) const MAX_ERROR_NS: u64 = 500_000_000; +pub(crate) const MAX_AGE_NS: u64 = 3_600_000_000_000; + +pub(crate) fn request(sequence: u32) -> [u8; PACKET_BYTES] { + let mut out = [0; PACKET_BYTES]; + out[0] = 6; + out[1] = 1; + out[4..6].copy_from_slice(&33u16.to_be_bytes()); + out[8..12].copy_from_slice(&sequence.to_be_bytes()); + out +} +fn u16_at(raw: &[u8], n: usize) -> u16 { + u16::from_be_bytes(raw[n..n + 2].try_into().expect("checked packet size")) +} +fn u32_at(raw: &[u8], n: usize) -> u32 { + u32::from_be_bytes(raw[n..n + 4].try_into().expect("checked packet size")) +} + +/// Chrony's wire Float is signed7 exponent + signed25 coefficient, value +/// coefficient * 2^(exponent-25). Convert its magnitude to ns, rounding upward +/// using integer arithmetic; no IEEE conversion or underflow-to-zero. +fn float_ns(raw: u32, allow_negative: bool) -> Result { + let mut exponent = (raw >> 25) as i32; + if exponent >= 64 { + exponent -= 128; + } + let mut coefficient = (raw & 0x01ff_ffff) as i32; + if coefficient >= 0x0100_0000 { + coefficient -= 0x0200_0000; + } + ensure!(allow_negative || coefficient >= 0, "CHRONY_NEGATIVE_ERROR"); + let numerator = u128::from(coefficient.unsigned_abs()) * 1_000_000_000; + let shift = exponent - 25; + let rounded = if shift >= 0 { + numerator + .checked_shl(shift as u32) + .ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))? + } else { + let denominator = 1u128 + .checked_shl((-shift) as u32) + .ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))?; + numerator.div_ceil(denominator) + }; + u64::try_from(rounded).map_err(Into::into) +} + +#[derive(Debug)] +pub(crate) struct Tracking { + pub reference_utc_ns: i64, + pub error_ns: u64, +} +pub(crate) fn reply(raw: &[u8], sequence: u32) -> Result { + ensure!(raw.len() == PACKET_BYTES, "CHRONY_PACKET_LENGTH"); + ensure!( + raw[0] == 6 + && raw[1] == 2 + && raw[2..4] == [0, 0] + && u16_at(raw, 4) == 33 + && u16_at(raw, 6) == 5 + && u16_at(raw, 8) == 0 + && raw[10..16] == [0; 6] + && raw[20..28] == [0; 8] + && u32_at(raw, 16) == sequence, + "CHRONY_REPLY_BINDING" + ); + let reference = u32_at(raw, 28); + let family = u16_at(raw, 48); + // Network peers only. Local/reference-clock fallback is deliberately outside + // this profile; family UNSPEC/ID and loopback identities cannot qualify. + ensure!( + reference != 0 + && reference != 0x4c4f_434c + && reference >> 24 != 127 + && (family == 1 || family == 2) + && raw[50..52] == [0, 0], + "CHRONY_REFERENCE_SOURCE" + ); + if family == 1 { + ensure!( + raw[32] != 127 && raw[32..36] != [0; 4] && raw[36..48] == [0; 12], + "CHRONY_LOCAL_IPV4" + ); + } else { + let address = &raw[32..48]; + let mapped = address[..10] == [0; 10] && address[10..12] == [0xff, 0xff]; + let compatible = address[..12] == [0; 12]; + ensure!( + !((mapped || compatible) && (address[12] == 127 || address[12..16] == [0; 4])), + "CHRONY_LOCAL_EMBEDDED_IPV4" + ); + ensure!( + raw[32..48] != [0; 16] + && raw[32..48] != [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + "CHRONY_LOCAL_IPV6" + ); + } + ensure!( + (1..=15).contains(&u16_at(raw, 52)) && u16_at(raw, 54) <= 2, + "CHRONY_UNSYNCHRONIZED" + ); + let high = u32_at(raw, 56); + let seconds = if high == 0x7fff_ffff { + u64::from(u32_at(raw, 60)) + } else { + (u64::from(high) << 32) | u64::from(u32_at(raw, 60)) + }; + let nanos = u32_at(raw, 64); + ensure!( + seconds > 0 && nanos < 1_000_000_000, + "CHRONY_REFERENCE_TIME" + ); + let reference_utc_ns = i64::try_from(u128::from(seconds) * 1_000_000_000 + u128::from(nanos))?; + let correction = float_ns(u32_at(raw, 68), true)?; + let delay = float_ns(u32_at(raw, 92), false)?; + let dispersion = float_ns(u32_at(raw, 96), false)?; + let error_ns = correction + .checked_add(delay.div_ceil(2)) + .and_then(|v| v.checked_add(dispersion)) + .ok_or_else(|| anyhow::anyhow!("CHRONY_ERROR_OVERFLOW"))?; + ensure!(error_ns <= MAX_ERROR_NS, "CHRONY_ERROR_LIMIT"); + Ok(Tracking { + reference_utc_ns, + error_ns, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + fn good() -> [u8; PACKET_BYTES] { + let mut b = [0; PACKET_BYTES]; + b[0] = 6; + b[1] = 2; + b[4..6].copy_from_slice(&33u16.to_be_bytes()); + b[6..8].copy_from_slice(&5u16.to_be_bytes()); + b[16..20].copy_from_slice(&7u32.to_be_bytes()); + b[28..32].copy_from_slice(&0xc0000201u32.to_be_bytes()); + b[32..36].copy_from_slice(&[192, 0, 2, 1]); + b[48..50].copy_from_slice(&1u16.to_be_bytes()); + b[52..54].copy_from_slice(&2u16.to_be_bytes()); + b[60..64].copy_from_slice(&1_800_000_000u32.to_be_bytes()); + b + } + #[test] + fn exact_packet_sequence_and_network_source() { + let b = good(); + let t = reply(&b, 7).unwrap(); + assert_eq!(t.reference_utc_ns, 1_800_000_000_000_000_000); + assert_eq!(t.error_ns, 0); + assert!(reply(&b, 8).is_err()); + assert!(reply(&b[..103], 7).is_err()); + for offset in [0, 1, 4, 6, 8, 10, 20, 48, 54] { + let mut bad = b; + bad[offset] ^= 0x40; + assert!(reply(&bad, 7).is_err(), "offset {offset}"); + } + let mut bad = b; + bad[48..50].fill(0); + assert!(reply(&bad, 7).is_err()); + // IPv4 loopback/unspecified cannot hide inside mapped or compatible + // IPv6. Ordinary IPv6 and mapped network peers remain accepted. + for (mapped, ipv4) in [ + (true, [127, 0, 0, 1]), + (true, [0, 0, 0, 0]), + (false, [127, 0, 0, 1]), + (false, [0, 0, 0, 0]), + ] { + let mut bad = b; + bad[48..50].copy_from_slice(&2u16.to_be_bytes()); + bad[32..48].fill(0); + if mapped { + bad[42..44].fill(0xff); + } + bad[44..48].copy_from_slice(&ipv4); + assert!(reply(&bad, 7).is_err()); + } + let mut ipv6 = b; + ipv6[48..50].copy_from_slice(&2u16.to_be_bytes()); + ipv6[32..48].fill(0); + ipv6[32..36].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]); + ipv6[47] = 1; + assert!(reply(&ipv6, 7).is_ok()); + ipv6[32..48].fill(0); + ipv6[42..44].fill(0xff); + ipv6[44..48].copy_from_slice(&[192, 0, 2, 1]); + assert!(reply(&ipv6, 7).is_ok()); + assert_eq!(request(7).len(), 104); + assert_eq!(&request(7)[8..12], &7u32.to_be_bytes()); + } + #[test] + fn signed_float_ceil_and_overflow_are_conservative() { + // exp=-6, coeff=2^24 -> 1/128 sec, exactly 7_812_500ns. + let positive = (122u32 << 25) | 0x0100_0000; // coeff -2^24 + assert_eq!(float_ns(positive, true).unwrap(), 7_812_500); + assert!(float_ns(positive, false).is_err()); + assert_eq!(float_ns(64u32 << 25 | 1, true).unwrap(), 1); + assert!(float_ns(63u32 << 25 | 0x00ff_ffff, true).is_err()); + let mut b = good(); + b[96..100].copy_from_slice(&(63u32 << 25 | 0x00ff_ffff).to_be_bytes()); + assert!(reply(&b, 7).is_err()); + } +} diff --git a/deploy/time_attestation_linux_acceptance.py b/deploy/time_attestation_linux_acceptance.py new file mode 100644 index 0000000..70086a8 --- /dev/null +++ b/deploy/time_attestation_linux_acceptance.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Frozen four Linux time-contract units only; 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/time-attestation-qualification/368c42aa-de32-41cd-85fe-c15637cd57a9' +STATE = ROOT / 'devstate/time-attestation-linux' +PROFILE = 'rmm.time-attestation.four-contract-units.v1' +RECEIPT_SHA = 'a50017a1a80042351a639ab2fa8f813435d7d40bd236331dd34f075e98cd09eb' +INPUTS_SHA = 'c01a21bfa09a77b7fa529b85931ac111d08f0dcce137e6aa86a9a22c2c35cf73' +BINARY_SHA = '0e06243dc6d9d502681fb62f755bf5267140a483f89ae61cd6a2e31201a85a13' +BINARY_BYTES = 1515200 +TESTS = sorted(['tests::foreign_reply_cannot_reenable_an_older_own_challenge', 'tests::signed_roundtrip_uses_entire_rtt_and_strict_deadline_interval', 'tests::discontinuity_invalidates_outstanding_and_requires_new_challenge', 'tests::tampering_wrong_role_nonce_key_and_delays_never_open']) +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 <= 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['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) == 4 and source == value['source_files'], 'exact frozen four codec 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') + binary = folder / 'time-contract-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-time-attestation-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') + 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']) == 2020268, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 1515200 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed four-unit binary') + binary = folder / 'time-contract-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) == 4 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact four tests before any run') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + code, stdout, stderr = run(command + ['--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'4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout + and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'four native units and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=4, ignored=0, filtered=0, 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) == 4 + and receipt['result'] == 'LOCAL_DEBUG_TIME4_PASS_RELEASE_LINKED' and receipt['tests'] == 4 + and receipt['skips'] == 0 and receipt['filters'] == 0, 'reviewed four-test 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 / 'qualified-time-tests' + support.require(receipt['artifacts'][0] == dict(path='qualified-time-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA), 'fixed original linked artifact') + copy_exact(binary, folder / 'time-contract-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, 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, 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 / 'time-contract-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['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/deploy/time_attestation_uri_linux_acceptance.py b/deploy/time_attestation_uri_linux_acceptance.py new file mode 100644 index 0000000..7b41816 --- /dev/null +++ b/deploy/time_attestation_uri_linux_acceptance.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Frozen four Linux time-contract units only; 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/time-attestation-qualification/61dd70ca-3952-435e-9de2-dc2f40fedac7' +STATE = ROOT / 'devstate/time-attestation-uri-linux' +PROFILE = 'rmm.time-attestation.four-uri-contract-units.v1' +RECEIPT_SHA = 'b708000c9ca9ba8da2128003683ed26382d4349833c322663bdd393dd60ad751' +INPUTS_SHA = '989bcd56c96747ce8f2c4020423360ce4a8c9d8057f7c3deccba4e44fbc30c9a' +BINARY_SHA = '4dc10170500912c703f815f8c13f9ac28715afe919ad94020fe713ade8fbafdb' +BINARY_BYTES = 1515168 +TESTS = sorted(['tests::foreign_reply_cannot_reenable_an_older_own_challenge', 'tests::signed_roundtrip_uses_entire_rtt_and_strict_deadline_interval', 'tests::discontinuity_invalidates_outstanding_and_requires_new_challenge', 'tests::tampering_wrong_role_nonce_key_and_delays_never_open']) +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 <= 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['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) == 4 and source == value['source_files'], 'exact frozen four codec 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') + binary = folder / 'time-contract-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-time-attestation-uri-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') + 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']) == 2020224, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 1515168 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed four-unit binary') + binary = folder / 'time-contract-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) == 4 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact four tests before any run') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + code, stdout, stderr = run(command + ['--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'4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout + and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'four native units and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=4, ignored=0, filtered=0, 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) == 4 + and receipt['result'] == 'LOCAL_TIME4_URI_PASS_RELEASE' and receipt['tests'] == 4 + and receipt['skips'] == 0 and receipt['filters'] == 0, 'reviewed four-test 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 / 'qualified-time-tests' + support.require(receipt['artifacts'][0] == dict(path='qualified-time-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA), 'fixed original linked artifact') + copy_exact(binary, folder / 'time-contract-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, 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, 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 / 'time-contract-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['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/deploy/updater_handoff_linux_acceptance.py b/deploy/updater_handoff_linux_acceptance.py new file mode 100644 index 0000000..bf6bc81 --- /dev/null +++ b/deploy/updater_handoff_linux_acceptance.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Run only the frozen eight pure handoff contracts on the Cloud Linux VM. + +No RMM job, approval, agent/helper operation, release application or updater +installation. Prepare locally; execute one isolated nobody-owned process; +after any lost reply use read only. Original verifier runners remain unchanged. +""" +import argparse +import base64 +import hashlib +import inspect +import json +import os +from pathlib import Path +import subprocess +import uuid + +import windows_msi_runtime_acceptance as support + +ROOT = Path(__file__).resolve().parents[1] +UPDATER = ROOT.parent / 'rust-discovery-agent-updater' +STATE = ROOT / 'devstate/updater-handoff-native' +COMMIT = 'a2efb79' +RECEIPT_SHA = 'e924471166e68629d27d6adae51ebac05a77f04426cdd427e844a9dfb4920f70' +BINARY_SHA = '0c80a2107fff96d9e30aa02b1cb56071a0f7e2be2acb1bec6794324205af9c7a' +TESTS = sorted('''closed_service_sets_reject_omitted_full_and_apt_restart +event_chain_clock_limits_and_canonical_bytes_fail_closed +full_linux_three_service_handoff_replays_exactly_sixteen_events +full_renderer_binds_provisioned_file_key_without_inserting_it_into_raw_config +full_renderer_changes_only_named_hash_spans_preserving_all_other_raw_bytes +full_renderer_rejects_foreign_pins_unknown_duplicate_escaped_and_privilege_changes +health_is_domain_bound_fresh_evidence_and_never_opens_ready +no_ownership_before_stop_no_partial_pair_no_start_before_return'''.splitlines()) + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def remote(p): + import base64 + import hashlib + import json + import os + from pathlib import Path + import stat + import subprocess + import time + import uuid + + def require(ok, message): + if not ok: + raise RuntimeError(message) + + def enc(v): + return json.dumps(v, 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 f: + f.write(raw); f.flush(); os.fsync(f.fileno()) + fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + def run(args, timeout=20): + return subprocess.run(args, capture_output=True, timeout=timeout, + env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'}) + + def witness(): + out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}} + 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'])): + r = run(['systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState']) + require(r.returncode == 0, 'existing service read') + s = dict(line.split('=', 1) for line in r.stdout.decode().splitlines()) + pid = int(s['MainPID']); require(s['ActiveState'] == 'active' and pid > 1, 'three existing services active') + proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] + status = (proc / 'status').read_text().splitlines() + ids = {line.split(':')[0]: line.split()[1:] for line in status if line.startswith(('Uid:', 'Gid:'))} + image = hashlib.sha256((proc / 'exe').read_bytes()).hexdigest() + require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary + and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'held generation/account/image') + out['services'][name] = dict(s, birth=birth, image=image, ids=ids) + r = run(['systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState']) + require(r.returncode == 0, 'APT service read') + apt = dict(line.split('=', 1) for line in r.stdout.decode().splitlines()) + require(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); m = path.lstat() + require(not path.is_symlink() and stat.S_ISREG(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022 + and m.st_nlink == 1 and m.st_size < 65536, 'protected known control') + out['files'][name] = [m.st_dev, m.st_ino, m.st_uid, m.st_gid, m.st_mode, m.st_size, + m.st_mtime_ns, m.st_ctime_ns, hashlib.sha256(path.read_bytes()).hexdigest()] + 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); m = path.lstat() + require(not path.is_symlink() and stat.S_ISREG(m.st_mode) and m.st_nlink == 1, 'existing state identity') + out['files'][name] = [m.st_dev, m.st_ino, m.st_uid, m.st_gid, m.st_mode] + return out + + require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root bootstrap') + ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical case') + folder = Path('/var/tmp') / ('rmm-updater-handoff-' + ident) + if p['action'] == 'read': + m = folder.lstat(); require(stat.S_ISDIR(m.st_mode) and not folder.is_symlink() and m.st_uid == 0, 'own original case') + return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(), + 'result': json.loads((folder / 'result.json').read_bytes()) if (folder / 'result.json').exists() else None, + 'current_witness': witness()} + require(p['action'] == 'execute', 'one exact unit action') + os.umask(0o022); folder.mkdir(mode=0o755) + create(folder / 'intent.json', enc({k: v for k, v in p.items() if k != 'binary_b64'})) + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 2261368 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed pure unit bytes') + binary = folder / 'handoff-contract'; create(binary, raw, 0o755) + before = witness(); create(folder / 'before.json', enc(before)) + command = ['/usr/bin/setpriv', '--reuid=65534', '--regid=65534', '--clear-groups', '--no-new-privs', str(binary)] + listed = run(command + ['--list', '--format', 'terse']) + create(folder / 'list.stdout', listed.stdout); create(folder / 'list.stderr', listed.stderr) + require(listed.returncode == 0 and listed.stderr == b'', 'native list succeeded') + require(sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test')) == p['tests'] + and len(listed.stdout.decode().splitlines()) == 8, 'exact eight native tests, no filter') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + result = run(command + ['--test-threads=1', '--nocapture']) + create(folder / 'run.stdout', result.stdout); create(folder / 'run.stderr', result.stderr) + after = witness(); create(folder / 'after.json', enc(after)) + require(before == after and result.returncode == 0 and result.stderr == b'' + and b'8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in result.stdout + and all((b'test ' + name.encode() + b' ... ok') in result.stdout for name in p['tests']), 'native eight and retained services/state') + receipt = dict(id=ident, passed=8, ignored=0, filtered=0, execution_uid=65534, tests=p['tests'], + before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'], + stdout_sha256=hashlib.sha256(result.stdout).hexdigest(), no_rmm_jobs=True, no_apply=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, exist_ok=True) + if args.action == 'prepare': + support.require(args.case is None, 'new local case') + receipt = UPDATER / 'devstate/agent-updater-handoff/local-qualification-filekey.json' + support.private(receipt) + raw = receipt.read_bytes(); support.require(sha(raw) == RECEIPT_SHA, 'reviewed local receipt') + local = json.loads(raw) + for item in local['sources']: + blob = subprocess.check_output(['git', '-C', str(UPDATER), 'show', COMMIT + ':' + item['path']]) + support.require(len(blob) == item['bytes'] and sha(blob) == item['sha256'], 'exact committed qualified source') + binary = UPDATER / local['binary']['path']; support.require(sha(binary.read_bytes()) == BINARY_SHA, 'qualified binary') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700) + support.save(folder / 'intent.json', dict(id=ident, runner_sha256=sha(Path(__file__).read_bytes()), + receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_path=str(binary), tests=TESTS, + agent_sha256='0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f', + helper_sha256='79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf')) + else: + ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same original case') + folder = STATE / ident; intent = support.load(folder / 'intent.json') + support.require(intent['runner_sha256'] == sha(Path(__file__).read_bytes()), 'original runner bytes') + if args.action == 'execute': + support.save(folder / 'execute-entered.json', {'once': True, 'no_retry': True}) + raw = Path(intent['binary_path']).read_bytes(); support.require(sha(raw) == BINARY_SHA, 'original binary') + intent['binary_b64'] = base64.b64encode(raw).decode() + payload = dict(intent, action=args.action) + code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n' + response = support.transport(support.access_settings(ROOT, 'linux'), 'python3 -', code.encode(), folder) + support.save(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response) + if args.action == 'read': + support.require(response['result'] is not None and response['current_witness'] == response['result']['after'], 'readback retained native result') + print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'), 'read_only': args.action == 'read'})); return + print(json.dumps({'id': ident, 'prepared_locally': True})) + + +if __name__ == '__main__': + main() diff --git a/deploy/updater_linux_native_acceptance.py b/deploy/updater_linux_native_acceptance.py new file mode 100644 index 0000000..833e9d6 --- /dev/null +++ b/deploy/updater_linux_native_acceptance.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +"""Frozen five Linux OS-port units only; 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] +UPDATER = ROOT.parent / 'rust-discovery-agent-updater' +QUALIFICATION = UPDATER / 'devstate/updater-linux-execfix-aa106c58-8c96-4c8a-8490-635b1d143f07' +STATE = ROOT / 'devstate/updater-linux-native' +PROFILE = 'rmm.updater-linux.five-os-units.v1' +RECEIPT_SHA = 'f705ba03e5043a411fc3a0642197fc4f16da8627e1e5cbfbac78ed125ecb650c' +INTENT_SHA = '4921dac74d57931ad1973b4e64409d231e02ab0cb264b35113292fc295840ad3' +BINARY_SHA = 'b11b57e6399dcfcfb255619a8fba558beea6a57e4f1ee997ee9c63c769a1e882' +BINARY_BYTES = 1538320 +TESTS = sorted('''ipc::tests::framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch +ipc::tests::partial_socket_frame_does_not_extend_its_total_deadline +tests::held_file_rejects_symlink_and_replaced_name_but_preserves_bound_hardlinks +tests::pidfd_image_birth_account_and_exit_are_independently_observed +tests::same_pid_exec_rejects_changed_image_despite_retained_pidfd_birth_and_credentials'''.splitlines()) +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 <= 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['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 / 'intent.json').read_bytes()) == INTENT_SHA, 'original qualification provenance') + source = support.load(folder / 'intent.json') + support.require(len(source['source_files']) == 22 and source['source_files'] == value['source_files'], 'exact frozen 22 inputs') + for item in source['source_files']: + 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') + binary = folder / 'os-port-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 OS fixtures') + ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case') + folder = Path('/var/tmp') / ('rmm-updater-linux-os-' + 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') + 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 OS unit 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']) == 2051096, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 1538320 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed five-unit binary') + binary = folder / 'os-port-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) == 5 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact five tests before any run') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + code, stdout, stderr = run(command + ['--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'5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout + and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'five native units and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=5, ignored=0, filtered=0, 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 / 'intent.json') + support.require(sha((QUALIFICATION / 'intent.json').read_bytes()) == INTENT_SHA + and receipt['intent_sha256'] == INTENT_SHA and len(original['source_files']) == 22 + and receipt['actual_fixed_tests'] == {'passed': 5, 'failed': 0, 'ignored': 0, 'filtered': 0} + and receipt['old_code_counterexample_expected_failed'] is True, 'reviewed five-test 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 / 'intent.json', folder / 'intent.json', INTENT_SHA, (QUALIFICATION / 'intent.json').stat().st_size) + paths = set() + for item in original['source_files']: + 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 = Path(receipt['binary']['path']) + support.require(binary == QUALIFICATION / 'target/release/deps/rmm_updater_linux-b7e2b2ad3deb3b92', 'fixed original linked artifact') + copy_exact(binary, folder / 'os-port-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['source_files'], tests=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, 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 / 'os-port-tests').read_bytes()).decode() + code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n' + response = support.transport(support.access_settings(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['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/deploy/updater_linux_reopen_acceptance.py b/deploy/updater_linux_reopen_acceptance.py new file mode 100644 index 0000000..50552a0 --- /dev/null +++ b/deploy/updater_linux_reopen_acceptance.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Frozen six Linux OS-port units only; 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] +UPDATER = ROOT.parent / 'rust-discovery-agent-updater' +QUALIFICATION = UPDATER / 'devstate/agent-updater-linux/qualification-os6-0b3c8018-b08f-4917-80b8-0e3169a0f813' +STATE = ROOT / 'devstate/updater-linux-native-reopen' +PROFILE = 'rmm.updater-linux.six-os-units.v1' +RECEIPT_SHA = 'c3e1ee619ef01630b296aaf7669d04f39ea952b1ec2d7adc1a791f69f6a6ee08' +INPUTS_SHA = '4f92d291e9edb63198f77071f73fe447f6cca0b040290e93b75673212ff4dd67' +BINARY_SHA = 'c78d24d9b3f543fc4eba3fa1d02bf82e72aea26493ae689f2fc82ee1067d33fc' +BINARY_BYTES = 1555392 +TESTS = sorted('''files::reopen_tests::bound_reopen_rejects_same_byte_name_substitution_and_added_stage_hardlink +ipc::tests::framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch +ipc::tests::partial_socket_frame_does_not_extend_its_total_deadline +tests::held_file_rejects_symlink_and_replaced_name_but_preserves_bound_hardlinks +tests::pidfd_image_birth_account_and_exit_are_independently_observed +tests::same_pid_exec_rejects_changed_image_despite_retained_pidfd_birth_and_credentials'''.splitlines()) +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 <= 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['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) == 23 and source == value['source_files'], 'exact frozen 23 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') + binary = folder / 'os-port-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 OS fixtures') + ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case') + folder = Path('/var/tmp') / ('rmm-updater-linux-os6-' + 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') + 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 OS unit 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']) == 2073856, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 1555392 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed six-unit binary') + binary = folder / 'os-port-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) == 6 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact six tests before any run') + create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()})) + code, stdout, stderr = run(command + ['--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'6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout + and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'six native units and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=6, ignored=0, filtered=0, 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) == 23 + and receipt['result'] == 'LOCAL_ONLY_OS6_PASS' and receipt['tests'] == 6 + and receipt['skips'] == 0 and receipt['filters'] == 0, 'reviewed six-test 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 / 'qualified-os6-tests' + support.require(receipt['artifacts'][0] == dict(path='qualified-os6-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA), 'fixed original linked artifact') + copy_exact(binary, folder / 'os-port-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, 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, 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 / 'os-port-tests').read_bytes()).decode() + code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n' + response = support.transport(support.access_settings(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['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/deploy/windows/clock-eeinfo-trace/build.py b/deploy/windows/clock-eeinfo-trace/build.py new file mode 100644 index 0000000..b01f656 --- /dev/null +++ b/deploy/windows/clock-eeinfo-trace/build.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Local-only SYSTEM trace diagnostic build; no VM and no product source edits.""" +import base64 +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-eeinfo-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_eeinfo.c','system_trace_eeinfo.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_eeinfo.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_eeinfo.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_eeinfo.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), own_system_token_only=True, exactly_one_trace_call=True, no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemEeInfoTrace.linked.exe']) + raw_linked = output / 'ClockSystemEeInfoTrace.linked.exe' + linked = output / 'ClockSystemEeInfoTrace.original.exe'; delivery = output / 'ClockSystemEeInfoTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSystemEeInfoTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemEeInfoTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-eeinfo-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c b/deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c new file mode 100644 index 0000000..11cc41b --- /dev/null +++ b/deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c @@ -0,0 +1,291 @@ +/* Only the authenticated local MS-W32T status operation is reachable here. + * NDR code is generated by WIDL; SEH must terminate inside C, never in Rust. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout, + * not a fallback to an older authentication contract. MSVC also checks it + * directly against its native SDK declaration. Windows x64 is the only target. + * https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w + */ +typedef struct { + unsigned long Version, Capabilities, IdentityTracking, ImpersonationType; + unsigned long AdditionalSecurityInfoType; + union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u; + void *Sid; + unsigned int EffectiveOnly; + void *ServerSecurityDescriptor; +} RmmRpcQosV5; +_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI"); +#ifdef _MSC_VER +_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI"); +#endif + +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_SECURITY_QOS qos = {0}; + unsigned long result; + memset(out, 0, sizeof(*out)); + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + if (trace) trace->stage = 30; + result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos); + if (!result) { + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + } + if (!result) result = invoke_status(binding, out, trace, eeinfo); + RpcBindingFree(&binding); + return result; +} +uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL, NULL); } +uint32_t rmm_clock_query_trace(RmmClockTrace *trace) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + return pipe_query(&ignored, trace, NULL); +} +/* Kernel-authenticated ALPC only. No automatic fallback to named pipes. + * The expected SID is fixed locally, never adopted from endpoint metadata. + */ +static uint32_t alpc_query(RmmClockStatus *out, unsigned control) { + RPC_IF_ID id = {0}; + RPC_EP_INQ_HANDLE inquiry = NULL; + RPC_STATUS result; + memset(out, 0, sizeof(*out)); + result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &id.Uuid); + if (result) return result; + id.VersMajor = 4; id.VersMinor = 1; + result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &id, RPC_C_VERS_EXACT, NULL, &inquiry); + if (result) return result; + for (unsigned i=0; i<16; ++i) { + RPC_IF_ID actual = {0}; + RPC_BINDING_HANDLE binding = NULL; + UUID object = {0}; + RPC_WSTR annotation = NULL, text = NULL, protocol = NULL; + result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation); + if (annotation) RpcStringFreeW(&annotation); + if (result) break; + result = RpcBindingToStringBindingW(binding, &text); + if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL); + int local = !result && !wcscmp((wchar_t *)protocol, L"ncalrpc"); + if (protocol) RpcStringFreeW(&protocol); + if (text) RpcStringFreeW(&text); + if (result) {RpcBindingFree(&binding);break;} + if (local) { + _Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE]; + _Alignas(8) BYTE service_sid[SECURITY_MAX_SID_SIZE]; + _Alignas(8) BYTE acl_buffer[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE]; + SECURITY_DESCRIPTOR descriptor; + WCHAR domain[64]; + DWORD domain_size = sizeof(domain) / sizeof(domain[0]); + DWORD service_sid_size = sizeof(service_sid); + SID_NAME_USE sid_type; + DWORD sid_size = sizeof(expected_sid); + RmmRpcQosV5 qos = {0}; + /* An account-only SID19 binding also accepts other LocalService + * processes, including our network agent. The client-owned V5 + * descriptor therefore requires the separate W32Time service SID. + * No descriptor/identity is obtained from endpoint metadata. + * Controls are fixed read-only diagnostics, never production modes. + */ + if (!CreateWellKnownSid(control == 1 ? WinLocalSystemSid : WinLocalServiceSid, + NULL, expected_sid, &sid_size)) result = GetLastError(); + if (!result && !LookupAccountNameW(NULL, + control == 2 ? L"NT SERVICE\\RmmDiscoveryWindows" : L"NT SERVICE\\W32Time", + service_sid, &service_sid_size, domain, &domain_size, &sid_type)) result = GetLastError(); + if (!result && (!IsValidSid(service_sid) || service_sid_size > sizeof(service_sid))) result = ERROR_INVALID_SID; + if (!result && !InitializeAcl((PACL)acl_buffer, sizeof(acl_buffer), ACL_REVISION)) result = GetLastError(); + if (!result && !AddAccessAllowedAce((PACL)acl_buffer, ACL_REVISION, GENERIC_ALL, service_sid)) result = GetLastError(); + if (!result && !InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION)) result = GetLastError(); + if (!result && !SetSecurityDescriptorDacl(&descriptor, TRUE, (PACL)acl_buffer, FALSE)) result = GetLastError(); + if (!result) { + qos.Version = 5; /* RPC_C_SECURITY_QOS_VERSION_5 */ + qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + qos.Sid = expected_sid; + qos.EffectiveOnly = TRUE; + qos.ServerSecurityDescriptor = &descriptor; + result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos); + if (!result) result = invoke_status(binding, out, NULL, NULL); + } + RpcBindingFree(&binding); + break; /* no retry, alternate identity, endpoint or weaker transport */ + } + RpcBindingFree(&binding); + result = EPT_S_NOT_REGISTERED; + } + RpcMgmtEpEltInqDone(&inquiry); + return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result; +} +uint32_t rmm_clock_alpc_query(RmmClockStatus *out) { return alpc_query(out, 0); } +uint32_t rmm_clock_wrong_account(RmmClockStatus *out) { return alpc_query(out, 1); } +uint32_t rmm_clock_wrong_service(RmmClockStatus *out) { return alpc_query(out, 2); } + +/* Exactly one original authenticated pipe query; EEInfo is observation only. */ +uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo); +} diff --git a/deploy/windows/clock-eeinfo-trace/native.py b/deploy/windows/clock-eeinfo-trace/native.py new file mode 100644 index 0000000..9b00f89 --- /dev/null +++ b/deploy/windows/clock-eeinfo-trace/native.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-eeinfo-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-eeinfo-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSystemEeInfoDiagnostic';$case=Join-Path $root ('clock-eeinfo-trace-'+$id);$exe=Join-Path $case 'ClockSystemEeInfoTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemEeInfoDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-eeinfo-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-eeinfo-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True + and report['query_invocations'] == 1 and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] == 90:require(ee['capture_attempted'] == 1 and report['rpc_code'] == report['trace']['rpc_exception'],'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True) + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-eeinfo-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-eeinfo-trace-'+ident+'/ClockSystemEeInfoTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c b/deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c new file mode 100644 index 0000000..7effabe --- /dev/null +++ b/deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c @@ -0,0 +1,135 @@ +/* Standalone diagnostic only. The original C/Auth/MIDL inputs are linked + * unchanged. Exactly one trace query, only under this process's SYSTEM token. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +uint32_t rmm_clock_query_trace_eeinfo(RmmClockTrace *trace, RmmClockEeInfo *eeinfo); + +static WCHAR service_name[] = L"RmmClockSystemEeInfoDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(void) { + HANDLE token = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return GetLastError(); + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed > sizeof(storage) || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + CloseHandle(token); + return result; +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo) { + WCHAR path[256]; + char id[37], report[4096]; + DWORD written = 0, result = ERROR_SUCCESS; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-eeinfo-trace-%ls\\result.json", case_id); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-eeinfo-v1\",\"case_id\":\"%s\"," + "\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":1," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, "]}}\n"); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, report, (DWORD)count, &written, NULL) || written != (DWORD)count) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file); + return result; +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + DWORD result = own_system_token(); + if (!result) { + RmmClockTrace trace = {0}; + RmmClockEeInfo eeinfo = {0}; + uint32_t rpc = rmm_clock_query_trace_eeinfo(&trace, &eeinfo); /* exactly one fixed call */ + result = write_result(rpc, &trace, &eeinfo); + } + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-midl-diagnostic/Cargo.toml b/deploy/windows/clock-midl-diagnostic/Cargo.toml new file mode 100644 index 0000000..6bd2380 --- /dev/null +++ b/deploy/windows/clock-midl-diagnostic/Cargo.toml @@ -0,0 +1,27 @@ +[workspace] + +[package] +name = "rmm-clock-midl-diagnostic" +version = "0.1.0" +edition = "2024" +license = "AGPL-3.0-only" +autobins = false + +[[bin]] +name = "clock-midl-readiness" +path = "../../../crates/agent-windows/examples/clock_readiness.rs" + +[dependencies] +anyhow = "1.0.100" +chrono = { version = "0.4.42", features = ["serde"] } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.145" +uuid = { version = "1.18.1", features = ["v4", "serde"] } +rmm-agent-core = { path = "../../../crates/agent-core" } + +[build-dependencies] +cc = "=1.11.1" +sha2 = "0.10.9" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] } diff --git a/deploy/windows/clock-midl-diagnostic/build.rs b/deploy/windows/clock-midl-diagnostic/build.rs new file mode 100644 index 0000000..b1a34ba --- /dev/null +++ b/deploy/windows/clock-midl-diagnostic/build.rs @@ -0,0 +1,93 @@ +//! Separate diagnostic only: actual Microsoft outputs from native case 149bafe2. +//! No generator execution/fallback, NDR edits, header-version overrides or +//! modification of the product crate's build script/output directory. +use sha2::{Digest, Sha256}; +use std::{env, fs, path::Path}; + +fn pinned(path: &Path, expected: &str) { + let bytes = fs::read(path).expect("missing pinned diagnostic input"); + assert_eq!( + format!("{:x}", Sha256::digest(bytes)), + expected, + "diagnostic input changed: {}", + path.display() + ); + println!("cargo:rerun-if-changed={}", path.display()); +} + +fn main() { + let here = env::current_dir().unwrap(); + let root = here.join("../../.."); + for (name, digest) in [ + ( + "examples/clock_readiness.rs", + "77433fafc9891ada53571bc070e33b9c9998379b7dadf48c1e19dc3851e44fe7", + ), + ( + "src/clock.rs", + "08b983095015cc7ba08ce08e9436d1519bf720c5501dd7af8b8b3dbae56b356f", + ), + ( + "native/clock_rpc.c", + "74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8", + ), + ( + "native/clock_endpoints.c", + "85c563bc8824bc30f7e80ef36e3dae5548c1f7a94faf5e882e98f275ab9a55e7", + ), + ( + "native/w32time.idl", + "37da4acb622daf9acf1aa6f1218ff9f52e5a2def14e58d8d9dd8da65078b3c6c", + ), + ] { + pinned(&root.join("crates/agent-windows").join(name), digest); + } + let generated = here.join("generated"); + pinned( + &generated.join("w32time.h"), + "db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde", + ); + pinned( + &generated.join("w32time_c.c"), + "d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38", + ); + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { + return; + } + assert_eq!(env::var("TARGET").as_deref(), Ok("x86_64-pc-windows-gnu")); + // Microsoft guards its AMD64 stub using this architecture macro. Clang's + // GNU target does not predefine it. This declares the actual selected x64 + // architecture; no SDK/RPCNDR version or _MSC_VER is fabricated. + cc::Build::new() + .compiler("clang") + .flag("--target=x86_64-w64-windows-gnu") + .flag("-fms-extensions") + .flag("-Werror") + .define("_M_AMD64", Some("100")) + .include(&generated) + .file(root.join("crates/agent-windows/native/clock_rpc.c")) + .file(root.join("crates/agent-windows/native/clock_endpoints.c")) + .compile("rmm_clock_rpc"); + // MIDL's unchanged descriptor initializer uses legal C brace elision for + // MinGW's union field and emits two unused const tables. Keep these style + // warnings visible only for this pinned generated unit; do not edit NDR + // data, suppress type/security errors, or weaken wrapper diagnostics. + cc::Build::new() + .compiler("clang") + .flag("--target=x86_64-w64-windows-gnu") + .flag("-fms-extensions") + .flag("-Werror") + .flag("-Wno-error=missing-braces") + .flag("-Wno-error=unused-const-variable") + .define("_M_AMD64", Some("100")) + .include(&generated) + .file(generated.join("w32time_c.c")) + .compile("rmm_clock_midl_stub"); + println!("cargo:rustc-link-lib=rpcrt4"); + println!("cargo:rustc-link-lib=advapi32"); + // The existing GNU readiness artifact imports both precise interrupt-time + // getters through the Windows realtime API set. This SDK's kernel32 import + // archive omits them; its mincore archive supplies those same OS imports. + // No clock implementation, API fallback or generated code is substituted. + println!("cargo:rustc-link-lib=mincore"); +} diff --git a/deploy/windows/clock-spnego-descriptor-trace/build.py b/deploy/windows/clock-spnego-descriptor-trace/build.py new file mode 100644 index 0000000..4008036 --- /dev/null +++ b/deploy/windows/clock-spnego-descriptor-trace/build.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Local-only isolated process privilege comparison; never starts a target.""" +import base64 +import argparse +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-descriptor-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-identity-trace/build-3800fdd9-d959-4746-953b-4a110114214d/manifest.json' +PARENT_SHA = 'd3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc' +PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-identity-trace/bcda2ede-d3e0-41bf-94e9-9f44ea785c54/diagnostic-result.json' +PARENT_RESULT_SHA = 'ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c': '43654029550c0c99904d35c381f4abfbc7b4830f28db8b92ce19acdf6971a4cf', + 'deploy/windows/clock-spnego-identity-trace/system_trace_spnego_identity.c': '39539b3994b134ec3bd2c1b0b4b7dbb548f397cfd49241f450744f94dc427784', + 'deploy/windows/clock-spnego-identity-trace/build.py': 'cd0cf6710005f3be20e4e5a907c83164979c8bfc9c72a13f9a5e1674b4301f1e', + 'deploy/windows/clock-spnego-identity-trace/native.py': '4d1362bec09d2c1c670b73364aa31fff613c29a125596e3e1ce30180b24ad332', + 'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c': '92c7a9a6e57bc199e7ae886a87398a6af98901a5affb888cd78ab5c5b3f7a59c', + 'deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c': 'f855fe7d0a7e5bcec0138131d78bbad7b2098c9031b1a857bc8b68ef8f57cd94', + 'deploy/windows/clock-spnego-impersonate-trace/build.py': 'b8de6616d7d7caa3c2c1307f6e216594ebb9455ceabe69e99c548ac927d2cb67', + 'deploy/windows/clock-spnego-impersonate-trace/native.py': 'eeec0a83b7ee9cfed874df8ce4b44da05b5eec85a4cb2c8a775d2a032e6855a5', + 'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c': '0cdffb2a881caf770b73ba32310305f2a4bfd1bdf8fc9e4a4544448bf0c7b7ac', + 'deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c': '392f7b9f8d8eec78d6d2645d5a47db1a5e8e739259e4205c01399c176b94a19e', + 'deploy/windows/clock-spnego-privilege-trace/build.py': '7977e67a3a4ae550a5ddc3e2435bef9506a97424719c5825364a35d558dfda48', + 'deploy/windows/clock-spnego-privilege-trace/native.py': '74d1740b921d7f1f20b0c78dfaa3cd5b8d9eb19eacb6bc31403d7b1dd4018ab1', + 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c': '9d9b5d247e9fc1570a72ced2f02373582c1aed7896e2f4bf8e7e85709a287dc5', + 'deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c': 'b8ce7b360e264e35781831e58a4a3278f7b35e44f07600e832d5d4ba82e8b986', + 'deploy/windows/clock-spnego-empty-trace/build.py': 'f72b50ad6977f491b32723ef9249569e6179e3072445392689a7a0bdf29c7f64', + 'deploy/windows/clock-spnego-empty-trace/native.py': '557cf3900ed16236376a26d24e863972e38d0ac7b34d3feb4329bc7d5bc7bc01', + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', + 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147', + 'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c', + 'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c', + 'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(ROOT/'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json')=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001', 'original F6 manifest retained') + require(sha(ROOT/'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json')=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9', 'original F6 result retained') + require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original enabled-privilege RPC5 case retained') + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_descriptor.c','system_trace_spnego_descriptor.c','build.py','native.py')} + + +def main(): + parser=argparse.ArgumentParser();parser.add_argument("--control",type=int,choices=(0,1,2),required=True);args=parser.parse_args() + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego_descriptor.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_descriptor.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego_descriptor.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + parent_wrapper = ROOT / 'deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c' + parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True), + fromfile='unchanged-parent-spnego.c', tofile='new-spnego-descriptor.c')) + write(folder / 'parent-wrapper-source.diff', parent_delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'), + own_system_token_only=True,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_discovery_principal_allowed=True,null_discovery_principal_allowed=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-DRMM_CLOCK_IDENTITY_CONTROL='+str(args.control),'-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSpnegoDescriptorTrace.linked.exe']) + raw_linked = output / 'ClockSpnegoDescriptorTrace.linked.exe' + linked = output / 'ClockSpnegoDescriptorTrace.original.exe'; delivery = output / 'ClockSpnegoDescriptorTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSpnegoDescriptorTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoDescriptorTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact Empty comparison') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-descriptor-v1',identity_control=args.control,qos_version=5,auth_principal_from_fixed_sid=False,auth_principal_from_discovery=True,client_server_descriptor=True,image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_discovery_principal_allowed=True,null_discovery_principal_allowed=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-descriptor-trace/clock_rpc_spnego_descriptor.c b/deploy/windows/clock-spnego-descriptor-trace/clock_rpc_spnego_descriptor.c new file mode 100644 index 0000000..4063d58 --- /dev/null +++ b/deploy/windows/clock-spnego-descriptor-trace/clock_rpc_spnego_descriptor.c @@ -0,0 +1,300 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#ifndef RMM_CLOCK_IDENTITY_CONTROL +#error fixed diagnostic identity control required +#endif +_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls"); + +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout, + * not a fallback to an older authentication contract. MSVC also checks it + * directly against its native SDK declaration. Windows x64 is the only target. + * https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w + */ +typedef struct { + unsigned long Version, Capabilities, IdentityTracking, ImpersonationType; + unsigned long AdditionalSecurityInfoType; + union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u; + void *Sid; + unsigned int EffectiveOnly; + void *ServerSecurityDescriptor; +} RmmRpcQosV5; +_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI"); +#ifdef _MSC_VER +_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI"); +#endif +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; + uint32_t qos_version, identity_control, server_descriptor_present; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 72, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + /* Preserve a returned non-NULL empty string; the SSP decides its meaning. */ + if (high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RmmRpcQosV5 qos = {0}; + _Alignas(8) BYTE account_sid[SECURITY_MAX_SID_SIZE], service_sid[SECURITY_MAX_SID_SIZE]; + _Alignas(8) BYTE acl_buffer[sizeof(ACL)+sizeof(ACCESS_ALLOWED_ACE)+SECURITY_MAX_SID_SIZE]; + SECURITY_DESCRIPTOR descriptor; + DWORD account_bytes=sizeof(account_sid),service_bytes=sizeof(service_sid),domain_bytes=64; + WCHAR domain[64];SID_NAME_USE sid_type; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IMPERSONATE; + auth->qos_version=5;auth->identity_control=RMM_CLOCK_IDENTITY_CONTROL; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + if(!result && !CreateWellKnownSid(RMM_CLOCK_IDENTITY_CONTROL==1?WinLocalSystemSid:WinLocalServiceSid,NULL,account_sid,&account_bytes))result=GetLastError(); + if(!result && !LookupAccountNameW(NULL,RMM_CLOCK_IDENTITY_CONTROL==2?L"NT SERVICE\\RmmDiscoveryWindows":L"NT SERVICE\\W32Time",service_sid,&service_bytes,domain,&domain_bytes,&sid_type))result=GetLastError(); + if(!result && (!IsValidSid(account_sid)||!IsValidSid(service_sid)||service_bytes>sizeof(service_sid)))result=ERROR_INVALID_SID; + if(!result && !InitializeAcl((PACL)acl_buffer,sizeof(acl_buffer),ACL_REVISION))result=GetLastError(); + if(!result && !AddAccessAllowedAce((PACL)acl_buffer,ACL_REVISION,GENERIC_ALL,RMM_CLOCK_IDENTITY_CONTROL==1?account_sid:service_sid))result=GetLastError(); + if(!result && !InitializeSecurityDescriptor(&descriptor,SECURITY_DESCRIPTOR_REVISION))result=GetLastError(); + if(!result && !SetSecurityDescriptorDacl(&descriptor,TRUE,(PACL)acl_buffer,FALSE))result=GetLastError(); + if(!result)auth->server_descriptor_present=1; + qos.Version = 5; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE; + qos.Sid=NULL;qos.EffectiveOnly=TRUE;qos.ServerSecurityDescriptor=&descriptor; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego_descriptor(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-descriptor-trace/native.py b/deploy/windows/clock-spnego-descriptor-trace/native.py new file mode 100644 index 0000000..53b9a77 --- /dev/null +++ b/deploy/windows/clock-spnego-descriptor-trace/native.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-descriptor-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-descriptor-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSpnegoDescriptorDiagnostic';$case=Join-Path $root ('clock-spnego-descriptor-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoDescriptorTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoDescriptorDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true;service_exit_code=$s.ExitCode} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$before=$null;$beforeFile=Join-Path $case 'privilege-before.json';if(Test-Path -LiteralPath $beforeFile){$before=Get-RmmTraceJson $beforeFile} +$adjust=$null;$adjustFile=Join-Path $case 'privilege-adjustment.json';if(Test-Path -LiteralPath $adjustFile){$adjust=Get-RmmTraceJson $adjustFile} +$cleaned=$false;$cleanedExit=$null;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true-or$null-eq$c.service_exit_code-or$c.service_exit_code-lt0-or$c.service_exit_code-gt4294967295){throw 'Bound cleanup receipt'};$cleaned=$true;$cleanedExit=$c.service_exit_code} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;cleaned_service_exit_code=$cleanedExit;report=$report;token_before_rpc=$token;privilege_before=$before;privilege_adjustment=$adjust;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true;own_privilege_adjustment=$true;foreign_token_query_only=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-descriptor-v1' and value['schema_version'] == 1 + and type(value['identity_control']) is int and value['identity_control'] in (0,1,2) and value['qos_version']==5 and value['auth_principal_from_fixed_sid'] is False and value['auth_principal_from_discovery'] is True and value['client_server_descriptor'] is True + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is False and value['own_token_privilege_adjustment'] is True and value['peer_token_query_only'] is True and value['max_enables']==value['max_restores']==1 and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'one own-token privilege adjustment/restore, peer QUERY only, no fallback/identity claim') + require(value['parent_manifest_sha256']=='d3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc' + and value['parent_result_sha256']=='ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c' + and value['returned_empty_discovery_principal_allowed'] is True and value['null_discovery_principal_allowed'] is False + and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'], + 'exact enabled-privilege parent; one explicit local impersonation-level comparison, no fallback') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_rpc_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True and value['own_privilege_adjustment'] is True and value['foreign_token_query_only'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-descriptor-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is False and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin','qos_version','identity_control','server_descriptor_present'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['qos_version']==5 and auth['identity_control'] in (0,1,2) and auth['server_descriptor_present'] in (0,1) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==3 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['server_descriptor_present']==1 and auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True and value.get('cleaned_service_exit_code')==0) + + +def numeric(value): + return type(value) is int and 0<=value<2**32 + + +def validate_snapshot(value): + fields={'present','query_status','token_id','authentication_id','modified_id','expiration_time','token_type','impersonation_level','dynamic_charged','dynamic_available','group_count','privilege_count','privileges'} + require(isinstance(value,dict) and set(value)==fields,'exact numeric token snapshot') + for k in fields-{'token_id','authentication_id','modified_id','expiration_time','privileges'}: + require(numeric(value[k]),'numeric token statistic') + for k in ('token_id','authentication_id','modified_id','expiration_time'): + require(isinstance(value[k],list) and len(value[k])==2 and all(numeric(v) for v in value[k]),'numeric LUID/time pair') + require(value['present']==1 and value['query_status']==0 and value['token_type']==1,'queried primary token') + privileges=value['privileges'] + require(isinstance(privileges,list) and len(privileges)==value['privilege_count']<=256 + and all(isinstance(p,list) and len(p)==3 and all(numeric(n) for n in p) for p in privileges),'bounded complete privilege list') + keys=[(p[1],p[0]) for p in privileges] + require(keys==sorted(set(keys)),'sorted unique privilege LUIDs') + + +def same_identity(before,after): + return all(before[k]==after[k] for k in ('token_id','authentication_id','token_type')) + + +def check_privilege_evidence(value): + before=value.get('privilege_before');change=value.get('privilege_adjustment') + if before is None or change is None:return False + require(set(before)=={'schema_version','own_pid','own_creation','own','peers'} and before['schema_version']==1 + and numeric(before['own_pid']) and before['own_pid']>0 and isinstance(before['own_creation'],list) and len(before['own_creation'])==2 and all(numeric(v) for v in before['own_creation']),'bound pre-enable numeric witness') + validate_snapshot(before['own']) + require(isinstance(before['peers'],list) and len(before['peers'])==4,'four named peer witnesses') + for i,peer in enumerate(before['peers']): + require(set(peer)=={'role','pid','creation','token'} and peer['role']==i and numeric(peer['pid']) and peer['pid']>0 and peer['pid']!=before['own_pid'] + and isinstance(peer['creation'],list) and len(peer['creation'])==2 and all(numeric(v) for v in peer['creation']),'held peer PID/start binding') + validate_snapshot(peer['token']) + require(peer['token']['token_id']!=before['own']['token_id'],'different actual peer token object') + fields={'schema_version','preflight_status','enable_attempted','enable_return','enable_error','previous_count','previous_bytes','previous_luid','previous_attributes','active_status','rpc_attempted','restore_attempted','restore_return','restore_error','restore_input_from_previous','restored_status','peer_after_status','restoration_verified','flow_status','target_luid','active','restored','peers_after'} + require(set(change)==fields and all(numeric(change[k]) for k in fields-{'previous_luid','target_luid','active','restored','peers_after'}),'exact bounded adjustment witness') + for k in ('previous_luid','target_luid'): + require(isinstance(change[k],list) and len(change[k])==2 and all(numeric(n) for n in change[k]),'exact privilege LUID') + target=change['target_luid'] + expected=[p.copy() for p in before['own']['privileges']] + targets=[p for p in expected if p[:2]==target] + require(len(targets)==1 and targets[0][2]==0,'exact one present originally disabled privilege') + require(change['schema_version']==1 and change['preflight_status']==0 + and all(change[k] in (0,1) for k in ('enable_attempted','enable_return','rpc_attempted','restore_attempted','restore_return','restore_input_from_previous','restoration_verified')),'one bounded activation/restore flow') + # Failure reports remain available raw. Never call them preserved/complete. + if change['flow_status']!=0 or change['restoration_verified']!=1:return False + require(change['enable_attempted']==change['enable_return']==change['restore_attempted']==change['restore_return']==change['restore_input_from_previous']==1 + and change['enable_error']==change['restore_error']==change['active_status']==change['restored_status']==change['peer_after_status']==0 + and change['previous_count']==1 and change['previous_bytes']==16 and change['previous_luid']==target and change['previous_attributes']==0, + 'one successful exact enable and PreviousState restore, not TRUE/NOT_ALL_ASSIGNED') + validate_snapshot(change['active']);validate_snapshot(change['restored']) + targets[0][2]=2 + require(same_identity(before['own'],change['active']) and same_identity(before['own'],change['restored']) + and change['active']['privileges']==expected and change['restored']['privileges']==before['own']['privileges'], + 'same own token only target enable bit changes and exact original attributes restored') + require(isinstance(change['peers_after'],list) and len(change['peers_after'])==4,'four post-restore peer snapshots') + for peer,after in zip(before['peers'],change['peers_after']): + validate_snapshot(after) + require(same_identity(peer['token'],after) and peer['token']['modified_id']==after['modified_id'] + and peer['token']['privileges']==after['privileges'],'observed peer token and privilege state preserved') + require(change['rpc_attempted']==1 and value['report']['query_invocations']<=1,'at most one RPC function after verified enable') + return True + + +def check_report(value,ident): + rpc_complete=check_rpc_report(value,ident) + privilege_complete=check_privilege_evidence(value) + return rpc_complete and privilege_complete + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-descriptor-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-descriptor-trace-'+ident+'/ClockSpnegoDescriptorTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if result.get("report") is not None:require(result["report"]["auth"]["identity_control"]==value["identity_control"],"actual compiled identity control matches original manifest") + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-descriptor-trace/system_trace_spnego_descriptor.c b/deploy/windows/clock-spnego-descriptor-trace/system_trace_spnego_descriptor.c new file mode 100644 index 0000000..1dcf977 --- /dev/null +++ b/deploy/windows/clock-spnego-descriptor-trace/system_trace_spnego_descriptor.c @@ -0,0 +1,501 @@ +/* Isolated own-process privilege comparison. Original MIDL/Auth unchanged. + * One existing own privilege enabled and restored; peer tokens QUERY only. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#ifndef RMM_CLOCK_IDENTITY_CONTROL +#error fixed diagnostic identity control required +#endif +_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls"); + +#include +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; + uint32_t qos_version, identity_control, server_descriptor_present; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 72, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego_descriptor(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSpnegoDescriptorDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-descriptor-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer + * handles request TOKEN_QUERY only and are retained until the final readback. */ +typedef struct { + DWORD present, query_status; + TOKEN_STATISTICS statistics; + DWORD count; + LUID_AND_ATTRIBUTES privileges[256]; +} TokenSnapshot; +typedef struct { + HANDLE process, token; + SC_HANDLE service; + DWORD pid; + FILETIME creation; + TokenSnapshot before, after; +} Peer; +typedef struct { + HANDLE own; + SC_HANDLE manager; + FILETIME creation; + Peer peers[4]; /* SCM, W32Time, agent, helper */ + TokenSnapshot before, active, restored; + LUID privilege; + DWORD preflight_status, enable_attempted, enable_return, enable_error; + DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes; + DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error; + DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status; +} PrivilegeContext; + +static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;} +static int luid_before(LUID a, LUID b) { + return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPartquery_status=ERROR_INVALID_DATA; + if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError(); + else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA; + if (!status) { + needed=0; + if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed) + || GetLastError()!=ERROR_INSUFFICIENT_BUFFER || neededsizeof(storage)) status=ERROR_INVALID_DATA; + else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError(); + else { + TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage; + if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage) + || offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA; + else { + out->count=value->PrivilegeCount; + for (DWORD i=0;icount;++i) out->privileges[i]=value->Privileges[i]; + for (DWORD i=1;icount;++i) { + LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i; + while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;} + out->privileges[j]=item; + } + for(DWORD i=1;icount;++i) + if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA; + } + } + } + out->query_status=status;out->present=!status;return status; +} +static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) { + return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId) + && luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId) + && a->statistics.TokenType==b->statistics.TokenType; +} +static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) { + if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA; + DWORD matched=0; + for(DWORD i=0;icount;++i) { + if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA; + DWORD attributes=a->privileges[i].Attributes; + if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;} + if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA; + } + return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD; +} +static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) { + SERVICE_STATUS_PROCESS state={0};DWORD needed=0; + if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError(); + if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE; + *pid=state.dwProcessId;return ERROR_SUCCESS; +} +static DWORD scm_pid(DWORD *pid) { + HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + if(list==INVALID_HANDLE_VALUE) return GetLastError(); + PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0; + if(!Process32FirstW(list,&entry)) status=GetLastError(); + else { + do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}} + while(Process32NextW(list,&entry)); + if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError(); + else if(found!=1) status=ERROR_INVALID_DATA; + } + CloseHandle(list);return status; +} +static DWORD thread_absent(void) { + HANDLE token=NULL; + if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;} + DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error; +} +static DWORD peer_binding(Peer *peer,DWORD index) { + DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid); + if(status) return status; + if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA; + FILETIME created,ended,kernel,user; + if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError(); + if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA; + HANDLE current=NULL;TokenSnapshot now={0}; + if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError(); + status=snapshot(current,&now);CloseHandle(current); + if(status) return status; + return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA; +} +static DWORD prepare_privilege(PrivilegeContext *ctx) { + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError(); + _Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user; + if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError(); + if(neededsizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED; + if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError(); + DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status; + if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED; + if((status=thread_absent())) return status; + if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError(); + if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status; + ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT); + if(!ctx->manager) return GetLastError(); + const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"}; + const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"}; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx->peers[i]; + if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();} + status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status; + if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA; + peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid); + if(!peer->process)return GetLastError(); + WCHAR path[512],expected[512];DWORD length=512; + if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError(); + if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA; + if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;} + else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);} + if(_wcsicmp(path,expected))return ERROR_INVALID_DATA; + FILETIME ended,kernel,user; + if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError(); + if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError(); + status=snapshot(peer->token,&peer->before);if(status)return status; + if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED; + if((status=peer_binding(peer,i)))return status; + } + return ERROR_SUCCESS; +} +static DWORD own_current(PrivilegeContext *ctx) { + HANDLE token=NULL;TokenSnapshot current={0}; + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError(); + DWORD status=snapshot(token,¤t);CloseHandle(token); + if(status)return status; + if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA; + return thread_absent(); +} +static void close_privilege(PrivilegeContext *ctx) { + for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);} + if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own); +} + +static char witness[262144]; +static size_t witness_used; +static int append(const char *format,...) { + va_list args;va_start(args,format); + int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args); + if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0; + witness_used+=(size_t)n;return 1; +} +static int append_snapshot(const TokenSnapshot *s) { + const TOKEN_STATISTICS *v=&s->statistics; + if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[", + (unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart, + (unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart, + (unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel, + (unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0; + for(DWORD i=0;icount;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0; + return append("]}"); +} +static DWORD write_before(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i]; + if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime) + || !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-before.json",witness,(DWORD)witness_used); +} +static DWORD write_adjustment(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":", + (unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error, + (unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes, + (unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error, + (unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status, + (unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart) + || !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-descriptor-v1\",\"case_id\":\"%s\"," + "\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false", + (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu,\"qos_version\":%lu,\"identity_control\":%lu,\"server_descriptor_present\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin,(unsigned long)auth->qos_version,(unsigned long)auth->identity_control,(unsigned long)auth->server_descriptor_present); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token={0};PrivilegeContext ctx={0}; + RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0}; + RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=3;auth.qos_version=5;auth.identity_control=RMM_CLOCK_IDENTITY_CONTROL; + DWORD result=own_system_token(&token),rpc=0; + DWORD token_write=write_token(&token); /* durable old numeric probe */ + if(!result)result=token_write; + if(!result)result=prepare_privilege(&ctx); + if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */ + ctx.preflight_status=result; + if(!result) { + TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0; + enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege; + enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED; + restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */ + ctx.enable_attempted=1; /* all paths after this call execute the one restore */ + SetLastError(ERROR_SUCCESS); + ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes); + ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes; + if(previous.PrivilegeCount==1) { + ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart; + ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart; + ctx.previous_attributes=previous.Privileges[0].Attributes; + if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege) + && previous.Privileges[0].Attributes==0) { + restore=previous;ctx.restore_input_from_previous=1; + } + } + if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous) + result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA; + if(!result)result=snapshot(ctx.own,&ctx.active); + if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1); + if(!result)result=own_current(&ctx); + for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i); + ctx.active_status=result; + if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_descriptor(&trace,&eeinfo,&auth);} + /* No report IO or early return between adjustment and this restoration. */ + ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS); + ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL); + ctx.restore_error=GetLastError(); + ctx.restored_status=snapshot(ctx.own,&ctx.restored); + if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0); + if(!ctx.restored_status)ctx.restored_status=own_current(&ctx); + ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status; + if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i); + if(!status)status=snapshot(peer->token,&peer->after); + if(!status && (!identity_equal(&peer->before,&peer->after) + || !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId) + || peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA; + for(DWORD j=0;!status && jbefore.count;++j) + if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid) + || peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA; + if(status && !ctx.peer_after_status)ctx.peer_after_status=status; + } + if(ctx.peer_after_status && !result)result=ctx.peer_after_status; + } + ctx.flow_status=result; + DWORD adjustment_write=write_adjustment(&ctx); + if(!result)result=adjustment_write; + if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;} + DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token); + if(!result)result=result_write; + close_privilege(&ctx); + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-spnego-empty-trace/build.py b/deploy/windows/clock-spnego-empty-trace/build.py new file mode 100644 index 0000000..2234f0a --- /dev/null +++ b/deploy/windows/clock-spnego-empty-trace/build.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Local-only SPNEGO comparison: retain the returned non-NULL empty principal.""" +import base64 +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-empty-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json' +PARENT_SHA = 'f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001' +PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json' +PARENT_RESULT_SHA = '4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', + 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147', + 'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c', + 'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c', + 'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original F6 and empty-principal case retained') + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_empty.c','system_trace_spnego_empty.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego_empty.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_empty.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego_empty.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + parent_wrapper = ROOT / 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c' + parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True), + fromfile='unchanged-parent-spnego.c', tofile='new-spnego-empty.c')) + write(folder / 'parent-wrapper-source.diff', parent_delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'), + own_system_token_only=True,token_query_only=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_principal_allowed=True,null_principal_allowed=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSpnegoEmptyTrace.linked.exe']) + raw_linked = output / 'ClockSpnegoEmptyTrace.linked.exe' + linked = output / 'ClockSpnegoEmptyTrace.original.exe'; delivery = output / 'ClockSpnegoEmptyTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSpnegoEmptyTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoEmptyTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact F6 comparison') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-empty-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_principal_allowed=True,null_principal_allowed=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c b/deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c new file mode 100644 index 0000000..cf40979 --- /dev/null +++ b/deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c @@ -0,0 +1,259 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + /* Preserve a returned non-NULL empty string; the SSP decides its meaning. */ + if (high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RPC_SECURITY_QOS qos = {0}; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IDENTIFY; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, &qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego_empty(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-empty-trace/native.py b/deploy/windows/clock-spnego-empty-trace/native.py new file mode 100644 index 0000000..7606fb1 --- /dev/null +++ b/deploy/windows/clock-spnego-empty-trace/native.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-empty-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-empty-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSpnegoEmptyDiagnostic';$case=Join-Path $root ('clock-spnego-empty-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoEmptyTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoEmptyDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;token_before_rpc=$token;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-empty-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is True and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'no privilege mutation/fallback or principal-as-identity claim') + require(value['parent_manifest_sha256']=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001' + and value['parent_result_sha256']=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9' + and value['returned_empty_principal_allowed'] is True and value['null_principal_allowed'] is False + and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'], + 'exact F6 comparison, returned non-NULL string only; no fabricated target or fallback') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-empty-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==2 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True) + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-empty-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-empty-trace-'+ident+'/ClockSpnegoEmptyTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c b/deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c new file mode 100644 index 0000000..d8ff0da --- /dev/null +++ b/deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c @@ -0,0 +1,233 @@ +/* Isolated SPNEGO diagnostic. Original MIDL remains unchanged. Read the own + * SYSTEM token first; one management discovery, then at most one status query. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego_empty(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSpnegoEmptyDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-empty-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-empty-v1\",\"case_id\":\"%s\"," + "\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token = {0}; + DWORD result = own_system_token(&token); + DWORD token_write = write_token(&token); /* durable numeric witness before RPC */ + if (!result) result = token_write; + if (!result) { + RmmClockTrace trace = {0}; + RmmClockEeInfo eeinfo = {0}; + RmmClockAuthTrace auth = {0}; + uint32_t rpc = rmm_clock_query_trace_spnego_empty(&trace, &eeinfo, &auth); + result = write_result(rpc, &trace, &eeinfo, &auth, &token); + } + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-spnego-identity-trace/build.py b/deploy/windows/clock-spnego-identity-trace/build.py new file mode 100644 index 0000000..75dcbf7 --- /dev/null +++ b/deploy/windows/clock-spnego-identity-trace/build.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Local-only isolated process privilege comparison; never starts a target.""" +import base64 +import argparse +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-identity-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-impersonate-trace/build-5e18bc39-0fca-4420-87e9-c94451f7775d/manifest.json' +PARENT_SHA = '5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702' +PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-impersonate-trace/daf8205c-a110-4fb7-9ae0-f27ca1532d8f/diagnostic-result.json' +PARENT_RESULT_SHA = '26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c': '92c7a9a6e57bc199e7ae886a87398a6af98901a5affb888cd78ab5c5b3f7a59c', + 'deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c': 'f855fe7d0a7e5bcec0138131d78bbad7b2098c9031b1a857bc8b68ef8f57cd94', + 'deploy/windows/clock-spnego-impersonate-trace/build.py': 'b8de6616d7d7caa3c2c1307f6e216594ebb9455ceabe69e99c548ac927d2cb67', + 'deploy/windows/clock-spnego-impersonate-trace/native.py': 'eeec0a83b7ee9cfed874df8ce4b44da05b5eec85a4cb2c8a775d2a032e6855a5', + 'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c': '0cdffb2a881caf770b73ba32310305f2a4bfd1bdf8fc9e4a4544448bf0c7b7ac', + 'deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c': '392f7b9f8d8eec78d6d2645d5a47db1a5e8e739259e4205c01399c176b94a19e', + 'deploy/windows/clock-spnego-privilege-trace/build.py': '7977e67a3a4ae550a5ddc3e2435bef9506a97424719c5825364a35d558dfda48', + 'deploy/windows/clock-spnego-privilege-trace/native.py': '74d1740b921d7f1f20b0c78dfaa3cd5b8d9eb19eacb6bc31403d7b1dd4018ab1', + 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c': '9d9b5d247e9fc1570a72ced2f02373582c1aed7896e2f4bf8e7e85709a287dc5', + 'deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c': 'b8ce7b360e264e35781831e58a4a3278f7b35e44f07600e832d5d4ba82e8b986', + 'deploy/windows/clock-spnego-empty-trace/build.py': 'f72b50ad6977f491b32723ef9249569e6179e3072445392689a7a0bdf29c7f64', + 'deploy/windows/clock-spnego-empty-trace/native.py': '557cf3900ed16236376a26d24e863972e38d0ac7b34d3feb4329bc7d5bc7bc01', + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', + 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147', + 'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c', + 'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c', + 'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(ROOT/'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json')=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001', 'original F6 manifest retained') + require(sha(ROOT/'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json')=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9', 'original F6 result retained') + require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original enabled-privilege RPC5 case retained') + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_identity.c','system_trace_spnego_identity.c','build.py','native.py')} + + +def main(): + parser=argparse.ArgumentParser();parser.add_argument("--control",type=int,choices=(0,1,2),required=True);args=parser.parse_args() + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego_identity.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_identity.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego_identity.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + parent_wrapper = ROOT / 'deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c' + parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True), + fromfile='unchanged-parent-spnego.c', tofile='new-spnego-identity.c')) + write(folder / 'parent-wrapper-source.diff', parent_delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'), + own_system_token_only=True,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_discovery_principal_allowed=True,null_discovery_principal_allowed=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-DRMM_CLOCK_IDENTITY_CONTROL='+str(args.control),'-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSpnegoIdentityTrace.linked.exe']) + raw_linked = output / 'ClockSpnegoIdentityTrace.linked.exe' + linked = output / 'ClockSpnegoIdentityTrace.original.exe'; delivery = output / 'ClockSpnegoIdentityTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSpnegoIdentityTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoIdentityTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact Empty comparison') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-identity-v1',identity_control=args.control,qos_version=5,auth_principal_from_fixed_sid=True,client_server_descriptor=True,image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_discovery_principal_allowed=True,null_discovery_principal_allowed=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c b/deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c new file mode 100644 index 0000000..5089b11 --- /dev/null +++ b/deploy/windows/clock-spnego-identity-trace/clock_rpc_spnego_identity.c @@ -0,0 +1,300 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#ifndef RMM_CLOCK_IDENTITY_CONTROL +#error fixed diagnostic identity control required +#endif +_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls"); + +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout, + * not a fallback to an older authentication contract. MSVC also checks it + * directly against its native SDK declaration. Windows x64 is the only target. + * https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w + */ +typedef struct { + unsigned long Version, Capabilities, IdentityTracking, ImpersonationType; + unsigned long AdditionalSecurityInfoType; + union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u; + void *Sid; + unsigned int EffectiveOnly; + void *ServerSecurityDescriptor; +} RmmRpcQosV5; +_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI"); +#ifdef _MSC_VER +_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI"); +_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI"); +#endif +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; + uint32_t qos_version, identity_control, server_descriptor_present; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 72, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + /* Preserve a returned non-NULL empty string; the SSP decides its meaning. */ + if (high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RmmRpcQosV5 qos = {0}; + _Alignas(8) BYTE account_sid[SECURITY_MAX_SID_SIZE], service_sid[SECURITY_MAX_SID_SIZE]; + _Alignas(8) BYTE acl_buffer[sizeof(ACL)+sizeof(ACCESS_ALLOWED_ACE)+SECURITY_MAX_SID_SIZE]; + SECURITY_DESCRIPTOR descriptor; + DWORD account_bytes=sizeof(account_sid),service_bytes=sizeof(service_sid),domain_bytes=64; + WCHAR domain[64];SID_NAME_USE sid_type; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IMPERSONATE; + auth->qos_version=5;auth->identity_control=RMM_CLOCK_IDENTITY_CONTROL; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + if(!result && !CreateWellKnownSid(RMM_CLOCK_IDENTITY_CONTROL==1?WinLocalSystemSid:WinLocalServiceSid,NULL,account_sid,&account_bytes))result=GetLastError(); + if(!result && !LookupAccountNameW(NULL,RMM_CLOCK_IDENTITY_CONTROL==2?L"NT SERVICE\\RmmDiscoveryWindows":L"NT SERVICE\\W32Time",service_sid,&service_bytes,domain,&domain_bytes,&sid_type))result=GetLastError(); + if(!result && (!IsValidSid(account_sid)||!IsValidSid(service_sid)||service_bytes>sizeof(service_sid)))result=ERROR_INVALID_SID; + if(!result && !InitializeAcl((PACL)acl_buffer,sizeof(acl_buffer),ACL_REVISION))result=GetLastError(); + if(!result && !AddAccessAllowedAce((PACL)acl_buffer,ACL_REVISION,GENERIC_ALL,service_sid))result=GetLastError(); + if(!result && !InitializeSecurityDescriptor(&descriptor,SECURITY_DESCRIPTOR_REVISION))result=GetLastError(); + if(!result && !SetSecurityDescriptorDacl(&descriptor,TRUE,(PACL)acl_buffer,FALSE))result=GetLastError(); + if(!result)auth->server_descriptor_present=1; + qos.Version = 5; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE; + qos.Sid=account_sid;qos.EffectiveOnly=TRUE;qos.ServerSecurityDescriptor=&descriptor; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego_identity(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-identity-trace/native.py b/deploy/windows/clock-spnego-identity-trace/native.py new file mode 100644 index 0000000..d2555af --- /dev/null +++ b/deploy/windows/clock-spnego-identity-trace/native.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-identity-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-identity-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSpnegoIdentityDiagnostic';$case=Join-Path $root ('clock-spnego-identity-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoIdentityTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoIdentityDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true;service_exit_code=$s.ExitCode} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$before=$null;$beforeFile=Join-Path $case 'privilege-before.json';if(Test-Path -LiteralPath $beforeFile){$before=Get-RmmTraceJson $beforeFile} +$adjust=$null;$adjustFile=Join-Path $case 'privilege-adjustment.json';if(Test-Path -LiteralPath $adjustFile){$adjust=Get-RmmTraceJson $adjustFile} +$cleaned=$false;$cleanedExit=$null;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true-or$null-eq$c.service_exit_code-or$c.service_exit_code-lt0-or$c.service_exit_code-gt4294967295){throw 'Bound cleanup receipt'};$cleaned=$true;$cleanedExit=$c.service_exit_code} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;cleaned_service_exit_code=$cleanedExit;report=$report;token_before_rpc=$token;privilege_before=$before;privilege_adjustment=$adjust;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true;own_privilege_adjustment=$true;foreign_token_query_only=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-identity-v1' and value['schema_version'] == 1 + and type(value['identity_control']) is int and value['identity_control'] in (0,1,2) and value['qos_version']==5 and value['auth_principal_from_fixed_sid'] is True and value['client_server_descriptor'] is True + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is False and value['own_token_privilege_adjustment'] is True and value['peer_token_query_only'] is True and value['max_enables']==value['max_restores']==1 and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'one own-token privilege adjustment/restore, peer QUERY only, no fallback/identity claim') + require(value['parent_manifest_sha256']=='5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702' + and value['parent_result_sha256']=='26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e' + and value['returned_empty_discovery_principal_allowed'] is True and value['null_discovery_principal_allowed'] is False + and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'], + 'exact enabled-privilege parent; one explicit local impersonation-level comparison, no fallback') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_rpc_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True and value['own_privilege_adjustment'] is True and value['foreign_token_query_only'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-identity-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is False and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin','qos_version','identity_control','server_descriptor_present'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['qos_version']==5 and auth['identity_control'] in (0,1,2) and auth['server_descriptor_present'] in (0,1) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==3 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['server_descriptor_present']==1 and auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True and value.get('cleaned_service_exit_code')==0) + + +def numeric(value): + return type(value) is int and 0<=value<2**32 + + +def validate_snapshot(value): + fields={'present','query_status','token_id','authentication_id','modified_id','expiration_time','token_type','impersonation_level','dynamic_charged','dynamic_available','group_count','privilege_count','privileges'} + require(isinstance(value,dict) and set(value)==fields,'exact numeric token snapshot') + for k in fields-{'token_id','authentication_id','modified_id','expiration_time','privileges'}: + require(numeric(value[k]),'numeric token statistic') + for k in ('token_id','authentication_id','modified_id','expiration_time'): + require(isinstance(value[k],list) and len(value[k])==2 and all(numeric(v) for v in value[k]),'numeric LUID/time pair') + require(value['present']==1 and value['query_status']==0 and value['token_type']==1,'queried primary token') + privileges=value['privileges'] + require(isinstance(privileges,list) and len(privileges)==value['privilege_count']<=256 + and all(isinstance(p,list) and len(p)==3 and all(numeric(n) for n in p) for p in privileges),'bounded complete privilege list') + keys=[(p[1],p[0]) for p in privileges] + require(keys==sorted(set(keys)),'sorted unique privilege LUIDs') + + +def same_identity(before,after): + return all(before[k]==after[k] for k in ('token_id','authentication_id','token_type')) + + +def check_privilege_evidence(value): + before=value.get('privilege_before');change=value.get('privilege_adjustment') + if before is None or change is None:return False + require(set(before)=={'schema_version','own_pid','own_creation','own','peers'} and before['schema_version']==1 + and numeric(before['own_pid']) and before['own_pid']>0 and isinstance(before['own_creation'],list) and len(before['own_creation'])==2 and all(numeric(v) for v in before['own_creation']),'bound pre-enable numeric witness') + validate_snapshot(before['own']) + require(isinstance(before['peers'],list) and len(before['peers'])==4,'four named peer witnesses') + for i,peer in enumerate(before['peers']): + require(set(peer)=={'role','pid','creation','token'} and peer['role']==i and numeric(peer['pid']) and peer['pid']>0 and peer['pid']!=before['own_pid'] + and isinstance(peer['creation'],list) and len(peer['creation'])==2 and all(numeric(v) for v in peer['creation']),'held peer PID/start binding') + validate_snapshot(peer['token']) + require(peer['token']['token_id']!=before['own']['token_id'],'different actual peer token object') + fields={'schema_version','preflight_status','enable_attempted','enable_return','enable_error','previous_count','previous_bytes','previous_luid','previous_attributes','active_status','rpc_attempted','restore_attempted','restore_return','restore_error','restore_input_from_previous','restored_status','peer_after_status','restoration_verified','flow_status','target_luid','active','restored','peers_after'} + require(set(change)==fields and all(numeric(change[k]) for k in fields-{'previous_luid','target_luid','active','restored','peers_after'}),'exact bounded adjustment witness') + for k in ('previous_luid','target_luid'): + require(isinstance(change[k],list) and len(change[k])==2 and all(numeric(n) for n in change[k]),'exact privilege LUID') + target=change['target_luid'] + expected=[p.copy() for p in before['own']['privileges']] + targets=[p for p in expected if p[:2]==target] + require(len(targets)==1 and targets[0][2]==0,'exact one present originally disabled privilege') + require(change['schema_version']==1 and change['preflight_status']==0 + and all(change[k] in (0,1) for k in ('enable_attempted','enable_return','rpc_attempted','restore_attempted','restore_return','restore_input_from_previous','restoration_verified')),'one bounded activation/restore flow') + # Failure reports remain available raw. Never call them preserved/complete. + if change['flow_status']!=0 or change['restoration_verified']!=1:return False + require(change['enable_attempted']==change['enable_return']==change['restore_attempted']==change['restore_return']==change['restore_input_from_previous']==1 + and change['enable_error']==change['restore_error']==change['active_status']==change['restored_status']==change['peer_after_status']==0 + and change['previous_count']==1 and change['previous_bytes']==16 and change['previous_luid']==target and change['previous_attributes']==0, + 'one successful exact enable and PreviousState restore, not TRUE/NOT_ALL_ASSIGNED') + validate_snapshot(change['active']);validate_snapshot(change['restored']) + targets[0][2]=2 + require(same_identity(before['own'],change['active']) and same_identity(before['own'],change['restored']) + and change['active']['privileges']==expected and change['restored']['privileges']==before['own']['privileges'], + 'same own token only target enable bit changes and exact original attributes restored') + require(isinstance(change['peers_after'],list) and len(change['peers_after'])==4,'four post-restore peer snapshots') + for peer,after in zip(before['peers'],change['peers_after']): + validate_snapshot(after) + require(same_identity(peer['token'],after) and peer['token']['modified_id']==after['modified_id'] + and peer['token']['privileges']==after['privileges'],'observed peer token and privilege state preserved') + require(change['rpc_attempted']==1 and value['report']['query_invocations']<=1,'at most one RPC function after verified enable') + return True + + +def check_report(value,ident): + rpc_complete=check_rpc_report(value,ident) + privilege_complete=check_privilege_evidence(value) + return rpc_complete and privilege_complete + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-identity-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-identity-trace-'+ident+'/ClockSpnegoIdentityTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if result.get("report") is not None:require(result["report"]["auth"]["identity_control"]==value["identity_control"],"actual compiled identity control matches original manifest") + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-identity-trace/system_trace_spnego_identity.c b/deploy/windows/clock-spnego-identity-trace/system_trace_spnego_identity.c new file mode 100644 index 0000000..f5d5b35 --- /dev/null +++ b/deploy/windows/clock-spnego-identity-trace/system_trace_spnego_identity.c @@ -0,0 +1,501 @@ +/* Isolated own-process privilege comparison. Original MIDL/Auth unchanged. + * One existing own privilege enabled and restored; peer tokens QUERY only. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#ifndef RMM_CLOCK_IDENTITY_CONTROL +#error fixed diagnostic identity control required +#endif +_Static_assert(RMM_CLOCK_IDENTITY_CONTROL >= 0 && RMM_CLOCK_IDENTITY_CONTROL <= 2, "closed identity controls"); + +#include +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; + uint32_t qos_version, identity_control, server_descriptor_present; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 72, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego_identity(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSpnegoIdentityDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-identity-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer + * handles request TOKEN_QUERY only and are retained until the final readback. */ +typedef struct { + DWORD present, query_status; + TOKEN_STATISTICS statistics; + DWORD count; + LUID_AND_ATTRIBUTES privileges[256]; +} TokenSnapshot; +typedef struct { + HANDLE process, token; + SC_HANDLE service; + DWORD pid; + FILETIME creation; + TokenSnapshot before, after; +} Peer; +typedef struct { + HANDLE own; + SC_HANDLE manager; + FILETIME creation; + Peer peers[4]; /* SCM, W32Time, agent, helper */ + TokenSnapshot before, active, restored; + LUID privilege; + DWORD preflight_status, enable_attempted, enable_return, enable_error; + DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes; + DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error; + DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status; +} PrivilegeContext; + +static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;} +static int luid_before(LUID a, LUID b) { + return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPartquery_status=ERROR_INVALID_DATA; + if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError(); + else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA; + if (!status) { + needed=0; + if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed) + || GetLastError()!=ERROR_INSUFFICIENT_BUFFER || neededsizeof(storage)) status=ERROR_INVALID_DATA; + else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError(); + else { + TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage; + if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage) + || offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA; + else { + out->count=value->PrivilegeCount; + for (DWORD i=0;icount;++i) out->privileges[i]=value->Privileges[i]; + for (DWORD i=1;icount;++i) { + LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i; + while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;} + out->privileges[j]=item; + } + for(DWORD i=1;icount;++i) + if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA; + } + } + } + out->query_status=status;out->present=!status;return status; +} +static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) { + return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId) + && luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId) + && a->statistics.TokenType==b->statistics.TokenType; +} +static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) { + if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA; + DWORD matched=0; + for(DWORD i=0;icount;++i) { + if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA; + DWORD attributes=a->privileges[i].Attributes; + if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;} + if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA; + } + return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD; +} +static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) { + SERVICE_STATUS_PROCESS state={0};DWORD needed=0; + if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError(); + if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE; + *pid=state.dwProcessId;return ERROR_SUCCESS; +} +static DWORD scm_pid(DWORD *pid) { + HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + if(list==INVALID_HANDLE_VALUE) return GetLastError(); + PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0; + if(!Process32FirstW(list,&entry)) status=GetLastError(); + else { + do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}} + while(Process32NextW(list,&entry)); + if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError(); + else if(found!=1) status=ERROR_INVALID_DATA; + } + CloseHandle(list);return status; +} +static DWORD thread_absent(void) { + HANDLE token=NULL; + if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;} + DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error; +} +static DWORD peer_binding(Peer *peer,DWORD index) { + DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid); + if(status) return status; + if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA; + FILETIME created,ended,kernel,user; + if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError(); + if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA; + HANDLE current=NULL;TokenSnapshot now={0}; + if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError(); + status=snapshot(current,&now);CloseHandle(current); + if(status) return status; + return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA; +} +static DWORD prepare_privilege(PrivilegeContext *ctx) { + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError(); + _Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user; + if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError(); + if(neededsizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED; + if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError(); + DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status; + if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED; + if((status=thread_absent())) return status; + if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError(); + if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status; + ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT); + if(!ctx->manager) return GetLastError(); + const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"}; + const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"}; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx->peers[i]; + if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();} + status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status; + if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA; + peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid); + if(!peer->process)return GetLastError(); + WCHAR path[512],expected[512];DWORD length=512; + if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError(); + if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA; + if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;} + else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);} + if(_wcsicmp(path,expected))return ERROR_INVALID_DATA; + FILETIME ended,kernel,user; + if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError(); + if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError(); + status=snapshot(peer->token,&peer->before);if(status)return status; + if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED; + if((status=peer_binding(peer,i)))return status; + } + return ERROR_SUCCESS; +} +static DWORD own_current(PrivilegeContext *ctx) { + HANDLE token=NULL;TokenSnapshot current={0}; + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError(); + DWORD status=snapshot(token,¤t);CloseHandle(token); + if(status)return status; + if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA; + return thread_absent(); +} +static void close_privilege(PrivilegeContext *ctx) { + for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);} + if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own); +} + +static char witness[262144]; +static size_t witness_used; +static int append(const char *format,...) { + va_list args;va_start(args,format); + int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args); + if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0; + witness_used+=(size_t)n;return 1; +} +static int append_snapshot(const TokenSnapshot *s) { + const TOKEN_STATISTICS *v=&s->statistics; + if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[", + (unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart, + (unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart, + (unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel, + (unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0; + for(DWORD i=0;icount;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0; + return append("]}"); +} +static DWORD write_before(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i]; + if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime) + || !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-before.json",witness,(DWORD)witness_used); +} +static DWORD write_adjustment(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":", + (unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error, + (unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes, + (unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error, + (unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status, + (unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart) + || !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-identity-v1\",\"case_id\":\"%s\"," + "\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false", + (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu,\"qos_version\":%lu,\"identity_control\":%lu,\"server_descriptor_present\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin,(unsigned long)auth->qos_version,(unsigned long)auth->identity_control,(unsigned long)auth->server_descriptor_present); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token={0};PrivilegeContext ctx={0}; + RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0}; + RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=3;auth.qos_version=5;auth.identity_control=RMM_CLOCK_IDENTITY_CONTROL; + DWORD result=own_system_token(&token),rpc=0; + DWORD token_write=write_token(&token); /* durable old numeric probe */ + if(!result)result=token_write; + if(!result)result=prepare_privilege(&ctx); + if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */ + ctx.preflight_status=result; + if(!result) { + TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0; + enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege; + enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED; + restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */ + ctx.enable_attempted=1; /* all paths after this call execute the one restore */ + SetLastError(ERROR_SUCCESS); + ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes); + ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes; + if(previous.PrivilegeCount==1) { + ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart; + ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart; + ctx.previous_attributes=previous.Privileges[0].Attributes; + if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege) + && previous.Privileges[0].Attributes==0) { + restore=previous;ctx.restore_input_from_previous=1; + } + } + if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous) + result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA; + if(!result)result=snapshot(ctx.own,&ctx.active); + if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1); + if(!result)result=own_current(&ctx); + for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i); + ctx.active_status=result; + if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_identity(&trace,&eeinfo,&auth);} + /* No report IO or early return between adjustment and this restoration. */ + ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS); + ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL); + ctx.restore_error=GetLastError(); + ctx.restored_status=snapshot(ctx.own,&ctx.restored); + if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0); + if(!ctx.restored_status)ctx.restored_status=own_current(&ctx); + ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status; + if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i); + if(!status)status=snapshot(peer->token,&peer->after); + if(!status && (!identity_equal(&peer->before,&peer->after) + || !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId) + || peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA; + for(DWORD j=0;!status && jbefore.count;++j) + if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid) + || peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA; + if(status && !ctx.peer_after_status)ctx.peer_after_status=status; + } + if(ctx.peer_after_status && !result)result=ctx.peer_after_status; + } + ctx.flow_status=result; + DWORD adjustment_write=write_adjustment(&ctx); + if(!result)result=adjustment_write; + if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;} + DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token); + if(!result)result=result_write; + close_privilege(&ctx); + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-spnego-impersonate-trace/build.py b/deploy/windows/clock-spnego-impersonate-trace/build.py new file mode 100644 index 0000000..a3c7f14 --- /dev/null +++ b/deploy/windows/clock-spnego-impersonate-trace/build.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Local-only isolated process privilege comparison; never starts a target.""" +import base64 +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-impersonate-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json' +PARENT_SHA = '6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3' +PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-privilege-trace/6de04277-6bec-477d-b1c9-bfca88a9cd78/diagnostic-result.json' +PARENT_RESULT_SHA = 'c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c': '0cdffb2a881caf770b73ba32310305f2a4bfd1bdf8fc9e4a4544448bf0c7b7ac', + 'deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c': '392f7b9f8d8eec78d6d2645d5a47db1a5e8e739259e4205c01399c176b94a19e', + 'deploy/windows/clock-spnego-privilege-trace/build.py': '7977e67a3a4ae550a5ddc3e2435bef9506a97424719c5825364a35d558dfda48', + 'deploy/windows/clock-spnego-privilege-trace/native.py': '74d1740b921d7f1f20b0c78dfaa3cd5b8d9eb19eacb6bc31403d7b1dd4018ab1', + 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c': '9d9b5d247e9fc1570a72ced2f02373582c1aed7896e2f4bf8e7e85709a287dc5', + 'deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c': 'b8ce7b360e264e35781831e58a4a3278f7b35e44f07600e832d5d4ba82e8b986', + 'deploy/windows/clock-spnego-empty-trace/build.py': 'f72b50ad6977f491b32723ef9249569e6179e3072445392689a7a0bdf29c7f64', + 'deploy/windows/clock-spnego-empty-trace/native.py': '557cf3900ed16236376a26d24e863972e38d0ac7b34d3feb4329bc7d5bc7bc01', + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', + 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147', + 'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c', + 'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c', + 'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(ROOT/'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json')=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001', 'original F6 manifest retained') + require(sha(ROOT/'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json')=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9', 'original F6 result retained') + require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original enabled-privilege RPC5 case retained') + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_impersonate.c','system_trace_spnego_impersonate.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego_impersonate.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_impersonate.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego_impersonate.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + parent_wrapper = ROOT / 'deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c' + parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True), + fromfile='unchanged-parent-spnego.c', tofile='new-spnego-impersonate.c')) + write(folder / 'parent-wrapper-source.diff', parent_delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'), + own_system_token_only=True,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_principal_allowed=True,null_principal_allowed=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSpnegoImpersonateTrace.linked.exe']) + raw_linked = output / 'ClockSpnegoImpersonateTrace.linked.exe' + linked = output / 'ClockSpnegoImpersonateTrace.original.exe'; delivery = output / 'ClockSpnegoImpersonateTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSpnegoImpersonateTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoImpersonateTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact Empty comparison') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-impersonate-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_principal_allowed=True,null_principal_allowed=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c b/deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c new file mode 100644 index 0000000..62aff88 --- /dev/null +++ b/deploy/windows/clock-spnego-impersonate-trace/clock_rpc_spnego_impersonate.c @@ -0,0 +1,259 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + /* Preserve a returned non-NULL empty string; the SSP decides its meaning. */ + if (high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RPC_SECURITY_QOS qos = {0}; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IMPERSONATE; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, &qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego_impersonate(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-impersonate-trace/native.py b/deploy/windows/clock-spnego-impersonate-trace/native.py new file mode 100644 index 0000000..14894e9 --- /dev/null +++ b/deploy/windows/clock-spnego-impersonate-trace/native.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-impersonate-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-impersonate-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSpnegoImpersonateDiagnostic';$case=Join-Path $root ('clock-spnego-impersonate-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoImpersonateTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoImpersonateDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true;service_exit_code=$s.ExitCode} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$before=$null;$beforeFile=Join-Path $case 'privilege-before.json';if(Test-Path -LiteralPath $beforeFile){$before=Get-RmmTraceJson $beforeFile} +$adjust=$null;$adjustFile=Join-Path $case 'privilege-adjustment.json';if(Test-Path -LiteralPath $adjustFile){$adjust=Get-RmmTraceJson $adjustFile} +$cleaned=$false;$cleanedExit=$null;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true-or$null-eq$c.service_exit_code-or$c.service_exit_code-lt0-or$c.service_exit_code-gt4294967295){throw 'Bound cleanup receipt'};$cleaned=$true;$cleanedExit=$c.service_exit_code} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;cleaned_service_exit_code=$cleanedExit;report=$report;token_before_rpc=$token;privilege_before=$before;privilege_adjustment=$adjust;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true;own_privilege_adjustment=$true;foreign_token_query_only=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-impersonate-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is False and value['own_token_privilege_adjustment'] is True and value['peer_token_query_only'] is True and value['max_enables']==value['max_restores']==1 and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'one own-token privilege adjustment/restore, peer QUERY only, no fallback/identity claim') + require(value['parent_manifest_sha256']=='6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3' + and value['parent_result_sha256']=='c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152' + and value['returned_empty_principal_allowed'] is True and value['null_principal_allowed'] is False + and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'], + 'exact enabled-privilege parent; one explicit local impersonation-level comparison, no fallback') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_rpc_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True and value['own_privilege_adjustment'] is True and value['foreign_token_query_only'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-impersonate-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is False and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==3 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True and value.get('cleaned_service_exit_code')==0) + + +def numeric(value): + return type(value) is int and 0<=value<2**32 + + +def validate_snapshot(value): + fields={'present','query_status','token_id','authentication_id','modified_id','expiration_time','token_type','impersonation_level','dynamic_charged','dynamic_available','group_count','privilege_count','privileges'} + require(isinstance(value,dict) and set(value)==fields,'exact numeric token snapshot') + for k in fields-{'token_id','authentication_id','modified_id','expiration_time','privileges'}: + require(numeric(value[k]),'numeric token statistic') + for k in ('token_id','authentication_id','modified_id','expiration_time'): + require(isinstance(value[k],list) and len(value[k])==2 and all(numeric(v) for v in value[k]),'numeric LUID/time pair') + require(value['present']==1 and value['query_status']==0 and value['token_type']==1,'queried primary token') + privileges=value['privileges'] + require(isinstance(privileges,list) and len(privileges)==value['privilege_count']<=256 + and all(isinstance(p,list) and len(p)==3 and all(numeric(n) for n in p) for p in privileges),'bounded complete privilege list') + keys=[(p[1],p[0]) for p in privileges] + require(keys==sorted(set(keys)),'sorted unique privilege LUIDs') + + +def same_identity(before,after): + return all(before[k]==after[k] for k in ('token_id','authentication_id','token_type')) + + +def check_privilege_evidence(value): + before=value.get('privilege_before');change=value.get('privilege_adjustment') + if before is None or change is None:return False + require(set(before)=={'schema_version','own_pid','own_creation','own','peers'} and before['schema_version']==1 + and numeric(before['own_pid']) and before['own_pid']>0 and isinstance(before['own_creation'],list) and len(before['own_creation'])==2 and all(numeric(v) for v in before['own_creation']),'bound pre-enable numeric witness') + validate_snapshot(before['own']) + require(isinstance(before['peers'],list) and len(before['peers'])==4,'four named peer witnesses') + for i,peer in enumerate(before['peers']): + require(set(peer)=={'role','pid','creation','token'} and peer['role']==i and numeric(peer['pid']) and peer['pid']>0 and peer['pid']!=before['own_pid'] + and isinstance(peer['creation'],list) and len(peer['creation'])==2 and all(numeric(v) for v in peer['creation']),'held peer PID/start binding') + validate_snapshot(peer['token']) + require(peer['token']['token_id']!=before['own']['token_id'],'different actual peer token object') + fields={'schema_version','preflight_status','enable_attempted','enable_return','enable_error','previous_count','previous_bytes','previous_luid','previous_attributes','active_status','rpc_attempted','restore_attempted','restore_return','restore_error','restore_input_from_previous','restored_status','peer_after_status','restoration_verified','flow_status','target_luid','active','restored','peers_after'} + require(set(change)==fields and all(numeric(change[k]) for k in fields-{'previous_luid','target_luid','active','restored','peers_after'}),'exact bounded adjustment witness') + for k in ('previous_luid','target_luid'): + require(isinstance(change[k],list) and len(change[k])==2 and all(numeric(n) for n in change[k]),'exact privilege LUID') + target=change['target_luid'] + expected=[p.copy() for p in before['own']['privileges']] + targets=[p for p in expected if p[:2]==target] + require(len(targets)==1 and targets[0][2]==0,'exact one present originally disabled privilege') + require(change['schema_version']==1 and change['preflight_status']==0 + and all(change[k] in (0,1) for k in ('enable_attempted','enable_return','rpc_attempted','restore_attempted','restore_return','restore_input_from_previous','restoration_verified')),'one bounded activation/restore flow') + # Failure reports remain available raw. Never call them preserved/complete. + if change['flow_status']!=0 or change['restoration_verified']!=1:return False + require(change['enable_attempted']==change['enable_return']==change['restore_attempted']==change['restore_return']==change['restore_input_from_previous']==1 + and change['enable_error']==change['restore_error']==change['active_status']==change['restored_status']==change['peer_after_status']==0 + and change['previous_count']==1 and change['previous_bytes']==16 and change['previous_luid']==target and change['previous_attributes']==0, + 'one successful exact enable and PreviousState restore, not TRUE/NOT_ALL_ASSIGNED') + validate_snapshot(change['active']);validate_snapshot(change['restored']) + targets[0][2]=2 + require(same_identity(before['own'],change['active']) and same_identity(before['own'],change['restored']) + and change['active']['privileges']==expected and change['restored']['privileges']==before['own']['privileges'], + 'same own token only target enable bit changes and exact original attributes restored') + require(isinstance(change['peers_after'],list) and len(change['peers_after'])==4,'four post-restore peer snapshots') + for peer,after in zip(before['peers'],change['peers_after']): + validate_snapshot(after) + require(same_identity(peer['token'],after) and peer['token']['modified_id']==after['modified_id'] + and peer['token']['privileges']==after['privileges'],'observed peer token and privilege state preserved') + require(change['rpc_attempted']==1 and value['report']['query_invocations']<=1,'at most one RPC function after verified enable') + return True + + +def check_report(value,ident): + rpc_complete=check_rpc_report(value,ident) + privilege_complete=check_privilege_evidence(value) + return rpc_complete and privilege_complete + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-impersonate-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-impersonate-trace-'+ident+'/ClockSpnegoImpersonateTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c b/deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c new file mode 100644 index 0000000..957c495 --- /dev/null +++ b/deploy/windows/clock-spnego-impersonate-trace/system_trace_spnego_impersonate.c @@ -0,0 +1,495 @@ +/* Isolated own-process privilege comparison. Original MIDL/Auth unchanged. + * One existing own privilege enabled and restored; peer tokens QUERY only. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego_impersonate(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSpnegoImpersonateDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-impersonate-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer + * handles request TOKEN_QUERY only and are retained until the final readback. */ +typedef struct { + DWORD present, query_status; + TOKEN_STATISTICS statistics; + DWORD count; + LUID_AND_ATTRIBUTES privileges[256]; +} TokenSnapshot; +typedef struct { + HANDLE process, token; + SC_HANDLE service; + DWORD pid; + FILETIME creation; + TokenSnapshot before, after; +} Peer; +typedef struct { + HANDLE own; + SC_HANDLE manager; + FILETIME creation; + Peer peers[4]; /* SCM, W32Time, agent, helper */ + TokenSnapshot before, active, restored; + LUID privilege; + DWORD preflight_status, enable_attempted, enable_return, enable_error; + DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes; + DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error; + DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status; +} PrivilegeContext; + +static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;} +static int luid_before(LUID a, LUID b) { + return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPartquery_status=ERROR_INVALID_DATA; + if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError(); + else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA; + if (!status) { + needed=0; + if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed) + || GetLastError()!=ERROR_INSUFFICIENT_BUFFER || neededsizeof(storage)) status=ERROR_INVALID_DATA; + else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError(); + else { + TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage; + if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage) + || offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA; + else { + out->count=value->PrivilegeCount; + for (DWORD i=0;icount;++i) out->privileges[i]=value->Privileges[i]; + for (DWORD i=1;icount;++i) { + LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i; + while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;} + out->privileges[j]=item; + } + for(DWORD i=1;icount;++i) + if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA; + } + } + } + out->query_status=status;out->present=!status;return status; +} +static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) { + return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId) + && luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId) + && a->statistics.TokenType==b->statistics.TokenType; +} +static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) { + if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA; + DWORD matched=0; + for(DWORD i=0;icount;++i) { + if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA; + DWORD attributes=a->privileges[i].Attributes; + if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;} + if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA; + } + return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD; +} +static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) { + SERVICE_STATUS_PROCESS state={0};DWORD needed=0; + if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError(); + if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE; + *pid=state.dwProcessId;return ERROR_SUCCESS; +} +static DWORD scm_pid(DWORD *pid) { + HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + if(list==INVALID_HANDLE_VALUE) return GetLastError(); + PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0; + if(!Process32FirstW(list,&entry)) status=GetLastError(); + else { + do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}} + while(Process32NextW(list,&entry)); + if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError(); + else if(found!=1) status=ERROR_INVALID_DATA; + } + CloseHandle(list);return status; +} +static DWORD thread_absent(void) { + HANDLE token=NULL; + if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;} + DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error; +} +static DWORD peer_binding(Peer *peer,DWORD index) { + DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid); + if(status) return status; + if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA; + FILETIME created,ended,kernel,user; + if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError(); + if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA; + HANDLE current=NULL;TokenSnapshot now={0}; + if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError(); + status=snapshot(current,&now);CloseHandle(current); + if(status) return status; + return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA; +} +static DWORD prepare_privilege(PrivilegeContext *ctx) { + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError(); + _Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user; + if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError(); + if(neededsizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED; + if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError(); + DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status; + if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED; + if((status=thread_absent())) return status; + if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError(); + if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status; + ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT); + if(!ctx->manager) return GetLastError(); + const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"}; + const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"}; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx->peers[i]; + if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();} + status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status; + if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA; + peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid); + if(!peer->process)return GetLastError(); + WCHAR path[512],expected[512];DWORD length=512; + if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError(); + if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA; + if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;} + else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);} + if(_wcsicmp(path,expected))return ERROR_INVALID_DATA; + FILETIME ended,kernel,user; + if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError(); + if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError(); + status=snapshot(peer->token,&peer->before);if(status)return status; + if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED; + if((status=peer_binding(peer,i)))return status; + } + return ERROR_SUCCESS; +} +static DWORD own_current(PrivilegeContext *ctx) { + HANDLE token=NULL;TokenSnapshot current={0}; + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError(); + DWORD status=snapshot(token,¤t);CloseHandle(token); + if(status)return status; + if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA; + return thread_absent(); +} +static void close_privilege(PrivilegeContext *ctx) { + for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);} + if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own); +} + +static char witness[262144]; +static size_t witness_used; +static int append(const char *format,...) { + va_list args;va_start(args,format); + int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args); + if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0; + witness_used+=(size_t)n;return 1; +} +static int append_snapshot(const TokenSnapshot *s) { + const TOKEN_STATISTICS *v=&s->statistics; + if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[", + (unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart, + (unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart, + (unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel, + (unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0; + for(DWORD i=0;icount;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0; + return append("]}"); +} +static DWORD write_before(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i]; + if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime) + || !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-before.json",witness,(DWORD)witness_used); +} +static DWORD write_adjustment(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":", + (unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error, + (unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes, + (unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error, + (unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status, + (unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart) + || !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-impersonate-v1\",\"case_id\":\"%s\"," + "\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false", + (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token={0};PrivilegeContext ctx={0}; + RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0}; + RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=3; + DWORD result=own_system_token(&token),rpc=0; + DWORD token_write=write_token(&token); /* durable old numeric probe */ + if(!result)result=token_write; + if(!result)result=prepare_privilege(&ctx); + if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */ + ctx.preflight_status=result; + if(!result) { + TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0; + enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege; + enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED; + restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */ + ctx.enable_attempted=1; /* all paths after this call execute the one restore */ + SetLastError(ERROR_SUCCESS); + ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes); + ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes; + if(previous.PrivilegeCount==1) { + ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart; + ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart; + ctx.previous_attributes=previous.Privileges[0].Attributes; + if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege) + && previous.Privileges[0].Attributes==0) { + restore=previous;ctx.restore_input_from_previous=1; + } + } + if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous) + result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA; + if(!result)result=snapshot(ctx.own,&ctx.active); + if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1); + if(!result)result=own_current(&ctx); + for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i); + ctx.active_status=result; + if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_impersonate(&trace,&eeinfo,&auth);} + /* No report IO or early return between adjustment and this restoration. */ + ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS); + ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL); + ctx.restore_error=GetLastError(); + ctx.restored_status=snapshot(ctx.own,&ctx.restored); + if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0); + if(!ctx.restored_status)ctx.restored_status=own_current(&ctx); + ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status; + if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i); + if(!status)status=snapshot(peer->token,&peer->after); + if(!status && (!identity_equal(&peer->before,&peer->after) + || !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId) + || peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA; + for(DWORD j=0;!status && jbefore.count;++j) + if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid) + || peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA; + if(status && !ctx.peer_after_status)ctx.peer_after_status=status; + } + if(ctx.peer_after_status && !result)result=ctx.peer_after_status; + } + ctx.flow_status=result; + DWORD adjustment_write=write_adjustment(&ctx); + if(!result)result=adjustment_write; + if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;} + DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token); + if(!result)result=result_write; + close_privilege(&ctx); + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-spnego-privilege-trace/build.py b/deploy/windows/clock-spnego-privilege-trace/build.py new file mode 100644 index 0000000..4bfc874 --- /dev/null +++ b/deploy/windows/clock-spnego-privilege-trace/build.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Local-only isolated process privilege comparison; never starts a target.""" +import base64 +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-privilege-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PARENT_MANIFEST = ROOT / 'devstate/windows-clock-spnego-empty-trace/build-9daffc05-64d1-45c2-954a-4ec642c5ef70/manifest.json' +PARENT_SHA = '768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548' +PARENT_RESULT = ROOT / 'devstate/windows-clock-spnego-empty-trace/5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94/diagnostic-result.json' +PARENT_RESULT_SHA = 'c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c': '9d9b5d247e9fc1570a72ced2f02373582c1aed7896e2f4bf8e7e85709a287dc5', + 'deploy/windows/clock-spnego-empty-trace/system_trace_spnego_empty.c': 'b8ce7b360e264e35781831e58a4a3278f7b35e44f07600e832d5d4ba82e8b986', + 'deploy/windows/clock-spnego-empty-trace/build.py': 'f72b50ad6977f491b32723ef9249569e6179e3072445392689a7a0bdf29c7f64', + 'deploy/windows/clock-spnego-empty-trace/native.py': '557cf3900ed16236376a26d24e863972e38d0ac7b34d3feb4329bc7d5bc7bc01', + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', + 'deploy/windows/clock-spnego-trace/clock_rpc_spnego.c': '10882bb39d7f27cc7e42123f2d2d4b2dbfb7a4cf86ed5bc80767c5fba1a33147', + 'deploy/windows/clock-spnego-trace/system_trace_spnego.c': '74f96e1e3d55799c3b599abf81ad5e66e436b9fcbd3b7125d87fe102d303812c', + 'deploy/windows/clock-spnego-trace/build.py': 'b10cdc0ba340d9b209e40a22391606f763aed01669e0356322f817eca6f08e0c', + 'deploy/windows/clock-spnego-trace/native.py': 'b85773f8c65d99aa59ec7318a2edca38d205ad3da394f645220f63ba1914bfd0', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(ROOT/'devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/manifest.json')=='f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001', 'original F6 manifest retained') + require(sha(ROOT/'devstate/windows-clock-spnego-trace/0f512772-3599-4c83-b877-41c74fe50fb0/diagnostic-result.json')=='4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9', 'original F6 result retained') + require(sha(PARENT_MANIFEST) == PARENT_SHA and sha(PARENT_RESULT) == PARENT_RESULT_SHA, 'original Empty and RPC5 case retained') + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego_privilege.c','system_trace_spnego_privilege.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego_privilege.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego_privilege.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego_privilege.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + parent_wrapper = ROOT / 'deploy/windows/clock-spnego-empty-trace/clock_rpc_spnego_empty.c' + parent_delta = ''.join(difflib.unified_diff(parent_wrapper.read_text().splitlines(True), wrapper.read_text().splitlines(True), + fromfile='unchanged-parent-spnego.c', tofile='new-spnego-privilege.c')) + write(folder / 'parent-wrapper-source.diff', parent_delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'), + own_system_token_only=True,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,returned_empty_principal_allowed=True,null_principal_allowed=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSpnegoPrivilegeTrace.linked.exe']) + raw_linked = output / 'ClockSpnegoPrivilegeTrace.linked.exe' + linked = output / 'ClockSpnegoPrivilegeTrace.original.exe'; delivery = output / 'ClockSpnegoPrivilegeTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSpnegoPrivilegeTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSpnegoPrivilegeTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + require(imports == json.loads(PARENT_MANIFEST.read_bytes())['artifact']['imports'], 'same DLL imports as exact Empty comparison') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-privilege-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=False,own_token_privilege_adjustment=True,peer_token_query_only=True,max_enables=1,max_restores=1,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + parent_manifest_sha256=PARENT_SHA,parent_result_sha256=PARENT_RESULT_SHA,parent_wrapper_diff_sha256=sha(folder / 'parent-wrapper-source.diff'),returned_empty_principal_allowed=True,null_principal_allowed=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c b/deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c new file mode 100644 index 0000000..fb1813b --- /dev/null +++ b/deploy/windows/clock-spnego-privilege-trace/clock_rpc_spnego_privilege.c @@ -0,0 +1,259 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + /* Preserve a returned non-NULL empty string; the SSP decides its meaning. */ + if (high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RPC_SECURITY_QOS qos = {0}; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IDENTIFY; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, &qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego_privilege(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-privilege-trace/native.py b/deploy/windows/clock-spnego-privilege-trace/native.py new file mode 100644 index 0000000..e8c425e --- /dev/null +++ b/deploy/windows/clock-spnego-privilege-trace/native.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-privilege-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-privilege-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSpnegoPrivilegeDiagnostic';$case=Join-Path $root ('clock-spnego-privilege-trace-'+$id);$exe=Join-Path $case 'ClockSpnegoPrivilegeTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSpnegoPrivilegeDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true;service_exit_code=$s.ExitCode} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$before=$null;$beforeFile=Join-Path $case 'privilege-before.json';if(Test-Path -LiteralPath $beforeFile){$before=Get-RmmTraceJson $beforeFile} +$adjust=$null;$adjustFile=Join-Path $case 'privilege-adjustment.json';if(Test-Path -LiteralPath $adjustFile){$adjust=Get-RmmTraceJson $adjustFile} +$cleaned=$false;$cleanedExit=$null;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true-or$null-eq$c.service_exit_code-or$c.service_exit_code-lt0-or$c.service_exit_code-gt4294967295){throw 'Bound cleanup receipt'};$cleaned=$true;$cleanedExit=$c.service_exit_code} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;cleaned_service_exit_code=$cleanedExit;report=$report;token_before_rpc=$token;privilege_before=$before;privilege_adjustment=$adjust;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true;own_privilege_adjustment=$true;foreign_token_query_only=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-privilege-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is False and value['own_token_privilege_adjustment'] is True and value['peer_token_query_only'] is True and value['max_enables']==value['max_restores']==1 and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'one own-token privilege adjustment/restore, peer QUERY only, no fallback/identity claim') + require(value['parent_manifest_sha256']=='768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548' + and value['parent_result_sha256']=='c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307' + and value['returned_empty_principal_allowed'] is True and value['null_principal_allowed'] is False + and sha(path.parent/'parent-wrapper-source.diff')==value['parent_wrapper_diff_sha256'], + 'exact Empty comparison, own process privilege only; no fabricated target or fallback') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_rpc_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True and value['own_privilege_adjustment'] is True and value['foreign_token_query_only'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-privilege-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is False and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==2 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 0<=auth['principal_units']<=512,'checked non-NULL bounded UTF16 principal, possibly empty') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 0<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True and value.get('cleaned_service_exit_code')==0) + + +def numeric(value): + return type(value) is int and 0<=value<2**32 + + +def validate_snapshot(value): + fields={'present','query_status','token_id','authentication_id','modified_id','expiration_time','token_type','impersonation_level','dynamic_charged','dynamic_available','group_count','privilege_count','privileges'} + require(isinstance(value,dict) and set(value)==fields,'exact numeric token snapshot') + for k in fields-{'token_id','authentication_id','modified_id','expiration_time','privileges'}: + require(numeric(value[k]),'numeric token statistic') + for k in ('token_id','authentication_id','modified_id','expiration_time'): + require(isinstance(value[k],list) and len(value[k])==2 and all(numeric(v) for v in value[k]),'numeric LUID/time pair') + require(value['present']==1 and value['query_status']==0 and value['token_type']==1,'queried primary token') + privileges=value['privileges'] + require(isinstance(privileges,list) and len(privileges)==value['privilege_count']<=256 + and all(isinstance(p,list) and len(p)==3 and all(numeric(n) for n in p) for p in privileges),'bounded complete privilege list') + keys=[(p[1],p[0]) for p in privileges] + require(keys==sorted(set(keys)),'sorted unique privilege LUIDs') + + +def same_identity(before,after): + return all(before[k]==after[k] for k in ('token_id','authentication_id','token_type')) + + +def check_privilege_evidence(value): + before=value.get('privilege_before');change=value.get('privilege_adjustment') + if before is None or change is None:return False + require(set(before)=={'schema_version','own_pid','own_creation','own','peers'} and before['schema_version']==1 + and numeric(before['own_pid']) and before['own_pid']>0 and isinstance(before['own_creation'],list) and len(before['own_creation'])==2 and all(numeric(v) for v in before['own_creation']),'bound pre-enable numeric witness') + validate_snapshot(before['own']) + require(isinstance(before['peers'],list) and len(before['peers'])==4,'four named peer witnesses') + for i,peer in enumerate(before['peers']): + require(set(peer)=={'role','pid','creation','token'} and peer['role']==i and numeric(peer['pid']) and peer['pid']>0 and peer['pid']!=before['own_pid'] + and isinstance(peer['creation'],list) and len(peer['creation'])==2 and all(numeric(v) for v in peer['creation']),'held peer PID/start binding') + validate_snapshot(peer['token']) + require(peer['token']['token_id']!=before['own']['token_id'],'different actual peer token object') + fields={'schema_version','preflight_status','enable_attempted','enable_return','enable_error','previous_count','previous_bytes','previous_luid','previous_attributes','active_status','rpc_attempted','restore_attempted','restore_return','restore_error','restore_input_from_previous','restored_status','peer_after_status','restoration_verified','flow_status','target_luid','active','restored','peers_after'} + require(set(change)==fields and all(numeric(change[k]) for k in fields-{'previous_luid','target_luid','active','restored','peers_after'}),'exact bounded adjustment witness') + for k in ('previous_luid','target_luid'): + require(isinstance(change[k],list) and len(change[k])==2 and all(numeric(n) for n in change[k]),'exact privilege LUID') + target=change['target_luid'] + expected=[p.copy() for p in before['own']['privileges']] + targets=[p for p in expected if p[:2]==target] + require(len(targets)==1 and targets[0][2]==0,'exact one present originally disabled privilege') + require(change['schema_version']==1 and change['preflight_status']==0 + and all(change[k] in (0,1) for k in ('enable_attempted','enable_return','rpc_attempted','restore_attempted','restore_return','restore_input_from_previous','restoration_verified')),'one bounded activation/restore flow') + # Failure reports remain available raw. Never call them preserved/complete. + if change['flow_status']!=0 or change['restoration_verified']!=1:return False + require(change['enable_attempted']==change['enable_return']==change['restore_attempted']==change['restore_return']==change['restore_input_from_previous']==1 + and change['enable_error']==change['restore_error']==change['active_status']==change['restored_status']==change['peer_after_status']==0 + and change['previous_count']==1 and change['previous_bytes']==16 and change['previous_luid']==target and change['previous_attributes']==0, + 'one successful exact enable and PreviousState restore, not TRUE/NOT_ALL_ASSIGNED') + validate_snapshot(change['active']);validate_snapshot(change['restored']) + targets[0][2]=2 + require(same_identity(before['own'],change['active']) and same_identity(before['own'],change['restored']) + and change['active']['privileges']==expected and change['restored']['privileges']==before['own']['privileges'], + 'same own token only target enable bit changes and exact original attributes restored') + require(isinstance(change['peers_after'],list) and len(change['peers_after'])==4,'four post-restore peer snapshots') + for peer,after in zip(before['peers'],change['peers_after']): + validate_snapshot(after) + require(same_identity(peer['token'],after) and peer['token']['modified_id']==after['modified_id'] + and peer['token']['privileges']==after['privileges'],'observed peer token and privilege state preserved') + require(change['rpc_attempted']==1 and value['report']['query_invocations']<=1,'at most one RPC function after verified enable') + return True + + +def check_report(value,ident): + rpc_complete=check_rpc_report(value,ident) + privilege_complete=check_privilege_evidence(value) + return rpc_complete and privilege_complete + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-privilege-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-privilege-trace-'+ident+'/ClockSpnegoPrivilegeTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c b/deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c new file mode 100644 index 0000000..a77ccc0 --- /dev/null +++ b/deploy/windows/clock-spnego-privilege-trace/system_trace_spnego_privilege.c @@ -0,0 +1,495 @@ +/* Isolated own-process privilege comparison. Original MIDL/Auth unchanged. + * One existing own privilege enabled and restored; peer tokens QUERY only. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego_privilege(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSpnegoPrivilegeDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-privilege-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +/* Only this held own token is ever passed to AdjustTokenPrivileges. Peer + * handles request TOKEN_QUERY only and are retained until the final readback. */ +typedef struct { + DWORD present, query_status; + TOKEN_STATISTICS statistics; + DWORD count; + LUID_AND_ATTRIBUTES privileges[256]; +} TokenSnapshot; +typedef struct { + HANDLE process, token; + SC_HANDLE service; + DWORD pid; + FILETIME creation; + TokenSnapshot before, after; +} Peer; +typedef struct { + HANDLE own; + SC_HANDLE manager; + FILETIME creation; + Peer peers[4]; /* SCM, W32Time, agent, helper */ + TokenSnapshot before, active, restored; + LUID privilege; + DWORD preflight_status, enable_attempted, enable_return, enable_error; + DWORD previous_count, previous_bytes, previous_luid_low, previous_luid_high, previous_attributes; + DWORD active_status, rpc_attempted, restore_attempted, restore_return, restore_error; + DWORD restore_input_from_previous, restored_status, peer_after_status, restoration_verified, flow_status; +} PrivilegeContext; + +static int luid_equal(LUID a, LUID b) {return a.LowPart==b.LowPart && a.HighPart==b.HighPart;} +static int luid_before(LUID a, LUID b) { + return (DWORD)a.HighPart<(DWORD)b.HighPart || (a.HighPart==b.HighPart && a.LowPartquery_status=ERROR_INVALID_DATA; + if (!GetTokenInformation(token,TokenStatistics,&out->statistics,sizeof(out->statistics),&needed)) status=GetLastError(); + else if (needed!=sizeof(out->statistics)) status=ERROR_INVALID_DATA; + if (!status) { + needed=0; + if (GetTokenInformation(token,TokenPrivileges,NULL,0,&needed) + || GetLastError()!=ERROR_INSUFFICIENT_BUFFER || neededsizeof(storage)) status=ERROR_INVALID_DATA; + else if (!GetTokenInformation(token,TokenPrivileges,storage,sizeof(storage),&needed)) status=GetLastError(); + else { + TOKEN_PRIVILEGES *value=(TOKEN_PRIVILEGES *)storage; + if (value->PrivilegeCount>256 || value->PrivilegeCount!=out->statistics.PrivilegeCount || needed>sizeof(storage) + || offsetof(TOKEN_PRIVILEGES,Privileges)+(size_t)value->PrivilegeCount*sizeof(LUID_AND_ATTRIBUTES)>needed) status=ERROR_INVALID_DATA; + else { + out->count=value->PrivilegeCount; + for (DWORD i=0;icount;++i) out->privileges[i]=value->Privileges[i]; + for (DWORD i=1;icount;++i) { + LUID_AND_ATTRIBUTES item=out->privileges[i];DWORD j=i; + while(j && luid_before(item.Luid,out->privileges[j-1].Luid)) {out->privileges[j]=out->privileges[j-1];--j;} + out->privileges[j]=item; + } + for(DWORD i=1;icount;++i) + if(luid_equal(out->privileges[i-1].Luid,out->privileges[i].Luid)) status=ERROR_INVALID_DATA; + } + } + } + out->query_status=status;out->present=!status;return status; +} +static int identity_equal(const TokenSnapshot *a,const TokenSnapshot *b) { + return a->present && b->present && luid_equal(a->statistics.TokenId,b->statistics.TokenId) + && luid_equal(a->statistics.AuthenticationId,b->statistics.AuthenticationId) + && a->statistics.TokenType==b->statistics.TokenType; +} +static DWORD compare_snapshots(const TokenSnapshot *a,const TokenSnapshot *b,LUID target,int enabled) { + if(!identity_equal(a,b) || a->count!=b->count) return ERROR_INVALID_DATA; + DWORD matched=0; + for(DWORD i=0;icount;++i) { + if(!luid_equal(a->privileges[i].Luid,b->privileges[i].Luid)) return ERROR_INVALID_DATA; + DWORD attributes=a->privileges[i].Attributes; + if(luid_equal(target,a->privileges[i].Luid)) {++matched;if(attributes) return ERROR_INVALID_DATA;if(enabled) attributes=SE_PRIVILEGE_ENABLED;} + if(b->privileges[i].Attributes!=attributes) return ERROR_INVALID_DATA; + } + return matched==1?ERROR_SUCCESS:ERROR_PRIVILEGE_NOT_HELD; +} +static DWORD query_service_pid(SC_HANDLE service,DWORD *pid) { + SERVICE_STATUS_PROCESS state={0};DWORD needed=0; + if(!QueryServiceStatusEx(service,SC_STATUS_PROCESS_INFO,(BYTE *)&state,sizeof(state),&needed)) return GetLastError(); + if(needed!=sizeof(state) || state.dwCurrentState!=SERVICE_RUNNING || !state.dwProcessId) return ERROR_INVALID_STATE; + *pid=state.dwProcessId;return ERROR_SUCCESS; +} +static DWORD scm_pid(DWORD *pid) { + HANDLE list=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + if(list==INVALID_HANDLE_VALUE) return GetLastError(); + PROCESSENTRY32W entry={0};entry.dwSize=sizeof(entry);DWORD found=0,status=0; + if(!Process32FirstW(list,&entry)) status=GetLastError(); + else { + do {if(!_wcsicmp(entry.szExeFile,L"services.exe")){*pid=entry.th32ProcessID;++found;}} + while(Process32NextW(list,&entry)); + if(GetLastError()!=ERROR_NO_MORE_FILES) status=GetLastError(); + else if(found!=1) status=ERROR_INVALID_DATA; + } + CloseHandle(list);return status; +} +static DWORD thread_absent(void) { + HANDLE token=NULL; + if(OpenThreadToken(GetCurrentThread(),TOKEN_QUERY,TRUE,&token)) {CloseHandle(token);return ERROR_ACCESS_DENIED;} + DWORD error=GetLastError();return error==ERROR_NO_TOKEN?ERROR_SUCCESS:error; +} +static DWORD peer_binding(Peer *peer,DWORD index) { + DWORD pid=0,status=index?query_service_pid(peer->service,&pid):scm_pid(&pid); + if(status) return status; + if(pid!=peer->pid || GetProcessId(peer->process)!=pid || WaitForSingleObject(peer->process,0)!=WAIT_TIMEOUT) return ERROR_INVALID_DATA; + FILETIME created,ended,kernel,user; + if(!GetProcessTimes(peer->process,&created,&ended,&kernel,&user)) return GetLastError(); + if(CompareFileTime(&created,&peer->creation)) return ERROR_INVALID_DATA; + HANDLE current=NULL;TokenSnapshot now={0}; + if(!OpenProcessToken(peer->process,TOKEN_QUERY,¤t)) return GetLastError(); + status=snapshot(current,&now);CloseHandle(current); + if(status) return status; + return identity_equal(&now,&peer->before)?ERROR_SUCCESS:ERROR_INVALID_DATA; +} +static DWORD prepare_privilege(PrivilegeContext *ctx) { + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&ctx->own)) return GetLastError(); + _Alignas(8) BYTE user_info[4096];DWORD needed=0;FILETIME ended,kernel,user; + if(!GetTokenInformation(ctx->own,TokenUser,user_info,sizeof(user_info),&needed))return GetLastError(); + if(neededsizeof(user_info) || !IsWellKnownSid(((TOKEN_USER *)user_info)->User.Sid,WinLocalSystemSid))return ERROR_ACCESS_DENIED; + if(!GetProcessTimes(GetCurrentProcess(),&ctx->creation,&ended,&kernel,&user))return GetLastError(); + DWORD status=snapshot(ctx->own,&ctx->before);if(status) return status; + if(ctx->before.statistics.TokenType!=TokenPrimary) return ERROR_ACCESS_DENIED; + if((status=thread_absent())) return status; + if(!LookupPrivilegeValueW(NULL,SE_SYSTEMTIME_NAME,&ctx->privilege)) return GetLastError(); + if((status=compare_snapshots(&ctx->before,&ctx->before,ctx->privilege,0))) return status; + ctx->manager=OpenSCManagerW(NULL,NULL,SC_MANAGER_CONNECT); + if(!ctx->manager) return GetLastError(); + const WCHAR *names[4]={NULL,L"W32Time",L"RmmDiscoveryWindows",L"RmmDiscoverySystemHelper"}; + const WCHAR *binaries[4]={L"services.exe",L"svchost.exe",L"C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe",L"C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe"}; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx->peers[i]; + if(i) {peer->service=OpenServiceW(ctx->manager,names[i],SERVICE_QUERY_STATUS);if(!peer->service)return GetLastError();} + status=i?query_service_pid(peer->service,&peer->pid):scm_pid(&peer->pid);if(status)return status; + if(peer->pid==GetCurrentProcessId()) return ERROR_INVALID_DATA; + peer->process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,peer->pid); + if(!peer->process)return GetLastError(); + WCHAR path[512],expected[512];DWORD length=512; + if(!QueryFullProcessImageNameW(peer->process,0,path,&length))return GetLastError(); + if(i<2) {UINT n=GetSystemDirectoryW(expected,512);if(!n || n>480)return ERROR_INVALID_DATA; + if(swprintf(expected+n,512-n,L"\\%ls",binaries[i])<=0)return ERROR_INVALID_DATA;} + else {if(wcslen(binaries[i])>=512)return ERROR_INVALID_DATA;wcscpy(expected,binaries[i]);} + if(_wcsicmp(path,expected))return ERROR_INVALID_DATA; + FILETIME ended,kernel,user; + if(!GetProcessTimes(peer->process,&peer->creation,&ended,&kernel,&user))return GetLastError(); + if(!OpenProcessToken(peer->process,TOKEN_QUERY,&peer->token))return GetLastError(); + status=snapshot(peer->token,&peer->before);if(status)return status; + if(peer->before.statistics.TokenType!=TokenPrimary || luid_equal(peer->before.statistics.TokenId,ctx->before.statistics.TokenId))return ERROR_ACCESS_DENIED; + if((status=peer_binding(peer,i)))return status; + } + return ERROR_SUCCESS; +} +static DWORD own_current(PrivilegeContext *ctx) { + HANDLE token=NULL;TokenSnapshot current={0}; + if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&token))return GetLastError(); + DWORD status=snapshot(token,¤t);CloseHandle(token); + if(status)return status; + if(!identity_equal(&ctx->before,¤t))return ERROR_INVALID_DATA; + return thread_absent(); +} +static void close_privilege(PrivilegeContext *ctx) { + for(DWORD i=0;i<4;++i){Peer *p=&ctx->peers[i];if(p->token)CloseHandle(p->token);if(p->process)CloseHandle(p->process);if(p->service)CloseServiceHandle(p->service);} + if(ctx->manager)CloseServiceHandle(ctx->manager);if(ctx->own)CloseHandle(ctx->own); +} + +static char witness[262144]; +static size_t witness_used; +static int append(const char *format,...) { + va_list args;va_start(args,format); + int n=vsnprintf(witness+witness_used,sizeof(witness)-witness_used,format,args);va_end(args); + if(n<=0 || (size_t)n>=sizeof(witness)-witness_used)return 0; + witness_used+=(size_t)n;return 1; +} +static int append_snapshot(const TokenSnapshot *s) { + const TOKEN_STATISTICS *v=&s->statistics; + if(!append("{\"present\":%lu,\"query_status\":%lu,\"token_id\":[%lu,%lu],\"authentication_id\":[%lu,%lu],\"modified_id\":[%lu,%lu],\"expiration_time\":[%lu,%lu],\"token_type\":%lu,\"impersonation_level\":%lu,\"dynamic_charged\":%lu,\"dynamic_available\":%lu,\"group_count\":%lu,\"privilege_count\":%lu,\"privileges\":[", + (unsigned long)s->present,(unsigned long)s->query_status,(unsigned long)v->TokenId.LowPart,(unsigned long)(DWORD)v->TokenId.HighPart, + (unsigned long)v->AuthenticationId.LowPart,(unsigned long)(DWORD)v->AuthenticationId.HighPart,(unsigned long)v->ModifiedId.LowPart,(unsigned long)(DWORD)v->ModifiedId.HighPart, + (unsigned long)v->ExpirationTime.LowPart,(unsigned long)(DWORD)v->ExpirationTime.HighPart,(unsigned long)v->TokenType,(unsigned long)v->ImpersonationLevel, + (unsigned long)v->DynamicCharged,(unsigned long)v->DynamicAvailable,(unsigned long)v->GroupCount,(unsigned long)s->count))return 0; + for(DWORD i=0;icount;++i)if(!append("%s[%lu,%lu,%lu]",i?",":"",(unsigned long)s->privileges[i].Luid.LowPart,(unsigned long)(DWORD)s->privileges[i].Luid.HighPart,(unsigned long)s->privileges[i].Attributes))return 0; + return append("]}"); +} +static DWORD write_before(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"own_pid\":%lu,\"own_creation\":[%lu,%lu],\"own\":",(unsigned long)GetCurrentProcessId(),(unsigned long)ctx->creation.dwLowDateTime,(unsigned long)ctx->creation.dwHighDateTime) || !append_snapshot(&ctx->before) || !append(",\"peers\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){const Peer *p=&ctx->peers[i]; + if(!append("%s{\"role\":%lu,\"pid\":%lu,\"creation\":[%lu,%lu],\"token\":",i?",":"",(unsigned long)i,(unsigned long)p->pid,(unsigned long)p->creation.dwLowDateTime,(unsigned long)p->creation.dwHighDateTime) + || !append_snapshot(&p->before) || !append("}"))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-before.json",witness,(DWORD)witness_used); +} +static DWORD write_adjustment(const PrivilegeContext *ctx) { + witness_used=0; + if(!append("{\"schema_version\":1,\"preflight_status\":%lu,\"enable_attempted\":%lu,\"enable_return\":%lu,\"enable_error\":%lu,\"previous_count\":%lu,\"previous_bytes\":%lu,\"previous_luid\":[%lu,%lu],\"previous_attributes\":%lu,\"active_status\":%lu,\"rpc_attempted\":%lu,\"restore_attempted\":%lu,\"restore_return\":%lu,\"restore_error\":%lu,\"restore_input_from_previous\":%lu,\"restored_status\":%lu,\"peer_after_status\":%lu,\"restoration_verified\":%lu,\"flow_status\":%lu,\"target_luid\":[%lu,%lu],\"active\":", + (unsigned long)ctx->preflight_status,(unsigned long)ctx->enable_attempted,(unsigned long)ctx->enable_return,(unsigned long)ctx->enable_error, + (unsigned long)ctx->previous_count,(unsigned long)ctx->previous_bytes,(unsigned long)ctx->previous_luid_low,(unsigned long)ctx->previous_luid_high,(unsigned long)ctx->previous_attributes, + (unsigned long)ctx->active_status,(unsigned long)ctx->rpc_attempted,(unsigned long)ctx->restore_attempted,(unsigned long)ctx->restore_return,(unsigned long)ctx->restore_error, + (unsigned long)ctx->restore_input_from_previous,(unsigned long)ctx->restored_status,(unsigned long)ctx->peer_after_status,(unsigned long)ctx->restoration_verified,(unsigned long)ctx->flow_status, + (unsigned long)ctx->privilege.LowPart,(unsigned long)(DWORD)ctx->privilege.HighPart) + || !append_snapshot(&ctx->active) || !append(",\"restored\":") || !append_snapshot(&ctx->restored) || !append(",\"peers_after\":["))return ERROR_BUFFER_OVERFLOW; + for(DWORD i=0;i<4;++i){if(i && !append(","))return ERROR_BUFFER_OVERFLOW;if(!append_snapshot(&ctx->peers[i].after))return ERROR_BUFFER_OVERFLOW;} + if(!append("]}\n"))return ERROR_BUFFER_OVERFLOW; + return write_new(L"privilege-adjustment.json",witness,(DWORD)witness_used); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-privilege-v1\",\"case_id\":\"%s\"," + "\"token_system\":%s,\"read_only\":false,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (token->query_status==0 && token->system_user==1 && token->token_type==1 && token->thread_present==0 && token->thread_query_status==ERROR_NO_TOKEN)?"true":"false", + (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token={0};PrivilegeContext ctx={0}; + RmmClockTrace trace={0};RmmClockEeInfo eeinfo={0}; + RmmClockAuthTrace auth={0};auth.authn_service=9;auth.authn_level=6;auth.impersonation_type=2; + DWORD result=own_system_token(&token),rpc=0; + DWORD token_write=write_token(&token); /* durable old numeric probe */ + if(!result)result=token_write; + if(!result)result=prepare_privilege(&ctx); + if(!result)result=write_before(&ctx); /* durable complete pre-enable witness */ + ctx.preflight_status=result; + if(!result) { + TOKEN_PRIVILEGES enable={0},previous={0},restore={0};DWORD previous_bytes=0; + enable.PrivilegeCount=1;enable.Privileges[0].Luid=ctx.privilege; + enable.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED; + restore.PrivilegeCount=1;restore.Privileges[0].Luid=ctx.privilege; /* saved original Attr0 */ + ctx.enable_attempted=1; /* all paths after this call execute the one restore */ + SetLastError(ERROR_SUCCESS); + ctx.enable_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&enable,sizeof(previous),&previous,&previous_bytes); + ctx.enable_error=GetLastError();ctx.previous_count=previous.PrivilegeCount;ctx.previous_bytes=previous_bytes; + if(previous.PrivilegeCount==1) { + ctx.previous_luid_low=previous.Privileges[0].Luid.LowPart; + ctx.previous_luid_high=(DWORD)previous.Privileges[0].Luid.HighPart; + ctx.previous_attributes=previous.Privileges[0].Attributes; + if(previous_bytes==sizeof(previous) && luid_equal(previous.Privileges[0].Luid,ctx.privilege) + && previous.Privileges[0].Attributes==0) { + restore=previous;ctx.restore_input_from_previous=1; + } + } + if(!ctx.enable_return || ctx.enable_error || !ctx.restore_input_from_previous) + result=ctx.enable_error?ctx.enable_error:ERROR_INVALID_DATA; + if(!result)result=snapshot(ctx.own,&ctx.active); + if(!result)result=compare_snapshots(&ctx.before,&ctx.active,ctx.privilege,1); + if(!result)result=own_current(&ctx); + for(DWORD i=0;!result && i<4;++i)result=peer_binding(&ctx.peers[i],i); + ctx.active_status=result; + if(!result) {ctx.rpc_attempted=1;rpc=rmm_clock_query_trace_spnego_privilege(&trace,&eeinfo,&auth);} + /* No report IO or early return between adjustment and this restoration. */ + ctx.restore_attempted=1;SetLastError(ERROR_SUCCESS); + ctx.restore_return=!!AdjustTokenPrivileges(ctx.own,FALSE,&restore,0,NULL,NULL); + ctx.restore_error=GetLastError(); + ctx.restored_status=snapshot(ctx.own,&ctx.restored); + if(!ctx.restored_status)ctx.restored_status=compare_snapshots(&ctx.before,&ctx.restored,ctx.privilege,0); + if(!ctx.restored_status)ctx.restored_status=own_current(&ctx); + ctx.restoration_verified=ctx.restore_return && !ctx.restore_error && !ctx.restored_status; + if(!ctx.restoration_verified && !result)result=ctx.restore_error?ctx.restore_error:ERROR_INVALID_DATA; + for(DWORD i=0;i<4;++i) { + Peer *peer=&ctx.peers[i];DWORD status=peer_binding(peer,i); + if(!status)status=snapshot(peer->token,&peer->after); + if(!status && (!identity_equal(&peer->before,&peer->after) + || !luid_equal(peer->before.statistics.ModifiedId,peer->after.statistics.ModifiedId) + || peer->before.count!=peer->after.count))status=ERROR_INVALID_DATA; + for(DWORD j=0;!status && jbefore.count;++j) + if(!luid_equal(peer->before.privileges[j].Luid,peer->after.privileges[j].Luid) + || peer->before.privileges[j].Attributes!=peer->after.privileges[j].Attributes)status=ERROR_INVALID_DATA; + if(status && !ctx.peer_after_status)ctx.peer_after_status=status; + } + if(ctx.peer_after_status && !result)result=ctx.peer_after_status; + } + ctx.flow_status=result; + DWORD adjustment_write=write_adjustment(&ctx); + if(!result)result=adjustment_write; + if(!ctx.rpc_attempted){rpc=ctx.flow_status;trace.stage=200;} + DWORD result_write=write_result(rpc,&trace,&eeinfo,&auth,&token); + if(!result)result=result_write; + close_privilege(&ctx); + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-spnego-trace/build.py b/deploy/windows/clock-spnego-trace/build.py new file mode 100644 index 0000000..cea2709 --- /dev/null +++ b/deploy/windows/clock-spnego-trace/build.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Local-only bounded SYSTEM SPNEGO diagnostic; no VM or product source edits.""" +import base64 +import difflib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +UNCHANGED_DIAGNOSTICS = { + 'deploy/windows/clock-system-trace/system_trace.c': '5be92130fda4dbb2a0078861f2b4ebd70bc3b7ecc3a65af0b426702cb69b772a', + 'deploy/windows/clock-system-trace/build.py': 'e66ef17ba8a442f594114e3fa8eec62c256f0a9b1d9ca0d4e5c821675e00f05f', + 'deploy/windows/clock-system-trace/native.py': 'fd46fc5167ac85808a4483f76e774e5e05e0d79f4a01def611a0c0b91414714e', + 'deploy/windows/clock-eeinfo-trace/clock_rpc_eeinfo.c': '2bf009c3118af34ae7945c7d67b4647f0b24a9db34fbeeb4b44299e69f7e9a68', + 'deploy/windows/clock-eeinfo-trace/system_trace_eeinfo.c': '09628d345592c767ebe136e40108e283e96bc37f749c5db93e62e327cb890301', + 'deploy/windows/clock-eeinfo-trace/build.py': '59a0c3f881b824d921d165ace4da1e5992b85ddbf9d1d5132404b588dd50f36c', + 'deploy/windows/clock-eeinfo-trace/native.py': 'cc71c230d4e6e30831eefd20de3d80848732e74d0ce077d79db29c3a1db33e8f', +} + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + require(all(sha(ROOT/name)==digest for name,digest in UNCHANGED_DIAGNOSTICS.items()),'existing SYSTEM/WINNT/EEInfo diagnostic sources unchanged') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('clock_rpc_spnego.c','system_trace_spnego.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + baseline_wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + require(sha(baseline_wrapper) == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8','same original C/Auth wrapper') + wrapper = HERE / 'clock_rpc_spnego.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace_spnego.c').read_bytes()) + delta = ''.join(difflib.unified_diff(baseline_wrapper.read_text().splitlines(True),wrapper.read_text().splitlines(True),fromfile='original-clock_rpc.c',tofile='diagnostic-clock_rpc_spnego.c')) + write(folder / 'wrapper-source.diff',delta.encode()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), original_wrapper_sha256=sha(baseline_wrapper), wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'), unchanged_diagnostics=UNCHANGED_DIAGNOSTICS, + own_system_token_only=True,token_query_only=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False,no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemSpnegoTrace.linked.exe']) + raw_linked = output / 'ClockSystemSpnegoTrace.linked.exe' + linked = output / 'ClockSystemSpnegoTrace.original.exe'; delivery = output / 'ClockSystemSpnegoTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSystemSpnegoTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemSpnegoTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-spnego-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),original_wrapper_sha256=sha(baseline_wrapper),wrapper_diff_sha256=sha(folder / 'wrapper-source.diff'),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,unchanged_diagnostics=UNCHANGED_DIAGNOSTICS,token_query_only=True,max_principal_discoveries=1,max_status_queries=1,principal_identity_proven=False, + checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-trace/clock_rpc_spnego.c b/deploy/windows/clock-spnego-trace/clock_rpc_spnego.c new file mode 100644 index 0000000..25abe1c --- /dev/null +++ b/deploy/windows/clock-spnego-trace/clock_rpc_spnego.c @@ -0,0 +1,258 @@ +/* Isolated diagnostic variant: discover SPNEGO principal on the fixed local + * authenticated endpoint, then at most one MS-W32T Opnum6. No fallback/trust. + * Actual Microsoft-generated MIDL is reused. SEH stays entirely inside C. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include +#include "w32time.h" +/* Documented public SDK API; older MinGW headers omit its declaration. */ +int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code); +typedef struct Allocation { struct Allocation *next; size_t size; } Allocation; +typedef struct { Allocation *head; size_t total; } Arena; +/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS + * in the mixed Rust/MinGW PE did not initialize such a thread's storage. */ +static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT; +static DWORD arena_index = TLS_OUT_OF_INDEXES; +static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; (void)parameter; (void)context; + arena_index = TlsAlloc(); + return arena_index != TLS_OUT_OF_INDEXES; +} +void *__RPC_USER MIDL_user_allocate(size_t size) { + Arena *arena = TlsGetValue(arena_index); + if (!arena || size > 65536 || arena->total > 65536 - size) return NULL; + Allocation *p = calloc(1, sizeof(*p) + size); + if (!p) return NULL; + p->size = size; p->next = arena->head; arena->head = p; arena->total += size; + return p + 1; +} +void __RPC_USER MIDL_user_free(void *memory) { + Arena *arena = TlsGetValue(arena_index); + if (!memory || !arena) return; + Allocation **link = &arena->head; + while (*link && (*link + 1) != memory) link = &(*link)->next; + if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); } +} +static void release_allocations(Arena *arena) { + while (arena->head) MIDL_user_free(arena->head + 1); +} +/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */ +typedef struct { + uint32_t leap, stratum, state, flags, last_result, size; + uint64_t last_sync, sync_age; + int64_t root_delay; + uint64_t root_dispersion; + int64_t phase; +} RmmClockStatus; +_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); +_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); + +/* Diagnostic source variant only. No strings/parameters leave this function. */ +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeRecord) == 20, "numeric EEInfo record ABI"); +_Static_assert(sizeof(RmmClockEeInfo) == 104, "bounded four-record EEInfo ABI"); +static void capture_eeinfo(RmmClockEeInfo *out) { + RPC_ERROR_ENUM_HANDLE enumeration = {0}; + out->capture_attempted = 1; + out->start_status = RpcErrorStartEnumeration(&enumeration); + if (out->start_status != RPC_S_OK) return; + for (unsigned i = 0; i < 4; ++i) { + RPC_EXTENDED_ERROR_INFO info = {0}; + info.Version = RPC_EEINFO_VERSION; + info.Flags = 0; + info.NumberOfParameters = MaxNumberOfEEInfoParams; + out->next_status = RpcErrorGetNextRecord(&enumeration, FALSE, &info); + if (out->next_status != RPC_S_OK) break; + RmmClockEeRecord *record = &out->records[out->count++]; + record->generating_component = info.GeneratingComponent; + record->status = info.Status; + record->detection_location = info.DetectionLocation; + record->flags = info.Flags; + record->number_of_parameters = info.NumberOfParameters; + /* ComputerName and Parameters are neither copied nor dereferenced. + * CopyStrings=FALSE: RPC owns all borrowed fields until EndEnumeration. */ + } + out->limit_reached = out->count == 4; + out->end_status = RpcErrorEndEnumeration(&enumeration); +} + +/* Numeric protocol-path observations, never a server-identity assertion. */ +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "numeric SPNEGO path ABI"); + +static uint32_t check_principal(RPC_WSTR value, RmmClockAuthTrace *auth) { + if (!value) return ERROR_INVALID_DATA; + auth->principal_present = 1; + int high = 0; + for (unsigned i = 0; i <= 512; ++i) { + unsigned unit = value[i]; + if (!unit) { + auth->principal_units = i; + if (!i || high) return ERROR_INVALID_NAME; + auth->principal_validated = 1; + return ERROR_SUCCESS; + } + if (i == 512 || unit < 0x20 || (unit >= 0x7f && unit <= 0x9f)) return ERROR_INVALID_NAME; + if (high) { + if (unit < 0xdc00 || unit > 0xdfff) return ERROR_INVALID_NAME; + high = 0; + } else if (unit >= 0xd800 && unit <= 0xdbff) high = 1; + else if (unit >= 0xdc00 && unit <= 0xdfff) return ERROR_INVALID_NAME; + } + return ERROR_INVALID_NAME; +} + +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RMM_W32TIME_STATUS *status = NULL; + unsigned long result = 0; + Arena arena = {0}; + if (trace) trace->stage = 50; + if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; + if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; + if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); + if (!result) { + RpcTryExcept { + if (trace) trace->stage = 60; + auth->status_query_invocations = 1; + result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } + if (!result) { + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; + result = RPC_X_BAD_STUB_DATA; + } + else { + if (trace) trace->stage = 80; + out->leap = status->eLeapIndicator; out->stratum = status->nStratum; + out->state = status->ulLcState; out->flags = status->ulTSFlags; + out->last_result = status->eLastSyncResult; out->size = status->ulSize; + out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync; + out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion; + out->phase = status->toSysPhaseOffset; + } + } + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + if (eeinfo) capture_eeinfo(eeinfo); /* before any further RPC call */ + if (trace) {trace->stage = 90; trace->rpc_exception = result;} + } RpcEndExcept + release_allocations(&arena); + TlsSetValue(arena_index, NULL); + } + return result; +} +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RPC_WSTR text = NULL; + RPC_BINDING_HANDLE binding = NULL; + RPC_WSTR principal = NULL; + RPC_SECURITY_QOS qos = {0}; + unsigned long result; + memset(out, 0, sizeof(*out)); + memset(auth, 0, sizeof(*auth)); + auth->authn_service = RPC_C_AUTHN_GSS_NEGOTIATE; + auth->authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; + auth->impersonation_type = RPC_C_IMP_LEVEL_IDENTIFY; + if (trace) trace->stage = 10; + result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, + (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); + if (result) return result; + if (trace) trace->stage = 20; + result = RpcBindingFromStringBindingW(text, &binding); + RpcStringFreeW(&text); + if (result) return result; + /* Bound the management discovery as well as Opnum6. RpcMgmt allocates its + * returned string internally: the 512-unit check bounds inspection/use, + * not RPC runtime allocations made before the API returns. */ + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + if (!result) { + if (trace) trace->stage = 25; + RpcTryExcept { + auth->discovery_invocations = 1; + result = RpcMgmtInqServerPrincNameW(binding, RPC_C_AUTHN_GSS_NEGOTIATE, &principal); + auth->discovery_return_present = 1; + auth->discovery_status = result; + if (result && eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { + result = RpcExceptionCode(); + auth->discovery_status = result; + if (eeinfo) {auth->eeinfo_origin = 1; capture_eeinfo(eeinfo);} + if (trace) {trace->stage = 91; trace->rpc_exception = result;} + } RpcEndExcept + } + if (!result) { + if (trace) trace->stage = 26; + result = check_principal(principal, auth); + } + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + if (!result) { + if (trace) trace->stage = 30; + /* The returned principal is ONLY a diagnostic authentication input, + * never an independently trusted service/account/SID assertion. */ + result = RpcBindingSetAuthInfoExW(binding, principal, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, + RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE, &qos); + if (result && eeinfo) {auth->eeinfo_origin = 3; capture_eeinfo(eeinfo);} + } + if (!result) { + result = invoke_status(binding, out, trace, eeinfo, auth); + if (eeinfo && eeinfo->capture_attempted) auth->eeinfo_origin = 2; + } + /* Preserve the original discovery/auth/query result before cleanup RPC. */ + if (principal) { + auth->principal_free_attempted = 1; + auth->principal_free_status = RpcStringFreeW(&principal); + } + auth->binding_free_attempted = 1; + auth->binding_free_status = RpcBindingFree(&binding); + return result; +} +/* At most one authenticated status query after exactly one discovery. */ +uint32_t rmm_clock_query_trace_spnego(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + memset(eeinfo, 0, sizeof(*eeinfo)); + return pipe_query(&ignored, trace, eeinfo, auth); +} diff --git a/deploy/windows/clock-spnego-trace/native.py b/deploy/windows/clock-spnego-trace/native.py new file mode 100644 index 0000000..7d564a6 --- /dev/null +++ b/deploy/windows/clock-spnego-trace/native.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-spnego-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-spnego-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSystemSpnegoDiagnostic';$case=Join-Path $root ('clock-spnego-trace-'+$id);$exe=Join-Path $case 'ClockSystemSpnegoTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemSpnegoDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$token=$null;$tokenFile=Join-Path $case 'token.json';if(Test-Path -LiteralPath $tokenFile){$token=Get-RmmTraceJson $tokenFile} +$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;token_before_rpc=$token;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-spnego-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + require(value['original_wrapper_sha256'] == '74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8' + and sha(path.parent / 'wrapper-source.diff') == value['wrapper_diff_sha256'],'same exact observational source delta') + require(value['token_query_only'] is True and value['max_principal_discoveries']==value['max_status_queries']==1 + and value['principal_identity_proven'] is False,'no privilege mutation/fallback or principal-as-identity claim') + for name,digest in value['unchanged_diagnostics'].items():require(sha(ROOT/name)==digest,'original SYSTEM/WINNT/EEInfo inputs retained') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-spnego-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True + and type(report['query_invocations']) is int and report['query_invocations'] in (0,1) and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + token=report['token'] + require(set(token)=={'query_status','system_user','token_type','thread_query_status','thread_present','lookup_status','privileges_status','privilege_present','privilege_attributes','privilege_enabled','privilege_default','privilege_removed'} + and all(type(v) is int and 0<=v<2**32 for v in token.values()) + and token==value['token_before_rpc'] and token['query_status']==token['lookup_status']==token['privileges_status']==0 + and token['system_user']==1 and token['token_type']==1 and token['thread_present']==0 and token['thread_query_status']==1008, + 'durable own SYSTEM primary token/privileges observed before RPC without impersonation') + require(all(token[k] in (0,1) for k in ('privilege_present','privilege_enabled','privilege_default','privilege_removed')) + and token['privilege_enabled']==int(bool(token['privilege_attributes']&2)) + and token['privilege_default']==int(bool(token['privilege_attributes']&1)) + and token['privilege_removed']==int(bool(token['privilege_attributes']&4)) + and (token['privilege_present'] or token['privilege_attributes']==0),'present/enabled privilege attributes remain observations only') + auth=report['auth'] + require(set(auth)=={'discovery_invocations','discovery_status','discovery_return_present','principal_present','principal_units','principal_validated','status_query_invocations','authn_service','authn_level','impersonation_type','principal_free_attempted','principal_free_status','binding_free_attempted','binding_free_status','eeinfo_origin'} + and all(type(v) is int and 0<=v<2**32 for v in auth.values()) + and auth['authn_service']==9 and auth['authn_level']==6 and auth['impersonation_type']==2 + and all(auth[k] in (0,1) for k in ('discovery_invocations','discovery_return_present','principal_present','principal_validated','status_query_invocations','principal_free_attempted','binding_free_attempted')) + and auth['status_query_invocations']==report['query_invocations'] and auth['eeinfo_origin'] in (0,1,2,3) + and auth['discovery_return_present']<=auth['discovery_invocations'] + and auth['principal_units']<=512,'bounded one-discovery/at-most-one-status SPNEGO Privacy Identify path') + if auth['principal_validated']: + require(auth['principal_present']==1 and 1<=auth['principal_units']<=512,'checked nonempty bounded principal') + if auth['principal_present']: + require(auth['principal_free_attempted']==1,'owned principal cleanup attempted') + if auth['status_query_invocations']: + require(auth['discovery_invocations']==auth['discovery_return_present']==auth['principal_present']==auth['principal_validated']==1 + and auth['discovery_status']==0 and 1<=auth['principal_units']<=512,'no status query without successful checked principal discovery') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + ee=report['eeinfo'] + require(set(ee) == {'capture_attempted','start_status','next_status','end_status','count','limit_reached','records'} + and all(type(ee[k]) is int and 0 <= ee[k] < 2**32 for k in ('capture_attempted','start_status','next_status','end_status','count','limit_reached')) + and ee['capture_attempted'] in (0,1) and 0 <= ee['count'] <= 4 and len(ee['records']) == ee['count'] + and ee['limit_reached'] == int(ee['count'] == 4),'four-record numeric EEInfo budget') + require(ee['capture_attempted']==int(auth['eeinfo_origin']!=0),'numeric EEInfo origin matches capture') + record_fields={'generating_component','status','detection_location','flags','number_of_parameters'} + for record in ee['records']: + require(set(record) == record_fields and all(type(n) is int and 0 <= n < 2**32 for n in record.values()) + and record['number_of_parameters'] <= 4,'numeric EEInfo fields only; no parameter contents') + if report['trace']['stage'] in (90,91): + require(ee['capture_attempted']==1 and report['rpc_code']==report['trace']['rpc_exception'] + and auth['eeinfo_origin']==(2 if report['trace']['stage']==90 else 1),'original exception code preserved before immediate capture') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True) + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-spnego-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-spnego-trace-'+ident+'/ClockSystemSpnegoTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,eeinfo_count=result['report']['eeinfo']['count'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-spnego-trace/system_trace_spnego.c b/deploy/windows/clock-spnego-trace/system_trace_spnego.c new file mode 100644 index 0000000..60aba33 --- /dev/null +++ b/deploy/windows/clock-spnego-trace/system_trace_spnego.c @@ -0,0 +1,233 @@ +/* Isolated SPNEGO diagnostic. Original MIDL remains unchanged. Read the own + * SYSTEM token first; one management discovery, then at most one status query. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#define UNICODE 1 +#include +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +typedef struct { + uint32_t generating_component, status, detection_location, flags; + int32_t number_of_parameters; +} RmmClockEeRecord; +typedef struct { + uint32_t capture_attempted, start_status, next_status, end_status, count, limit_reached; + RmmClockEeRecord records[4]; +} RmmClockEeInfo; +_Static_assert(sizeof(RmmClockEeInfo) == 104, "same four-record numeric EEInfo ABI"); +typedef struct { + uint32_t discovery_invocations, discovery_status, discovery_return_present; + uint32_t principal_present, principal_units, principal_validated; + uint32_t status_query_invocations, authn_service, authn_level, impersonation_type; + uint32_t principal_free_attempted, principal_free_status; + uint32_t binding_free_attempted, binding_free_status, eeinfo_origin; +} RmmClockAuthTrace; +_Static_assert(sizeof(RmmClockAuthTrace) == 60, "same numeric auth trace ABI"); +typedef struct { + uint32_t query_status, system_user, token_type, thread_query_status, thread_present; + uint32_t lookup_status, privileges_status, privilege_present, privilege_attributes; + uint32_t privilege_enabled, privilege_default, privilege_removed; +} RmmTokenProbe; +uint32_t rmm_clock_query_trace_spnego(RmmClockTrace *trace, RmmClockEeInfo *eeinfo, RmmClockAuthTrace *auth); + +static WCHAR service_name[] = L"RmmClockSystemSpnegoDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(RmmTokenProbe *probe) { + HANDLE token = NULL; + HANDLE thread = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + probe->query_status = GetLastError(); + return probe->query_status; + } + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed < sizeof(TOKEN_USER) || needed > sizeof(storage) + || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + else probe->system_user = 1; + if (!result) { + TOKEN_TYPE type = 0; + if (!GetTokenInformation(token, TokenType, &type, sizeof(type), &needed)) result = GetLastError(); + else { + probe->token_type = (uint32_t)type; + if (needed != sizeof(type) || type != TokenPrimary) result = ERROR_ACCESS_DENIED; + } + } + if (!result) { + if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread)) { + probe->thread_present = 1; + CloseHandle(thread); + result = ERROR_ACCESS_DENIED; /* never impersonate/revert to continue */ + } else { + probe->thread_query_status = GetLastError(); + if (probe->thread_query_status != ERROR_NO_TOKEN) result = probe->thread_query_status; + } + } + if (!result) { + LUID target = {0}; + if (!LookupPrivilegeValueW(NULL, SE_SYSTEMTIME_NAME, &target)) { + probe->lookup_status = GetLastError();result = probe->lookup_status; + } else { + needed = 0; + if (GetTokenInformation(token, TokenPrivileges, NULL, 0, &needed) + || GetLastError() != ERROR_INSUFFICIENT_BUFFER || needed < sizeof(DWORD) || needed > sizeof(storage)) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else if (!GetTokenInformation(token, TokenPrivileges, storage, sizeof(storage), &needed)) { + probe->privileges_status = GetLastError();result = probe->privileges_status; + } else { + TOKEN_PRIVILEGES *privileges = (TOKEN_PRIVILEGES *)storage; + size_t count = privileges->PrivilegeCount; + if (count > 256 || needed > sizeof(storage) + || offsetof(TOKEN_PRIVILEGES, Privileges) + count * sizeof(LUID_AND_ATTRIBUTES) > needed) { + probe->privileges_status = ERROR_INVALID_DATA;result = ERROR_INVALID_DATA; + } else for (size_t i = 0; i < count; ++i) { + const LUID_AND_ATTRIBUTES *p = &privileges->Privileges[i]; + if (p->Luid.LowPart != target.LowPart || p->Luid.HighPart != target.HighPart) continue; + if (probe->privilege_present) {result = ERROR_INVALID_DATA;break;} + probe->privilege_present = 1; + probe->privilege_attributes = p->Attributes; + probe->privilege_enabled = !!(p->Attributes & SE_PRIVILEGE_ENABLED); + probe->privilege_default = !!(p->Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT); + probe->privilege_removed = !!(p->Attributes & SE_PRIVILEGE_REMOVED); + } + } + } + } + probe->query_status = result; + CloseHandle(token); + return result; +} + +#define TOKEN_FIELDS "\"query_status\":%lu,\"system_user\":%lu,\"token_type\":%lu,\"thread_query_status\":%lu,\"thread_present\":%lu,\"lookup_status\":%lu,\"privileges_status\":%lu,\"privilege_present\":%lu,\"privilege_attributes\":%lu,\"privilege_enabled\":%lu,\"privilege_default\":%lu,\"privilege_removed\":%lu" +#define TOKEN_VALUES(p) (unsigned long)(p)->query_status,(unsigned long)(p)->system_user,(unsigned long)(p)->token_type,(unsigned long)(p)->thread_query_status,(unsigned long)(p)->thread_present,(unsigned long)(p)->lookup_status,(unsigned long)(p)->privileges_status,(unsigned long)(p)->privilege_present,(unsigned long)(p)->privilege_attributes,(unsigned long)(p)->privilege_enabled,(unsigned long)(p)->privilege_default,(unsigned long)(p)->privilege_removed +static DWORD write_new(const WCHAR *suffix, const char *bytes, DWORD length) { + WCHAR path[256];DWORD written = 0, result = ERROR_SUCCESS; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-spnego-trace-%ls\\%ls", case_id, suffix); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, bytes, length, &written, NULL) || written != length) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file);return result; +} +static DWORD write_token(const RmmTokenProbe *token) { + char report[1024]; + int count = snprintf(report, sizeof(report), "{" TOKEN_FIELDS "}\n", TOKEN_VALUES(token)); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + return write_new(L"token.json", report, (DWORD)count); +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace, const RmmClockEeInfo *eeinfo, const RmmClockAuthTrace *auth, const RmmTokenProbe *token) { + char id[37], report[4096]; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-spnego-v1\",\"case_id\":\"%s\"," + "\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":%lu," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (unsigned long)auth->status_query_invocations, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + if (count < 3 || eeinfo->count > 4) return ERROR_INVALID_DATA; + /* Replace only the final root-object closure; original trace stays intact. */ + size_t used = (size_t)count - 2; + int appended = snprintf(report + used, sizeof(report) - used, + ",\"eeinfo\":{\"capture_attempted\":%lu,\"start_status\":%lu,\"next_status\":%lu," + "\"end_status\":%lu,\"count\":%lu,\"limit_reached\":%lu,\"records\":[", + (unsigned long)eeinfo->capture_attempted, (unsigned long)eeinfo->start_status, + (unsigned long)eeinfo->next_status, (unsigned long)eeinfo->end_status, + (unsigned long)eeinfo->count, (unsigned long)eeinfo->limit_reached); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + for (unsigned i = 0; i < eeinfo->count; ++i) { + const RmmClockEeRecord *record = &eeinfo->records[i]; + appended = snprintf(report + used, sizeof(report) - used, + "%s{\"generating_component\":%lu,\"status\":%lu,\"detection_location\":%lu," + "\"flags\":%lu,\"number_of_parameters\":%ld}", i ? "," : "", + (unsigned long)record->generating_component, (unsigned long)record->status, + (unsigned long)record->detection_location, (unsigned long)record->flags, + (long)record->number_of_parameters); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + } + appended = snprintf(report + used, sizeof(report) - used, + "]},\"token\":{" TOKEN_FIELDS "},\"auth\":{" + "\"discovery_invocations\":%lu,\"discovery_status\":%lu,\"discovery_return_present\":%lu," + "\"principal_present\":%lu,\"principal_units\":%lu,\"principal_validated\":%lu," + "\"status_query_invocations\":%lu,\"authn_service\":%lu,\"authn_level\":%lu,\"impersonation_type\":%lu," + "\"principal_free_attempted\":%lu,\"principal_free_status\":%lu,\"binding_free_attempted\":%lu," + "\"binding_free_status\":%lu,\"eeinfo_origin\":%lu}}\n", + TOKEN_VALUES(token), (unsigned long)auth->discovery_invocations, (unsigned long)auth->discovery_status, + (unsigned long)auth->discovery_return_present, (unsigned long)auth->principal_present, + (unsigned long)auth->principal_units, (unsigned long)auth->principal_validated, + (unsigned long)auth->status_query_invocations, (unsigned long)auth->authn_service, + (unsigned long)auth->authn_level, (unsigned long)auth->impersonation_type, + (unsigned long)auth->principal_free_attempted, (unsigned long)auth->principal_free_status, + (unsigned long)auth->binding_free_attempted, (unsigned long)auth->binding_free_status, + (unsigned long)auth->eeinfo_origin); + if (appended <= 0 || (size_t)appended >= sizeof(report) - used) return ERROR_BUFFER_OVERFLOW; + used += (size_t)appended; + count = (int)used; + return write_new(L"result.json", report, (DWORD)count); +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + RmmTokenProbe token = {0}; + DWORD result = own_system_token(&token); + DWORD token_write = write_token(&token); /* durable numeric witness before RPC */ + if (!result) result = token_write; + if (!result) { + RmmClockTrace trace = {0}; + RmmClockEeInfo eeinfo = {0}; + RmmClockAuthTrace auth = {0}; + uint32_t rpc = rmm_clock_query_trace_spnego(&trace, &eeinfo, &auth); + result = write_result(rpc, &trace, &eeinfo, &auth, &token); + } + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock-system-trace/build.py b/deploy/windows/clock-system-trace/build.py new file mode 100644 index 0000000..38a4f5f --- /dev/null +++ b/deploy/windows/clock-system-trace/build.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Local-only SYSTEM trace diagnostic build; no VM and no product source edits.""" +import base64 +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-system-trace' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +BASELINE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912/qualification.json' +BASELINE_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +NATIVE = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = NATIVE / 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' + + +def require(value, message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, raw): + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def save(path, value): + write(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def original_sources(): + require(sha(BASELINE) == BASELINE_SHA, 'original b1d3 qualification') + value = json.loads(BASELINE.read_bytes()) + require(len(value['source_files']) == 131 and value['artifact']['sha256'] == 'b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560', 'unchanged complete original131 source set') + for name, digest in value['source_files'].items(): + path = ROOT / name + require(not path.is_symlink() and path.is_file() and sha(path) == digest, 'original131 input changed') + return value + + +def own_sources(): + return {str((HERE / name).relative_to(ROOT)):sha(HERE / name) for name in ('system_trace.c','build.py','native.py')} + + +def main(): + os.umask(0o077) + baseline = original_sources(); before = own_sources() + require(sha(READBACK) == READBACK_SHA, 'actual Microsoft codegen readback') + receipt = json.loads(READBACK.read_bytes()) + require(receipt['readback_only'] is True and receipt['result']['complete'] is True + and receipt['result']['run']['exit_code'] == 0 and receipt['result']['no_rpc'] is True, + 'actual completed MIDL codegen') + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700, parents=True) + source = folder / 'source'; source.mkdir(mode=0o700) + generated = {} + for name, digest in baseline['generated_inputs'].items(): + path = NATIVE / ('native-' + name); raw = path.read_bytes() + item = next(item for item in receipt['files'] if item['name'] == name) + require(sha(path) == item['sha256'] == digest and len(raw) == item['bytes'] + and base64.b64decode(item['base64'], validate=True) == raw, 'same actual unchanged Microsoft output') + write(source / name, raw); generated[name] = digest + wrapper = ROOT / 'crates/agent-windows/native/clock_rpc.c' + write(source / 'clock_rpc.c', wrapper.read_bytes()); write(source / 'system_trace.c', (HERE / 'system_trace.c').read_bytes()) + save(folder / 'intent.json', dict(image=IMAGE, original131=baseline['source_files'], baseline_sha256=BASELINE_SHA, + actual_codegen_readback_sha256=READBACK_SHA, generated=generated, own_sources=before, + wrapper_sha256=sha(wrapper), own_system_token_only=True, exactly_one_trace_call=True, no_vm=True)) + output = folder / 'output'; output.mkdir(mode=0o700) + checks = {} + def run(name, args): + command = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=128m', + '-v',str(source)+':/src:ro','-v',str(output)+':/out','--entrypoint',args[0],IMAGE,*args[1:]] + done = subprocess.run(command,capture_output=True,timeout=120) + write(folder / (name+'.stdout'),done.stdout); write(folder / (name+'.stderr'),done.stderr) + checks[name] = dict(exit_code=done.returncode,command=command,stdout_sha256=sha(folder / (name+'.stdout')),stderr_sha256=sha(folder / (name+'.stderr'))) + save(folder / (name+'.json'),checks[name]); require(done.returncode == 0,'local diagnostic compile/check failure: '+name) + return done.stdout + flags = ['--target=x86_64-w64-windows-gnu','-fms-extensions','-Wall','-Wextra','-Werror','-D_M_AMD64=100','-I/src','-O2'] + run('main',['clang',*flags,'-c','/src/system_trace.c','-o','/out/system_trace.o']) + run('wrapper',['clang',*flags,'-c','/src/clock_rpc.c','-o','/out/clock_rpc.o']) + run('actual-midl',['clang',*flags,'-Wno-error=missing-braces','-Wno-error=unused-const-variable','-c','/src/w32time_c.c','-o','/out/w32time_c.o']) + run('link',['x86_64-w64-mingw32-gcc','-static-libgcc','-municode','/out/system_trace.o','/out/clock_rpc.o','/out/w32time_c.o', + '-lrpcrt4','-ladvapi32','-lkernel32','-lmincore','-o','/out/ClockSystemTrace.linked.exe']) + raw_linked = output / 'ClockSystemTrace.linked.exe' + linked = output / 'ClockSystemTrace.original.exe'; delivery = output / 'ClockSystemTrace.exe' + # Retain a caller-owned private exact copy; Docker's root-owned raw link is + # kept too. No chmod/chown of unrelated objects or source mutation. + shutil.copyfile(raw_linked,linked); linked.chmod(0o600) + shutil.copyfile(linked,delivery); delivery.chmod(0o600) + run('strip',['x86_64-w64-mingw32-strip','--strip-debug','/out/ClockSystemTrace.exe']) + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)',run('imports',['x86_64-w64-mingw32-objdump','-p','/out/ClockSystemTrace.exe']).decode()))) + require(imports and {name.lower() for name in imports}.issubset({'kernel32.dll','msvcrt.dll','advapi32.dll','rpcrt4.dll','api-ms-win-core-realtime-l1-1-2.dll'}),'reviewed system DLL imports only') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64],'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) < 1048576,'bounded standalone C x64 PE') + spec = importlib.util.spec_from_file_location('system_trace_native',HERE / 'native.py'); native = importlib.util.module_from_spec(spec); spec.loader.exec_module(native) + script = folder / 'native.ps1'; write(script,native.SCRIPT.encode()) + parser = "$e=$null;$t=$null;[System.Management.Automation.Language.Parser]::ParseFile($args[0],[ref]$t,[ref]$e)|Out-Null;if($e.Count){$e|ForEach-Object{$_.Message};exit 1};'AST_PASS'" + parser_path = folder / 'parse-native.ps1'; write(parser_path,parser.encode()) + parsed = subprocess.run(['/tmp/rmm-powershell-parser/pwsh','-NoLogo','-NoProfile','-NonInteractive','-File',str(parser_path),str(script)],capture_output=True,timeout=15) + write(folder / 'powershell-parser.stdout',parsed.stdout); write(folder / 'powershell-parser.stderr',parsed.stderr) + require(parsed.returncode == 0 and b'AST_PASS' in parsed.stdout and not parsed.stderr,'actual PowerShell AST') + command_chars = len(native.encoded_command()) + require(command_chars < 32767,'Windows encoded command length') + require(original_sources()['source_files'] == baseline['source_files'] and own_sources() == before,'all original131 and new sources unchanged') + manifest = dict(schema_version=1,profile='clock-system-trace-v1',image=IMAGE,baseline_sha256=BASELINE_SHA, + original131=baseline['source_files'],own_sources=before,wrapper_sha256=sha(wrapper),generated=generated, + actual_codegen_readback_sha256=READBACK_SHA,checks=checks,script_sha256=hashlib.sha256(native.SCRIPT.encode()).hexdigest(), + powershell_ast_passed=True,encoded_command_characters=command_chars, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),imports=imports), + linked=dict(path=str(linked),sha256=sha(linked)),raw_linked_sha256=sha(raw_linked),native_executed=False,clock_qualified=False, + adapter_qualified=False,product_gate_open=False,no_vm=True,no_rmm_jobs=True) + save(folder / 'manifest.json',manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'),artifact=manifest['artifact'], + original131_unchanged=True,powershell_ast=True,command_characters=command_chars,native_executed=False))) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_LOCAL_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-system-trace/native.py b/deploy/windows/clock-system-trace/native.py new file mode 100644 index 0000000..0d7c667 --- /dev/null +++ b/deploy/windows/clock-system-trace/native.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""Parent-only native SYSTEM trace bootstrap: prepare, once start, read, cleanup. + +Readback is strictly read-only. Cleanup is a separate explicit phase and may +remove only this exact stopped diagnostic service. Never changes W32Time/RMM. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +STATE = ROOT / 'devstate/windows-clock-system-trace' +ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') + + +def require(value,message): + if not value: raise RuntimeError(message) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(items): + result = {} + for name,value in items: + require(name not in result,'duplicate JSON key'); result[name] = value + return result + + +def private(path,directory=False): + item = Path(path).lstat() + require(item.st_uid == os.getuid() and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),'private owned path') + + +def load(path): + private(path); require(Path(path).stat().st_size <= 2*1024*1024,'bounded private JSON') + return json.loads(Path(path).read_bytes(),object_pairs_hook=pairs) + + +def save(path,value): + private(path.parent,True) + fd = os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as output: + json.dump(value,output,indent=2); output.flush(); os.fsync(output.fileno()) + + +SCRIPT = r''' +$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id-cne$p.id-or$p.profile-cne'clock-system-trace-v1'-or$p.action-notin@('prepare','start','readback','cleanup')-or$p.binary_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed SYSTEM diagnostic request'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$name='RmmClockSystemDiagnostic';$case=Join-Path $root ('clock-system-trace-'+$id);$exe=Join-Path $case 'ClockSystemTrace.exe';$command='"'+$exe+'" --service '+$id +function Test-RmmTracePrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private object type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private object owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private ACL'}}} +function Write-RmmTraceNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmTraceJson($path){Test-RmmTracePrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt16384){throw 'Small diagnostic receipt'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Get-RmmTraceService{return(Get-CimInstance Win32_Service -Filter "Name='RmmClockSystemDiagnostic'" -OperationTimeoutSec 5)} +function Test-RmmTraceService($s){if($s-and($s.PathName-cne$command-or$s.StartName-cne'LocalSystem'-or$s.StartMode-cne'Manual')){throw 'Only own exact temporary service'}} +if($p.action-eq'readback'-and!(Test-Path -LiteralPath $case)){@{id=$id;status='remote_case_absent';read_only=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $root $true +if($p.action-eq'prepare'){if((Test-Path -LiteralPath $case)-or(Get-RmmTraceService)){throw 'Existing case/service retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmTracePrivate $case $true;Write-RmmTraceNew (Join-Path $case 'intent.json') $p;@{id=$id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmTracePrivate $case $true;$old=Get-RmmTraceJson (Join-Path $case 'intent.json') +foreach($field in @('id','profile','binary_sha256','manifest_sha256','script_sha256','binary_bytes')){if($old.$field-cne$p.$field){throw 'Original exact diagnostic intent'}} +Test-RmmTracePrivate $exe $false;if((Get-Item -LiteralPath $exe).Length-ne$p.binary_bytes-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.binary_sha256){throw 'Exact diagnostic executable'} +$s=Get-RmmTraceService;Test-RmmTraceService $s +if($p.action-eq'start'){ + if($s-or(Test-Path -LiteralPath (Join-Path $case 'start-intent.json'))){throw 'No repeated start; original readback only'} + Write-RmmTraceNew (Join-Path $case 'start-intent.json') @{id=$id;command=$command;binary_sha256=$p.binary_sha256;create_once=$true} + New-Service -Name $name -BinaryPathName $command -StartupType Manual|Out-Null + $s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s){throw 'Own service creation missing'} + Write-RmmTraceNew (Join-Path $case 'service-created.json') @{id=$id;command=$command;start_name=$s.StartName} + Write-RmmTraceNew (Join-Path $case 'service-start-intent.json') @{start_once=$true} + Start-Service -Name $name + $deadline=[DateTime]::UtcNow.AddSeconds(20) + do{$s=Get-RmmTraceService;Test-RmmTraceService $s;if(!$s-or$s.State-eq'Stopped'){break};Start-Sleep -Milliseconds 100}while([DateTime]::UtcNow-lt$deadline) +} +if($p.action-eq'cleanup'){ + if(!$s){if(!(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'))){throw 'Missing service without bound cleanup'};@{id=$id;cleanup_verified=$true;already_absent=$true;read_only=$true}|ConvertTo-Json -Compress;exit 0} + if($s.State-cne'Stopped'){throw 'Cleanup only own bound stopped service'} + $created=Get-RmmTraceJson (Join-Path $case 'service-created.json');if($created.id-cne$id-or$created.command-cne$command-or$created.start_name-cne'LocalSystem'){throw 'Original service creation binding'} + if(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json')){throw 'Cleanup already attempted; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-intent.json') @{id=$id;command=$command;delete_once=$true} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE-ne0){throw 'Own stopped service deletion incomplete'} + if(Get-RmmTraceService){throw 'Own service still registered; readback only'} + Write-RmmTraceNew (Join-Path $case 'cleanup-completed.json') @{id=$id;service_absent=$true} + @{id=$id;cleanup_verified=$true;already_absent=$false;read_only=$false}|ConvertTo-Json -Compress;exit 0 +} +$report=$null;$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){$report=Get-RmmTraceJson $result} +$cleaned=$false;$cleanupReceipt=Join-Path $case 'cleanup-completed.json';if(Test-Path -LiteralPath $cleanupReceipt){$c=Get-RmmTraceJson $cleanupReceipt;if($c.id-cne$id-or$c.service_absent-ne$true){throw 'Bound cleanup receipt'};$cleaned=$true} +@{id=$id;service_present=[bool]$s;service_state=$(if($s){$s.State}else{$null});service_exit_code=$(if($s){$s.ExitCode}else{$null});start_intent_present=(Test-Path -LiteralPath (Join-Path $case 'service-start-intent.json'));cleanup_intent_present=(Test-Path -LiteralPath (Join-Path $case 'cleanup-intent.json'));cleanup_completed=$cleaned;report=$report;read_only=($p.action-eq'readback');no_rmm_jobs=$true;no_w32time_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress +''' + + +def encoded_command(): + script = 'try {\n'+SCRIPT+'\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + return 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '+base64.b64encode(script.encode('utf-16le')).decode() + + +def manifest(path): + path = path.absolute(); private(path.parent,True) + require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name),'fixed local build manifest') + value = load(path) + require(value['profile'] == 'clock-system-trace-v1' and value['schema_version'] == 1 + and value['native_executed'] is False and value['clock_qualified'] is False and value['product_gate_open'] is False + and value['powershell_ast_passed'] is True and value['encoded_command_characters'] == len(encoded_command()) < 32767 + and value['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(),'same reviewed nonqualifying diagnostic source') + for name,digest in value['own_sources'].items():require(sha(ROOT / name) == digest,'same original local driver source') + for name in ('artifact','linked'): + item=value[name];p=Path(item['path']);require(p.parent == path.parent / 'output','fixed retained PE path');private(p);require(sha(p) == item['sha256'],'retained exact diagnostic PE') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'],'exact PE size') + return value + + +def access(root): + require(root == ACCESS_ROOT and root.resolve() == root,'existing Main access root only') + sys.path.insert(0,str(ROOT / 'deploy')) + import vm_access_check + config = vm_access_check.load_config(root / 'credentials/server.conf') + require(config['address'] == '88.99.80.202' and config['username'] == 'root' and config.get('port','22') == '22','fixed existing cloud reverse jump') + record=load(root / 'credentials/windows-dev-access.json');expiry=dt.datetime.fromisoformat(record['expires_at']) + require(expiry.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expiry,'current existing access only') + private(root / 'credentials',True);private(root / 'credentials/windows-dev.known_hosts') + key=str(Path(config['ssh_key_path']).expanduser()) + jump=['ssh','-F','/dev/null','-T','-p','22','-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240','root@88.99.80.202'] + prefix=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev','-o','UserKnownHostsFile='+str(root / 'credentials/windows-dev.known_hosts'),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1'] + require(record['ssh_prefix'] == prefix,'original pinned transport only') + return prefix + + +def run_transport(args,data,folder): + try: + done=subprocess.run(args,input=data,capture_output=True,timeout=50) + save(folder / ('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=done.returncode,stdout_b64=base64.b64encode(done.stdout).decode(),stderr_b64=base64.b64encode(done.stderr).decode())) + require(done.returncode == 0,'transport incomplete; original readback only') + return done.stdout + except subprocess.TimeoutExpired as error: + save(folder / ('transport-timeout-'+str(uuid.uuid4())+'.json'),dict(timed_out=True,stdout_b64=base64.b64encode(error.stdout or b'').decode(),stderr_b64=base64.b64encode(error.stderr or b'').decode())) + raise RuntimeError('lost reply; no repeated operation') from None + + +def rpc(prefix,payload,folder): + value=json.loads(run_transport(prefix+[encoded_command()],(json.dumps(payload)+'\n').encode(),folder).decode('utf-8-sig'),object_pairs_hook=pairs) + require(isinstance(value,dict) and 'bootstrap_error' not in value,'remote diagnostic incomplete') + return value + + +def check_report(value,ident): + require(value['id'] == ident and value['no_rmm_jobs'] is True and value['no_w32time_change'] is True and value['no_agent_change'] is True,'exact nonproduct diagnostic case') + report=value.get('report') + if report is None:return False + require(report['schema_version'] == 1 and report['profile'] == 'clock-system-trace-v1' and report['case_id'] == ident + and report['token_system'] is True and report['read_only'] is True and report['diagnostic_only'] is True + and report['query_invocations'] == 1 and report['clock_qualified'] is False and report['adapter_qualified'] is False + and report['product_gate_open'] is False,'actual SYSTEM token and single nonqualifying trace') + fields={'stage','native_rpc_return','native_rpc_return_present','rpc_exception','status_present','ul_size','c_entries','p_entries_present'} + require(set(report['trace']) == fields and type(report['rpc_code']) is int and 0 <= report['rpc_code'] < 2**32 + and all(type(n) is int and 0 <= n < 2**32 for n in report['trace'].values()),'bounded numeric trace only') + return (value['service_state'] == 'Stopped' and value['service_exit_code'] == 0) or (value['service_present'] is False and value['cleanup_completed'] is True) + + +def execute(action,path,root,ident): + os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True);private(STATE,True) + value=manifest(path);prefix=access(root) + if action == 'prepare': + require(not ident,'new diagnostic case only');ident=str(uuid.uuid4());folder=STATE / ident;folder.mkdir(mode=0o700) + payload=dict(id=ident,profile='clock-system-trace-v1',manifest_sha256=sha(path),binary_sha256=value['artifact']['sha256'],binary_bytes=value['artifact']['bytes'],script_sha256=value['script_sha256']) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path.absolute()),access_root=str(root))) + print(json.dumps(dict(case_id=ident,prepare_once=True)),flush=True) + prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder / 'prepared-remote.json',prepared);require(prepared == dict(id=ident,prepared=True),'new private remote case') + save(folder / 'upload-intent.json',dict(binary_sha256=payload['binary_sha256'],upload_once=True)) + args=['sftp']+[p for p in prefix[1:-1] if p != '-T']+['-b','-',prefix[-1]] + destination='/C:/ProgramData/RustDiscoveryBootstrap/clock-system-trace-'+ident+'/ClockSystemTrace.exe' + run_transport(args,('put '+json.dumps(value['artifact']['path'])+' '+json.dumps(destination)+'\n').encode(),folder) + save(folder / 'upload-completed.json',dict(uploaded=True));print(json.dumps(dict(case_id=ident,prepared=True,service_started=False)));return + require(str(uuid.UUID(ident)) == ident,'canonical original case') + folder=STATE / ident;private(folder,True);original=load(folder / 'intent.json');payload=original['payload'] + require(original['manifest_path'] == str(path.absolute()) and original['access_root'] == str(root) + and payload['manifest_sha256'] == sha(path) and payload['script_sha256'] == value['script_sha256'],'original same-case input tuple') + if action in ('start','cleanup'): + if action == 'start':require(load(folder / 'upload-completed.json')['uploaded'] is True,'completed original upload') + save(folder / (action+'-intent.json'),dict(action=action,once=True)) + result=rpc(prefix,dict(payload,action=action),folder);save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if action == 'cleanup': + require(result.get('id') == ident and result.get('cleanup_verified') is True,'own stopped service cleanup only') + print(json.dumps(dict(case_id=ident,cleanup_verified=True)));return + if result.get('status'): + require(action == 'readback' and result['status'] == 'remote_case_absent','read-only original partial status') + print(json.dumps(dict(case_id=ident,complete=False,retry_allowed=False)));return + complete=check_report(result,ident) + if complete: + destination=folder / 'diagnostic-result.json' + receipt=dict(complete=True,manifest_sha256=sha(path),actual=result,clock_qualified=False,product_gate_open=False) + if destination.exists():require(load(destination)['actual']['report'] == result['report'],'preserve original numeric report') + else:save(destination,receipt) + print(json.dumps(dict(case_id=ident,diagnostic_complete=complete,rpc_code=result['report']['rpc_code'] if complete else None, + stage=result['report']['trace']['stage'] if complete else None,clock_qualified=False,cleanup_separate=True))) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','start','readback','cleanup')) + parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--access-root',type=Path,required=True);parser.add_argument('--id') + parser.add_argument('--execute-native',action='store_true');args=parser.parse_args() + require((args.action == 'readback' and not args.execute_native) or (args.action != 'readback' and args.execute_native),'explicit native effect phase; readback only reads') + execute(args.action,args.manifest,args.access_root,args.id) + + +if __name__ == '__main__': + try:main() + except Exception as error: + print(json.dumps(dict(error='CLOCK_SYSTEM_TRACE_NATIVE_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/deploy/windows/clock-system-trace/system_trace.c b/deploy/windows/clock-system-trace/system_trace.c new file mode 100644 index 0000000..28654df --- /dev/null +++ b/deploy/windows/clock-system-trace/system_trace.c @@ -0,0 +1,99 @@ +/* Standalone diagnostic only. The original C/Auth/MIDL inputs are linked + * unchanged. Exactly one trace query, only under this process's SYSTEM token. + * No clock setter, token impersonation, NTP/ACL/provider or product gate. */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include + +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "same diagnostic trace ABI"); +uint32_t rmm_clock_query_trace(RmmClockTrace *trace); + +static WCHAR service_name[] = L"RmmClockSystemDiagnostic"; +static WCHAR case_id[37]; +static SERVICE_STATUS_HANDLE status_handle; +static SERVICE_STATUS service_status; + +static DWORD WINAPI control(DWORD event, DWORD type, void *data, void *context) { + (void)event; (void)type; (void)data; (void)context; + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static DWORD own_system_token(void) { + HANDLE token = NULL; + DWORD needed = 0, result = ERROR_SUCCESS; + _Alignas(8) BYTE storage[4096]; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return GetLastError(); + if (!GetTokenInformation(token, TokenUser, storage, sizeof(storage), &needed)) result = GetLastError(); + else if (needed > sizeof(storage) || !IsWellKnownSid(((TOKEN_USER *)storage)->User.Sid, WinLocalSystemSid)) result = ERROR_ACCESS_DENIED; + CloseHandle(token); + return result; +} + +static DWORD write_result(uint32_t rpc, const RmmClockTrace *trace) { + WCHAR path[256]; + char id[37], report[1536]; + DWORD written = 0, result = ERROR_SUCCESS; + for (unsigned i = 0; i < 37; ++i) id[i] = (char)case_id[i]; + int count = swprintf(path, sizeof(path) / sizeof(path[0]), + L"C:\\ProgramData\\RustDiscoveryBootstrap\\clock-system-trace-%ls\\result.json", case_id); + if (count <= 0 || count >= (int)(sizeof(path) / sizeof(path[0]))) return ERROR_INVALID_PARAMETER; + count = snprintf(report, sizeof(report), + "{\"schema_version\":1,\"profile\":\"clock-system-trace-v1\",\"case_id\":\"%s\"," + "\"token_system\":true,\"read_only\":true,\"diagnostic_only\":true,\"query_invocations\":1," + "\"clock_qualified\":false,\"adapter_qualified\":false,\"product_gate_open\":false,\"rpc_code\":%lu," + "\"trace\":{\"stage\":%lu,\"native_rpc_return\":%lu,\"native_rpc_return_present\":%lu," + "\"rpc_exception\":%lu,\"status_present\":%lu,\"ul_size\":%lu,\"c_entries\":%lu,\"p_entries_present\":%lu}}\n", + id, (unsigned long)rpc, (unsigned long)trace->stage, + (unsigned long)trace->native_rpc_return, (unsigned long)trace->native_rpc_return_present, + (unsigned long)trace->rpc_exception, (unsigned long)trace->status_present, + (unsigned long)trace->ul_size, (unsigned long)trace->c_entries, (unsigned long)trace->p_entries_present); + if (count <= 0 || count >= (int)sizeof(report)) return ERROR_BUFFER_OVERFLOW; + HANDLE file = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL); + if (file == INVALID_HANDLE_VALUE) return GetLastError(); + if (!WriteFile(file, report, (DWORD)count, &written, NULL) || written != (DWORD)count) result = ERROR_WRITE_FAULT; + else if (!FlushFileBuffers(file)) result = GetLastError(); + CloseHandle(file); + return result; +} + +static void WINAPI run_service(DWORD argc, WCHAR **argv) { + (void)argc; (void)argv; + status_handle = RegisterServiceCtrlHandlerExW(service_name, control, NULL); + if (!status_handle) return; + ZeroMemory(&service_status, sizeof(service_status)); + service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service_status.dwCurrentState = SERVICE_RUNNING; + service_status.dwControlsAccepted = 0; + if (!SetServiceStatus(status_handle, &service_status)) return; + DWORD result = own_system_token(); + if (!result) { + RmmClockTrace trace = {0}; + uint32_t rpc = rmm_clock_query_trace(&trace); /* exactly one fixed call */ + result = write_result(rpc, &trace); + } + service_status.dwCurrentState = SERVICE_STOPPED; + service_status.dwWin32ExitCode = result; + SetServiceStatus(status_handle, &service_status); +} + +int wmain(int argc, WCHAR **argv) { + if (argc != 3 || wcscmp(argv[1], L"--service") || wcslen(argv[2]) != 36) return ERROR_INVALID_PARAMETER; + for (unsigned i = 0; i < 36; ++i) { + WCHAR value = argv[2][i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (value != L'-') return ERROR_INVALID_PARAMETER; + } else if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) return ERROR_INVALID_PARAMETER; + case_id[i] = value; + } + case_id[36] = 0; + SERVICE_TABLE_ENTRYW table[] = {{service_name, run_service}, {NULL, NULL}}; + if (!StartServiceCtrlDispatcherW(table)) return (int)GetLastError(); + return 0; +} diff --git a/deploy/windows/clock_midl_diagnostic_build.py b/deploy/windows/clock_midl_diagnostic_build.py new file mode 100644 index 0000000..45e4a35 --- /dev/null +++ b/deploy/windows/clock_midl_diagnostic_build.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Local-only, separate MIDL readiness crossbuild. Never accesses a VM. + +Preserves all existing runners, product sources, generated outputs and evidence. +Each invocation creates a fresh source snapshot and records failed checks too. +""" +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[2] +PACKAGE = Path('deploy/windows/clock-midl-diagnostic') +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +CODEGEN = ROOT / 'devstate/windows-clock-midl/native-cases/149bafe2-3469-4580-b133-988812bcc3db' +READBACK = 'readback-059c15ef-0f31-41aa-ad1d-ea6b774280d7.json' +READBACK_SHA = '0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c' +PINNED = { + 'w32time.h': 'db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde', + 'w32time_c.c': 'd806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38', +} + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def write_new(path, raw): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as out: + out.write(raw) + out.flush() + os.fsync(out.fileno()) + + +def save(path, value): + write_new(path, (json.dumps(value, indent=2) + '\n').encode()) + + +def compiler_inputs(): + paths = [ROOT / name for name in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml')] + paths += [p for p in (ROOT / 'crates').rglob('*') if p.is_file() and p.suffix in ('.rs', '.toml', '.c', '.idl')] + paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()] + paths += [ROOT / PACKAGE / name for name in ('Cargo.toml', 'build.rs')] + paths += [Path(__file__).resolve()] + require(all(not p.is_symlink() for p in paths), 'compiler input symlink') + return {str(p.relative_to(ROOT)): sha(p.read_bytes()) for p in sorted(paths)} + + +def external_packages(lock): + # Only compare Cargo-generated fixed string fields; never execute TOML. + result = set() + for block in lock.split('[[package]]')[1:]: + fields = dict(re.findall(r'^(name|version|source|checksum) = "([^"\n]+)"$', block, re.M)) + if 'source' in fields: + require(set(fields) == {'name', 'version', 'source', 'checksum'}, 'unrecognized external lock entry') + result.add(tuple(fields[key] for key in ('name', 'version', 'source', 'checksum'))) + return result + + +def main(): + os.umask(0o077) + before = compiler_inputs() + receipt_raw = (CODEGEN / READBACK).read_bytes() + require(sha(receipt_raw) == READBACK_SHA, 'original native readback hash changed') + receipt = json.loads(receipt_raw) + result = receipt['result'] + require(receipt['readback_only'] is True and result['complete'] is True and result['no_rpc'] is True + and result['run']['exit_code'] == 0 and result['run']['all_own_children_exited'] is True + and result['clock_qualified'] is False, 'native codegen readback incomplete') + ident = str(uuid.uuid4()) + case = ROOT / 'devstate/windows-clock-midl/diagnostic-builds' / ident + case.mkdir(parents=True, mode=0o700) + source = case / 'source' + source.mkdir(mode=0o700) + for name, digest in before.items(): + raw = (ROOT / name).read_bytes() + require(sha(raw) == digest, 'source changed during snapshot') + write_new(source / name, raw) + for name, digest in PINNED.items(): + raw = (CODEGEN / ('native-' + name)).read_bytes() + original = next(item for item in receipt['files'] if item['name'] == name) + require(sha(raw) == digest == original['sha256'] and len(raw) == original['bytes'] + and base64.b64decode(original['base64'], validate=True) == raw, 'actual Microsoft output differs') + write_new(source / PACKAGE / 'generated' / name, raw) + write_new(source / PACKAGE / 'Cargo.lock', (ROOT / 'Cargo.lock').read_bytes()) + save(case / 'intent.json', dict(id=ident, image=IMAGE, native_case=str(CODEGEN), native_readback_sha256=READBACK_SHA, + source_files=before, microsoft_generated=PINNED, no_vm=True, no_jobs=True, + production_clock_qualified=False)) + print('Retained local MIDL diagnostic build ' + ident, flush=True) + checks = {} + + def run(name, args): + command = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m', + '-v', str(source) + ':/src:ro', '-v', str(case / 'target') + ':/target', + '-v', str(case) + ':/evidence', '-e', 'CARGO_TARGET_DIR=/target', + '--entrypoint', args[0], IMAGE] + args[1:] + with (case / (name + '.log')).open('xb') as output: + completed = subprocess.run(command, stdout=output, stderr=subprocess.STDOUT, timeout=600) + checks[name] = dict(exit_code=completed.returncode, command=command, log_sha256=sha((case / (name + '.log')).read_bytes())) + save(case / (name + '.check.json'), checks[name]) + require(completed.returncode == 0, 'local check failed: ' + name) + print(name + ' PASS', flush=True) + + manifest = '/src/' + str(PACKAGE / 'Cargo.toml') + # Resolve only the new diagnostic leaf against the existing locked versions. + # Snapshot manifest directory is temporarily a private writable mount for + # this sole metadata step; the source worktree is never writable in Docker. + writable = case / 'lock-resolution' + shutil.copytree(source, writable) + metadata_command = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=128m', + '-v', str(writable) + ':/src', '--entrypoint', 'cargo', IMAGE, 'metadata', + '--manifest-path', manifest, '--offline', '--format-version', '1'] + with (case / 'lock-resolution.log').open('xb') as output: + lock_result = subprocess.run(metadata_command, stdout=output, stderr=subprocess.STDOUT, timeout=120) + require(lock_result.returncode == 0, 'diagnostic lock resolution failed') + resolved = (writable / PACKAGE / 'Cargo.lock').read_bytes() + require(external_packages(resolved.decode()).issubset(external_packages((ROOT / 'Cargo.lock').read_text())), 'new external dependency version') + # Replace only our freshly copied diagnostic lock BEFORE build admission; + # this is never an edit to generated NDR/header data or an OUT_DIR patch. + (source / PACKAGE / 'Cargo.lock').write_bytes(resolved) + save(case / 'resolved-lock.json', dict(sha256=sha(resolved), no_new_external_versions=True)) + run('fmt', ['cargo', 'fmt', '--manifest-path', manifest, '--', '--check']) + run('clippy-windows', ['cargo', 'clippy', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--all-targets', '--', '-D', 'warnings']) + run('linux-clock-tests', ['cargo', 'test', '--manifest-path', manifest, '--locked', '--offline', '--bin', 'clock-midl-readiness', '--', '--test-threads=1']) + require('test result: ok. 5 passed; 0 failed; 0 ignored;' in (case / 'linux-clock-tests.log').read_text(), 'actual five clock tests required') + run('windows-test-link', ['cargo', 'build', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--tests']) + run('release-link', ['cargo', 'build', '--manifest-path', manifest, '--locked', '--offline', '--target', 'x86_64-pc-windows-gnu', '--release', '--bin', 'clock-midl-readiness']) + run('artifact', ['sh', '-c', 'cp /target/x86_64-pc-windows-gnu/release/clock-midl-readiness.exe /evidence/WindowsClockReadiness.linked.exe && cp /evidence/WindowsClockReadiness.linked.exe /evidence/WindowsClockReadiness.exe && x86_64-w64-mingw32-strip /evidence/WindowsClockReadiness.exe && x86_64-w64-mingw32-objdump -p /evidence/WindowsClockReadiness.exe']) + require(compiler_inputs() == before, 'source inputs changed during diagnostic build') + executable = case / 'WindowsClockReadiness.exe' + qualification = dict(id=ident, source_files=before, source_before_after_identical=True, image=IMAGE, + native_codegen_case=CODEGEN.name, native_readback_sha256=READBACK_SHA, + generated_inputs=PINNED, checks=checks, artifact=dict(path=str(executable), sha256=sha(executable.read_bytes()), bytes=executable.stat().st_size), + linked_binary_sha256=sha((case / 'WindowsClockReadiness.linked.exe').read_bytes()), + linux_clock_test_count=5, native_windows_execution=False, native_cloud_linux_execution=False, + production_clock_qualified=False, no_vm=True, no_jobs=True) + save(case / 'qualification.json', qualification) + print(json.dumps(dict(id=ident, artifact=qualification['artifact'], qualification_sha256=sha((case / 'qualification.json').read_bytes()), no_vm=True, clock_qualified=False))) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/clock_midl_linux_native.py b/deploy/windows/clock_midl_linux_native.py new file mode 100644 index 0000000..ba57bd8 --- /dev/null +++ b/deploy/windows/clock_midl_linux_native.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Package existing five portable clock units; only Root invokes native phases. + +No build, Windows/NDR execution, RMM daemon, service, policy, DB or job action. +Lost native replies permit readback of the same case only, never another run. +""" +import argparse +import base64 +import hashlib +import inspect +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'deploy')) +import remote_client_bootstrap as linux +import vm_mvp_acceptance as contract + +CASE = ROOT / 'devstate/windows-clock-midl/diagnostic-builds/181c3a1c-8324-41fd-9b7c-aa8010262912' +QUALIFICATION_SHA = '2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb' +STATE = ROOT / 'devstate/windows-clock-midl/linux-native-packs' +REMOTE = '/var/lib/rmm-clock-midl-portable-tests' +TESTS = ( + 'clock::tests::gate_requires_all_status_and_uncertainty_evidence', + 'clock::tests::production_clock_stays_closed_until_native_adapter_qualification', + 'clock::tests::suspend_closes_until_actual_post_resume_sync', + 'clock::tests::timeout_worker_stays_closed_without_a_second_call', + 'clock::tests::wall_step_and_overflow_fail_closed', +) +require = contract.require + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def support_sources(): + return {str(Path(module.__file__).resolve().relative_to(ROOT)): sha(module.__file__) + for module in (linux, contract, linux.access)} + + +def native_source_sha256(): + return hashlib.sha256(inspect.getsource(native_case).encode()).hexdigest() + + +def save(folder, name, value): + fd = os.open(folder / name, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as out: + json.dump(value, out, indent=2) + out.write('\n') + out.flush() + os.fsync(out.fileno()) + + +def prepare(): + require(sha(CASE / 'qualification.json') == QUALIFICATION_SHA, 'original build qualification') + qualified = contract.protected_json(CASE / 'qualification.json') + require(qualified['linux_clock_test_count'] == 5 and qualified['no_vm'] is True, 'five local portable guards only') + original = CASE / 'target/debug/deps/clock_midl_readiness-277aee462cb4f674' + raw = original.read_bytes() + require(raw[:6] == b'\x7fELF\x02\x01' and raw[18:20] == b'\x3e\x00', 'existing x64 Linux test executable') + os.umask(0o077) + STATE.mkdir(mode=0o700, parents=True, exist_ok=True) + folder = STATE / str(uuid.uuid4()) + folder.mkdir(mode=0o700) + binary = folder / 'clock-portable-tests' + shutil.copyfile(original, binary) + binary.chmod(0o600) + require(sha(binary) == sha(original), 'byte-identical existing test executable') + for name, args in ( + ('elf', ['readelf', '--wide', '--program-headers', '--dynamic', '--version-info', str(binary)]), + ('list', ['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(binary) + ':/tests:ro', + '--entrypoint', '/lib64/ld-linux-x86-64.so.2', qualified['image'], '/tests', '--list', '--format', 'terse']), + ): + completed = subprocess.run(args, capture_output=True, timeout=15) + require(completed.returncode == 0, 'local loader/list metadata failed') + fd = os.open(folder / (name + '.log'), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fd, 'wb') as out: + out.write(completed.stdout) + out.flush() + os.fsync(out.fileno()) + listed = (folder / 'list.log').read_bytes() + require(set(re.findall(rb'^(.+): test$', listed, re.M)) == {name.encode() for name in TESTS}, 'exact existing five-test list') + info = (folder / 'elf.log').read_text() + needed = re.findall(r'\(NEEDED\).*?\[([^\]]+)\]', info) + glibc = sorted(set(re.findall(r'GLIBC_[0-9.]+', info)), key=lambda v: tuple(map(int, v[6:].split('.')))) + require('/lib64/ld-linux-x86-64.so.2' in info and needed and glibc, 'actual ELF loader dependencies') + manifest = dict(schema_version=1, type='rmm.clock.portable-unit-native-pack', original_build=str(CASE), + qualification_sha256=QUALIFICATION_SHA, runner_sha256=sha(__file__), + support_sources=support_sources(), native_case_sha256=native_source_sha256(), + artifact=dict(path=str(binary), bytes=binary.stat().st_size, sha256=sha(binary)), + original_test_executable=str(original), selected_tests=list(TESTS), + interpreter='/lib64/ld-linux-x86-64.so.2', needed=needed, maximum_glibc=glibc[-1], + list_sha256=sha(folder / 'list.log'), elf_sha256=sha(folder / 'elf.log'), + compiled_new_code=False, stripped=False, native_vm_executed=False, + linux_ndr_tested=False, windows_rpc_tested=False, product_clock_qualified=False) + save(folder, 'manifest.json', manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'), manifest_sha256=sha(folder / 'manifest.json'), + artifact=manifest['artifact'], interpreter=manifest['interpreter'], needed=needed, + maximum_glibc=glibc[-1], selected_tests=5, native_vm_executed=False))) + + +def verified(path): + manifest = contract.protected_json(path) + require(manifest['runner_sha256'] == sha(__file__) and manifest['selected_tests'] == list(TESTS), 'frozen native pack runner and exact tests') + require(manifest['support_sources'] == support_sources() and manifest['native_case_sha256'] == native_source_sha256(), 'frozen native transport/parser sources') + require(manifest['qualification_sha256'] == QUALIFICATION_SHA == sha(CASE / 'qualification.json'), 'actual original build') + require(manifest['compiled_new_code'] is False and manifest['stripped'] is False and manifest['native_vm_executed'] is False, 'existing portable harness only') + binary = Path(manifest['artifact']['path']) + require(sha(binary) == manifest['artifact']['sha256'] and binary.stat().st_size == manifest['artifact']['bytes'] + and sha(manifest['original_test_executable']) == sha(binary), 'unchanged actual original Linux harness') + return manifest + + +def native_case(payload): + import resource + import stat + import time + root = Path('/var/lib/rmm-clock-midl-portable-tests') + ident = str(uuid.UUID(payload['id'])) + names = [ + 'clock::tests::gate_requires_all_status_and_uncertainty_evidence', + 'clock::tests::production_clock_stays_closed_until_native_adapter_qualification', + 'clock::tests::suspend_closes_until_actual_post_resume_sync', + 'clock::tests::timeout_worker_stays_closed_without_a_second_call', + 'clock::tests::wall_step_and_overflow_fail_closed', + ] + require(payload['id'] == ident and payload['action'] in ('prepare', 'run', 'read') + and payload['tests'] == names and os.geteuid() == 0, 'fixed exact portable test case') + digest = payload['binary_sha256'] + require(len(digest) == 64 and all(c in '0123456789abcdef' for c in digest), 'fixed binary hash') + def safe(path, directory): + value = path.lstat() + require(value.st_uid == 0 and not value.st_mode & 0o077 and not stat.S_ISLNK(value.st_mode) + and (stat.S_ISDIR(value.st_mode) if directory else stat.S_ISREG(value.st_mode)), 'private fixed test path') + def write(path, value): + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as out: + json.dump(value, out) + out.flush() + os.fsync(out.fileno()) + if payload['action'] == 'prepare' and not root.exists(): + root.mkdir(mode=0o700) + safe(root, True) + case = root / ident + if payload['action'] == 'prepare': + case.mkdir(mode=0o700) + write(case / 'intent.json', payload) + return dict(prepared=True) + safe(case, True) + safe(case / 'intent.json', False) + intent = json.loads((case / 'intent.json').read_bytes()) + require(all(intent[key] == payload[key] for key in ('id', 'binary_sha256', 'manifest_sha256', 'tests', 'runner_sha256', 'support_sources', 'native_case_sha256')), 'original create-once intent') + if payload['action'] == 'read': + safe(case / 'result.json', False) + return json.loads((case / 'result.json').read_bytes()) + binary = case / 'clock-portable-tests' + safe(binary, False) + require(hashlib.sha256(binary.read_bytes()).hexdigest() == digest, 'actual staged original test bytes') + write(case / 'started.json', dict(binary_sha256=digest, tests=names, never_repeat_start=True)) + binary.chmod(0o500) + temporary = case / 'tmp' + temporary.mkdir(mode=0o700) + env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'TMPDIR': str(temporary), 'RUST_BACKTRACE': '0'} + namespace = subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3) + require(namespace.returncode == 0, 'network namespace required; no fallback') + loader = subprocess.run(['/lib64/ld-linux-x86-64.so.2', '--list', str(binary)], env=env, capture_output=True, timeout=3) + require(loader.returncode == 0 and len(loader.stdout) <= 16384 and len(loader.stderr) <= 16384, 'actual native loader compatibility') + def limits(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576)) + resource.setrlimit(resource.RLIMIT_CPU, (10, 10)) + results = [] + deadline = time.monotonic() + 20 + for number, name in enumerate(names): + output = case / (str(number) + '-stdout.bin') + errors = case / (str(number) + '-stderr.bin') + timed_out = False + with output.open('xb') as stdout, errors.open('xb') as stderr: + output.chmod(0o600) + errors.chmod(0o600) + try: + remaining = deadline - time.monotonic() + require(remaining > 0, 'aggregate test deadline') + child = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--exact', name, '--test-threads=1'], + cwd=case, env=env, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, + timeout=min(5, remaining), preexec_fn=limits) + code = child.returncode + except subprocess.TimeoutExpired: + timed_out = True + code = None + stdout.flush() + stderr.flush() + os.fsync(stdout.fileno()) + os.fsync(stderr.fileno()) + raw, err = output.read_bytes(), errors.read_bytes() + require(len(raw) <= 1048576 and len(err) <= 1048576, 'bounded unit output') + results.append(dict(name=name, exit_code=code, timed_out=timed_out, stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(err).decode())) + if code != 0: + break + report = dict(id=ident, binary_sha256=digest, manifest_sha256=payload['manifest_sha256'], results=results, + native_platform='linux', network_namespace=True, environment_cleared=True, + loader_stdout_sha256=hashlib.sha256(loader.stdout).hexdigest(), linux_ndr_tested=False, + windows_rpc_tested=False, product_clock_qualified=False, rmm_jobs_created=False) + write(case / 'result.json', report) + return report + + +def native(path, access_root, ident=None): + manifest = verified(path) + linux.ROOT = linux.access.ROOT = access_root.resolve() + os.umask(0o077) + if ident is None: + ident = str(uuid.uuid4()) + folder = STATE / ident + folder.mkdir(mode=0o700) + payload = dict(id=ident, binary_sha256=manifest['artifact']['sha256'], manifest_sha256=sha(path), tests=list(TESTS), + runner_sha256=manifest['runner_sha256'], support_sources=manifest['support_sources'], native_case_sha256=manifest['native_case_sha256']) + save(folder, 'intent.json', dict(payload=payload, manifest_path=str(path.resolve()))) + linux.rpc('linux-vm.conf', native_case, dict(payload, action='prepare')) + cfg = linux.access.load_config(access_root / 'credentials/linux-vm.conf') + args = ['sftp', '-F', '/dev/null', '-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()), + '-b', '-', cfg['username'] + '@' + cfg['address']] + result = subprocess.run(args, input=('put ' + json.dumps(manifest['artifact']['path']) + ' ' + json.dumps(REMOTE + '/' + ident + '/clock-portable-tests') + '\n').encode(), capture_output=True, timeout=120) + save(folder, 'upload.json', dict(returncode=result.returncode)) + require(result.returncode == 0, 'fixed portable binary upload') + save(folder, 'run-intent.json', dict(execute_only_exact_five_portable_units=True)) + value = linux.rpc('linux-vm.conf', native_case, dict(payload, action='run')) + else: + ident = str(uuid.UUID(ident)) + folder = STATE / ident + intent = contract.protected_json(folder / 'intent.json') + payload = intent['payload'] + require(intent['manifest_path'] == str(path.resolve()) and payload['manifest_sha256'] == sha(path), 'original same native case') + require(payload['runner_sha256'] == manifest['runner_sha256'] and payload['support_sources'] == manifest['support_sources'] + and payload['native_case_sha256'] == manifest['native_case_sha256'], 'original same native sources') + value = linux.rpc('linux-vm.conf', native_case, dict(payload, action='read')) + save(folder, 'readback-' + str(uuid.uuid4()) + '.json', value) + require(value['binary_sha256'] == manifest['artifact']['sha256'] and value['manifest_sha256'] == sha(path) + and len(value['results']) == 5 and value['product_clock_qualified'] is False, 'all five exact portable results') + for result, name in zip(value['results'], TESTS, strict=True): + require(result['name'] == name and result['exit_code'] == 0 and result['timed_out'] is False + and b'1 passed; 0 failed; 0 ignored;' in base64.b64decode(result['stdout_b64'], validate=True), 'one exact native portable unit passed') + proof = dict(verified=True, case_id=ident, native_platform='linux', selected_tests=5, manifest_sha256=sha(path), report=value) + if (folder / 'passed.json').exists(): + require(contract.protected_json(folder / 'passed.json') == proof, 'unchanged original native proof') + else: + save(folder, 'passed.json', proof) + print(json.dumps(dict(verified=True, case_id=ident, selected_native_portable_tests=5, linux_ndr_tested=False, product_clock_qualified=False))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare-local', 'native', 'readback')) + parser.add_argument('--manifest', type=Path) + parser.add_argument('--access-root', type=Path) + parser.add_argument('--case') + parser.add_argument('--execute-native-tests', action='store_true') + args = parser.parse_args() + if args.action == 'prepare-local': + require(not (args.manifest or args.access_root or args.case or args.execute_native_tests), 'local packaging only') + prepare() + elif args.action == 'native': + require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'Root explicitly starts one fixed native case') + native(args.manifest, args.access_root) + else: + require(args.manifest and args.access_root and args.case and not args.execute_native_tests, 'same-case readback only') + native(args.manifest, args.access_root, args.case) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/console_access_hash_command.py b/deploy/windows/console_access_hash_command.py new file mode 100644 index 0000000..6b0d670 --- /dev/null +++ b/deploy/windows/console_access_hash_command.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Local CreateNew correction of the public recovery hash function alias clash. + +The User's H/Get-History error occurred in the old pre-effect case/config guard. +Keep the same console case and untouched original files. No target/server call, +alias mutation or retry of an effect; the same case-absence guard still applies. +""" +import argparse +import os +from pathlib import Path +import re + +import console_access_precision as previous + +require, sha, save = previous.require, previous.sha, previous.save +CASE = '5c96d3d8-1657-40c8-a6ec-c00b63a98210' +OLD_SHA = '4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69' +OLD_NAME = 'Recover-ExistingDevAccess.ps1' +NEW_NAME = 'Recover-ExistingDevAccess-HashFix.ps1' +NAME = 'Get-RmmRecoveryFileSha256' +STATE = previous.original.cb.EVIDENCE / 'dev-access-console-hash-correction' + + +def corrected(raw): + require(previous.original.pair.raw_sha(raw) == OLD_SHA, 'exact original reviewed 5c96 public script') + source = raw.decode('utf-8') + require(source.count('function H(') == 1 and NAME not in source, 'one original hash function and fresh unique name') + calls = re.findall(r'\(H\s', source) + require(len(calls) == source.count('(H ') and calls, 'all original H calls have the reviewed spelling') + result = source.replace('function H(', 'function ' + NAME + '(').replace('(H ', '(' + NAME + ' ') + require('function H(' not in result and not re.search(r'\(H\s', result), 'no alias-sensitive hash call remains') + require(result.replace('function ' + NAME + '(', 'function H(').replace('(' + NAME + ' ', '(H ') == source, 'only function/command spelling changed; all effects/pins/case bytes preserved') + return result.encode(), len(calls) + + +def build(): + folder = previous.STATE / CASE + raw = (folder / OLD_NAME).read_bytes() + new, calls = corrected(raw) + STATE.mkdir(mode=0o700, parents=True, exist_ok=False) + previous.original.pair.write_bytes(STATE / NEW_NAME, new) + digest = previous.original.pair.raw_sha(new) + # Literal replacement, UTF8 without BOM, CreateNew, both independent hashes. + # No free script content, Remove-Alias, persistent policy or registry change. + patch = r'''$ErrorActionPreference='Stop' +$oldPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1' +$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1' +if((Get-FileHash -LiteralPath $oldPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OLD@@'){throw 'Falsche Originaldatei; nichts ausfuehren'} +if(Test-Path -LiteralPath $newPath){throw 'Korrekturdatei existiert bereits; nur lesend pruefen'} +$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($oldPath)) +$text=$text.Replace('function H(','function Get-RmmRecoveryFileSha256(').Replace('(H ','(Get-RmmRecoveryFileSha256 ') +$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text) +$out=[IO.File]::Open($newPath,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read) +try{$out.Write($bytes,0,$bytes.Length);$out.Flush($true)}finally{$out.Dispose()} +if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@NEW@@'){throw 'Korrekturhash stimmt nicht; nichts ausfuehren'} +powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath +'''.replace('@@OLD@@', OLD_SHA).replace('@@NEW@@', digest) + previous.original.pair.write_bytes(STATE / 'Create-VerifiedHashFix.ps1', patch.encode()) + save(STATE / 'qualification.json', dict(source_sha256=sha(__file__), source_only=True, same_console_case=CASE, original_script_sha256=OLD_SHA, corrected_script_sha256=digest, renamed_call_count=calls, exact_inverse_spelling_transform=True, all_other_bytes_unchanged=True, original_script_and_zip_unchanged=True, case_absence_guard_retained=True, no_alias_mutation=True, no_server_or_vm_call=True, original_failure='Get-History/IdCannotConvert before New-Item/case or any effect')) + print('corrected_script_sha256=' + digest) + print('patch_sha256=' + sha(STATE / 'Create-VerifiedHashFix.ps1')) + print('renamed_hash_calls=' + str(calls)) + print('patch=' + str((STATE / 'Create-VerifiedHashFix.ps1').resolve())) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build() + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/console_access_original_bootstrap.py b/deploy/windows/console_access_original_bootstrap.py new file mode 100644 index 0000000..4eba9ff --- /dev/null +++ b/deploy/windows/console_access_original_bootstrap.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""One local provenance correction: pin the actually deployed original bootstrap. + +Actual User readonly values identify the published original file, not an unknown +hash. Preserve the same absent console case and every other byte/guard/effect. +No Windows/server access, new expiry, alias/policy change or effect retry. +""" +import argparse +import json +import os +from pathlib import Path +import zipfile + +import console_access_hash_command as previous + +require, sha, save = previous.require, previous.sha, previous.save +STATE = previous.previous.original.cb.EVIDENCE / 'dev-access-console-original-bootstrap-correction' +MAIN = Path('/home/kevin/Schreibtisch/Coding/rust-discovery') +OLD_NAME = 'Recover-ExistingDevAccess-HashFix.ps1' +NEW_NAME = 'Recover-ExistingDevAccess-OriginalBootstrap.ps1' +OLD_SCRIPT_SHA = 'd366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c' +PARENT_SOURCE_SHA = 'b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad' +REPO_BOOTSTRAP_SHA = '9e992602034026efbe17f833d4d6be694da3e223ac6b4a394c502eb140ec0189' +PUBLISHED_BOOTSTRAP_SHA = '332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f' +CONFIG_SHA = '4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823' +BUNDLE_SHA = 'cba159469efad9039562633fd60213d8f6a62f169fc3d1bba915e49d22c764d2' +REPAIR_BUNDLE_SHA = '2558448b7812b95de1612fca5f11da8f4a868764fb45666b128d03eb0c423eb4' + + +def build(facts_path): + require(sha(previous.__file__) == PARENT_SOURCE_SHA, 'immutable reviewed parent hash fix source') + facts = previous.previous.original.cb.contract.protected_json(facts_path) + require(set(facts) == {'case_present', 'config_sha256', 'bootstrap_sha256', 'configured_expiry', 'account_expiry_filetime'} and facts['case_present'] is False and facts['config_sha256'] == CONFIG_SHA and facts['bootstrap_sha256'] == PUBLISHED_BOOTSTRAP_SHA and facts['configured_expiry'] == '2026-11-14T12:55:31.254999+00:00' and facts['account_expiry_filetime'] == '134391345312549990', 'exact actual User readonly original baseline, no unknown hash adoption') + public = MAIN / 'devstate/windows-bootstrap' + require(sha(public / 'windows-dev-access.zip') == BUNDLE_SHA and sha(public / 'windows-dev-repair.zip') == REPAIR_BUNDLE_SHA, 'immutable originally published bundles') + with zipfile.ZipFile(public / 'windows-dev-access.zip') as archive: + bootstrap = archive.read('Bootstrap-DevAccess.ps1'); config = archive.read('bootstrap-public.json') + with zipfile.ZipFile(public / 'windows-dev-repair.zip') as archive: + repair = json.loads(archive.read('repair-public.json')) + raw_sha = previous.previous.original.pair.raw_sha + require(raw_sha(bootstrap) == PUBLISHED_BOOTSTRAP_SHA == repair['previous_bootstrap_sha256'] and raw_sha(config) == CONFIG_SHA, 'actual file equals original publication and independently pinned repair prerequisite') + original_path = previous.STATE / OLD_NAME + require(sha(original_path) == OLD_SCRIPT_SHA, 'exact reviewed parent PS1') + source = original_path.read_bytes().decode('utf-8') + old = "$expectedBootstrap='" + REPO_BOOTSTRAP_SHA + "'" + new = "$expectedBootstrap='" + PUBLISHED_BOOTSTRAP_SHA + "'" + require(source.count(old) == 1 and new not in source, 'single exact original constant') + corrected = source.replace(old, new, 1) + require(corrected.replace(new, old, 1) == source, 'all other bytes including expiry/case/alias/clock/effects unchanged') + STATE.mkdir(mode=0o700, parents=True, exist_ok=False) + save(STATE / 'actual-user-readonly.json', facts) + previous.previous.original.pair.write_bytes(STATE / NEW_NAME, corrected.encode()) + digest = raw_sha(corrected.encode()) + patch = r'''$ErrorActionPreference='Stop' +$inputPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1';$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-OriginalBootstrap.ps1' +if((Get-FileHash -LiteralPath $inputPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@INPUT@@'-or(Test-Path -LiteralPath $newPath)){throw 'Originalhash falsch oder neue Datei bereits vorhanden; nichts ausfuehren'} +$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($inputPath));$text=$text.Replace("`$expectedBootstrap='@@OLD@@'","`$expectedBootstrap='@@PIN@@'");$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text);$file=[IO.File]::Open($newPath,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()} +if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OUTPUT@@'){throw 'Neuer Hash falsch; nichts ausfuehren'} +powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath +''' + for token, value in {'INPUT': OLD_SCRIPT_SHA, 'OLD': REPO_BOOTSTRAP_SHA, 'PIN': PUBLISHED_BOOTSTRAP_SHA, 'OUTPUT': digest}.items(): + patch = patch.replace('@@' + token + '@@', value) + previous.previous.original.pair.write_bytes(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1', patch.encode()) + save(STATE / 'qualification.json', dict(source_only=True, source_sha256=sha(__file__), parent_source_sha256=PARENT_SOURCE_SHA, actual_user_readonly_sha256=sha(STATE / 'actual-user-readonly.json'), same_console_case=previous.CASE, input_script_sha256=OLD_SCRIPT_SHA, corrected_script_sha256=digest, original_bundle_sha256=BUNDLE_SHA, repair_bundle_sha256=REPAIR_BUNDLE_SHA, published_bootstrap_sha256=PUBLISHED_BOOTSTRAP_SHA, corrected_exactly_one_constant=True, all_other_bytes_unchanged=True, no_unknown_hash_adoption=True, original_scripts_and_zip_retained=True, no_windows_or_server_access=True)) + print('source_sha256=' + sha(__file__)) + print('corrected_script_sha256=' + digest) + print('patch_sha256=' + sha(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1')) + print('patch=' + str((STATE / 'Create-VerifiedOriginalBootstrapFix.ps1').resolve())) + + +def main(): + os.umask(0o077) + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('build',));parser.add_argument('--actual-user-readonly',required=True,type=Path);args=parser.parse_args();build(args.actual_user_readonly) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/console_access_precision.py b/deploy/windows/console_access_precision.py new file mode 100644 index 0000000..1d25088 --- /dev/null +++ b/deploy/windows/console_access_precision.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""New public console package correcting only the old AccountExpires guard. + +Local only: reads the immutable completed server-only recovery case and its +public package, never contacts Windows/server and cannot change a server lease. +The same active server expiry/key/pins remain bound. The old package is retained. +""" +import argparse +import json +import os +from pathlib import Path +import uuid +import zipfile + +import console_access_recovery as original + +require, sha, save = original.require, original.sha, original.save +STATE = original.cb.EVIDENCE / 'dev-access-console-precision-correction' +PARENT_ID = '4b6506a7-6c3e-4cca-a497-618fa8666300' +PARENT_SOURCE_SHA = '703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053' +PARENT_INTENT_SHA = 'cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a' +PARENT_ENTER_SHA = '2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317' +PARENT_READBACK = 'readback-754e47df-25e0-4c0b-a411-56b3d350ace5.json' +PARENT_READBACK_SHA = 'f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787' +EXPIRY = '2026-11-15T13:05:58+00:00' +AUTHORIZED_SHA = 'fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2' +NAMES = ('Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt') + + +def replace_once(text, old, new): + require(text.count(old) == 1, 'one exact reviewed precision/provenance replacement') + return text.replace(old, new, 1) + + +def corrected_script(source, ident): + require(str(uuid.UUID(ident)) == ident, 'new canonical console UUID') + # The original cfg bytes/hash and its exact expiry string have already been + # verified before this line. Derive ONE full 64-bit FILETIME, no rounding, + # alternative value, tolerance or claim of a measured VM account value. + old = "$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}" + new = "$expectedOldAccountFiletime=[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc().ToString()\n$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$expectedOldAccountFiletime){throw 'Existing original expired account precision mismatch; stop for readonly inspection'}" + result = replace_once(source, old, new) + result = replace_once(result, "$recoveryId='" + PARENT_ID + "'", "$recoveryId='" + ident + "'") + result = replace_once(result, "@{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=", "@{id=$recoveryId;parent_server_case='" + PARENT_ID + "';parent_server_enter_sha256='" + PARENT_ENTER_SHA + "';new_expiry=$newExpiry;original_config_sha256=") + effect = '[IO.File]::Replace($candidate,$config,$nativeBackup)' + require(result.split(effect, 1)[1] == source.split(effect, 1)[1], 'all three mutation steps/start behavior unchanged') + require(result.count('Start-ScheduledTask -TaskName $taskName') == 1 and '134391345310000000' not in result, 'one original task start, no obsolete rounded guard') + return result + + +def parent(): + require(sha(original.__file__) == PARENT_SOURCE_SHA, 'immutable historical source, no rebase') + folder = original.STATE / PARENT_ID + require(sha(folder / 'intent.json') == PARENT_INTENT_SHA and sha(folder / 'server-entered.json') == PARENT_ENTER_SHA and sha(folder / PARENT_READBACK) == PARENT_READBACK_SHA, 'exact existing server-only CAS and independent readback') + intent = original.cb.contract.protected_json(folder / 'intent.json') + entered = original.cb.contract.protected_json(folder / 'server-entered.json') + readback = original.cb.contract.protected_json(folder / PARENT_READBACK) + require(intent['id'] == PARENT_ID and intent['source_sha256'] == PARENT_SOURCE_SHA and intent['payload']['new_expiry'] == EXPIRY and entered['completed'] is True and entered['authorized_sha256'] == readback['authorized_sha256'] == AUTHORIZED_SHA and entered['expiry'] == readback['expiry'] == '20261115130558Z' and readback['read_only'] is True and readback['completed'] is True, 'same already completed server lease; never a new CAS') + before = intent['payload']['server_before'] + require(all(readback[field] == before[field] for field in ('profile_sha256', 'effective_sha256', 'server_host_key_sha256', 'tunnel_public_key_sha256', 'uid', 'gid', 'home', 'shell')), 'original forwarding authority/key/profile/account unchanged') + for name, field in ((NAMES[0], 'console_sha256'), ('README.txt', 'readme_sha256'), ('public-recovery.json', 'public_json_sha256'), ('windows-dev-access-recovery.zip', 'bundle_sha256')): + require(sha(folder / name) == intent[field], 'immutable original public package files') + return folder, intent + + +def build(): + old_folder, old_intent = parent() + require(original.cb.contract.now() < original.dt.datetime.fromisoformat(EXPIRY), 'existing server lease still in its fixed window') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True) + save(folder / 'prepare-intent.json', dict(id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_server_enter_sha256=PARENT_ENTER_SHA, new_server_cas=False, no_windows_or_server_access=True)) + script = corrected_script((old_folder / NAMES[0]).read_text(), ident) + original.pair.write_bytes(folder / NAMES[0], script.encode()) + digest = original.pair.raw_sha(script.encode()) + public = dict(schema_version=1, id=ident, parent_server_case=PARENT_ID, parent_source_sha256=PARENT_SOURCE_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, new_expiry=EXPIRY, script_sha256=digest, no_private_keys=True, new_server_cas=False, old_account_guard='exact_derived_from_verified_config_utc_filetime', actual_vm_account_filetime_measured=False) + save(folder / 'public-recovery.json', public) + readme = (old_folder / 'README.txt').read_text() + require(old_intent['console_sha256'] in readme, 'original independent PS1 hash instructions') + readme = readme.replace(old_intent['console_sha256'], digest) + readme += ('\nPraezisionskorrektur: neues Konsolenpaket, neuer Fall ' + ident + '.\n' + 'Verwendet ausschliesslich den bereits bestaetigten Serverfall ' + PARENT_ID + ' und dieselbe UTC-Frist ' + EXPIRY + '. Keine neue Serververlaengerung.\n' + 'Der alte AccountExpires-Sollwert wird exakt aus der unveraenderten alten Config-UTC-Zeit einschliesslich Bruchteilen abgeleitet. Dies ist kein gemessener VM-Accountwert.\n' + 'Keine Rundung, Toleranz oder alternativer Sollwert. Bei Abweichung abbrechen und nur lesend pruefen lassen.\n' + 'Falls ein frueheres Paket bereits erfolgreich ausgefuehrt wurde: dieses Paket NICHT als Retry verwenden; der alte Config-Hashguard muss dann verweigern.\n') + original.pair.write_bytes(folder / 'README.txt', readme.encode()) + bundle = folder / 'windows-dev-access-recovery.zip' + with zipfile.ZipFile(bundle, 'x', compression=zipfile.ZIP_DEFLATED) as archive: + for name in NAMES: archive.write(folder / name, name) + bundle.chmod(0o600) + intent = dict(schema_version=1, id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_intent_sha256=PARENT_INTENT_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, original_bundle_sha256=old_intent['bundle_sha256'], new_expiry=EXPIRY, console_sha256=digest, public_json_sha256=sha(folder / 'public-recovery.json'), readme_sha256=sha(folder / 'README.txt'), bundle_sha256=sha(bundle), no_windows_or_server_access=True, new_server_cas=False) + save(folder / 'intent.json', intent) + print(json.dumps(dict(id=ident, intent_sha256=sha(folder / 'intent.json'), bundle=str(bundle.resolve()), bundle_sha256=intent['bundle_sha256'], console_source=str((folder / NAMES[0]).resolve()), console_sha256=digest, new_expiry=EXPIRY, parent_server_case=PARENT_ID, new_server_cas=False, no_windows_or_server_access=True))) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build() + + +if __name__ == '__main__': + try: main() + except Exception as error: print('CONSOLE_PRECISION_CORRECTION_INCOMPLETE:' + type(error).__name__); raise SystemExit(2) from None diff --git a/deploy/windows/console_access_recovery.py b/deploy/windows/console_access_recovery.py new file mode 100644 index 0000000..4f28cb0 --- /dev/null +++ b/deploy/windows/console_access_recovery.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Expired development tunnel recovery: server-only CAS + fixed public console code. + +No Windows access, key generation, SSH profile edit, port/download/RMM change. +Root renews the one expired restricted authorized key first, then hands the +reviewed public PowerShell to the User's elevated Windows console. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import inspect +import json +import os +from pathlib import Path +import subprocess +import uuid +import zipfile +import client_bootstrap as cb +import system_pipe_upgrade as pair +import dev_access_renewal as previous +require,sha,save=pair.require,pair.sha,pair.save +STATE=cb.EVIDENCE/'dev-access-console-recovery' +OLD_EXPIRY='2026-11-14T12:55:31.254999+00:00' + +def recover_server(payload): + import datetime as dt + import re + import stat + root=Path('/opt/rust-discovery/devstate/windows-bootstrap') + authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys') + profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf') + ident=str(uuid.UUID(payload['id']));case=root/('console-recovery-'+ident) + require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase') + def check(path,mode): + s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file') + def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest() + check(authorized,0o644);check(profile,0o644) + account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account') + public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2]) + fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1] + require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key') + raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw) + require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options') + effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout + for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile') + def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell) + if payload['phase']=='state':return state() + if payload['phase']=='readback': + value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value + old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc) + require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and olddt.datetime.fromisoformat(OLD_EXPIRY),'original lease actually expired') + ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True) + expiry=(cb.contract.now()+dt.timedelta(hours=24)).replace(microsecond=0) + console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json') + with zipfile.ZipFile(access.root/'devstate/windows-bootstrap/windows-dev-access.zip') as bundle: + original=bundle.read('bootstrap-public.json') + public=json.loads(original,object_pairs_hook=cb.contract.strict_object) + require(public['expires_at']==OLD_EXPIRY and public['server']=='discovery.ease-technologies.de','original public-only bundle') + payload=dict(id=ident,phase='state',old_expiry=OLD_EXPIRY,new_expiry=expiry.isoformat(),tunnel_public_key=console['tunnel_public_key']) + save(folder/'prepare-intent.json',dict(id=ident,source_sha256=sha(__file__),new_expiry=payload['new_expiry'],no_windows_access=True)) + baseline=access.rpc(payload);require(baseline['expiry']==dt.datetime.fromisoformat(OLD_EXPIRY).strftime('%Y%m%d%H%M%SZ'),'only original expired key') + payload['server_before']=baseline + script=CONSOLE + for key,value in {'ID':ident,'EXPIRY':payload['new_expiry'],'CONFIG':hashlib.sha256(original).hexdigest(),'BOOTSTRAP':sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'TUNNEL':console['tunnel_public_key'],'HOST':console['windows_host_public_key'],'FILETIME':str((int(expiry.timestamp())+11644473600)*10000000)}.items(): + token='@@'+key+'@@';require(script.count(token)==1,'exact fixed public console field');script=script.replace(token,value) + require('@@' not in script,'complete fixed public instructions') + pair.write_bytes(folder/'Recover-ExistingDevAccess.ps1',script.encode()) + save(folder/'public-recovery.json',dict(id=ident,new_expiry=payload['new_expiry'],script_sha256=pair.raw_sha(script.encode()),no_private_keys=True)) + readme=('Bestehenden Windows-Entwicklungszugang wiederherstellen\r\n\r\n' + 'Nur in dieser Windows-Test-VM ausfuehren, in einer als Administrator gestarteten PowerShell.\r\n' + 'Der Cloudserver muss zuvor durch den Entwickler fuer diese feste Frist erneuert worden sein.\r\n' + 'Neue UTC-Frist: '+payload['new_expiry']+'\r\n' + 'ZIP-SHA256 mit dem unabhaengig mitgeteilten Downloadhash vergleichen; dann hier entpacken.\r\n' + 'Folgende Befehle im entpackten Verzeichnis ausfuehren:\r\n\r\n' + "$recoveryScript = Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'\r\n" + "if ((Get-FileHash -LiteralPath $recoveryScript -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+pair.raw_sha(script.encode())+"') { throw 'Falsche Recoverydatei' }\r\n" + 'Unblock-File -LiteralPath $recoveryScript\r\n' + 'powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $recoveryScript\r\n\r\n' + 'Unblock-File betrifft nur diese exakt gepruefte heruntergeladene Datei; RemoteSigned nur diesen Bootstrapprozess.\r\n' + 'Keine globale Policy/GPO aendern. Falls eine Richtlinie oder Pruefung verweigert: stoppen, Fehlermeldung melden, nicht erneut ausfuehren.\r\n' + 'Das Skript behaelt Schluessel, Pins, SSH-Profil und Taskdefinition bei, erneuert nur die Ablaufzeit und startet den Originaltunnel einmal.\r\n' + 'Keine Installation, ACL-Reparatur, RMM-Aktion, Reboot oder Update. Private Schluessel werden nicht gelesen/ausgegeben.\r\n' + 'Nach Erfolg bitte nur die Abschlusszeile melden, keine Schluessel oder Zugangsdaten. Bei Fehler den Zustand fuer lesende Kontrolle behalten.\r\n') + pair.write_bytes(folder/'README.txt',readme.encode('utf-8')) + bundle=folder/'windows-dev-access-recovery.zip' + with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive: + for name in ('Recover-ExistingDevAccess.ps1','public-recovery.json','README.txt'): + archive.write(folder/name,name) + bundle.chmod(0o600) + intent=dict(id=ident,source_sha256=sha(__file__),access_root=str(access.root),payload=payload,console_sha256=pair.raw_sha(script.encode()),bundle_sha256=sha(bundle),readme_sha256=sha(folder/'README.txt'),public_json_sha256=sha(folder/'public-recovery.json')) + save(folder/'intent.json',intent) + print(json.dumps(dict(id=ident,review_sha256=sha(folder/'intent.json'),console_source=str((folder/'Recover-ExistingDevAccess.ps1').resolve()),console_sha256=intent['console_sha256'],bundle=str(bundle.resolve()),bundle_sha256=sha(bundle),new_expiry=payload['new_expiry'],windows_not_accessed=True))) + + +def run(access,ident,phase,review_sha): + require(str(uuid.UUID(ident))==ident,'canonical original recovery');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json') + require(intent['source_sha256']==sha(__file__) and intent['access_root']==str(access.root) and sha(folder/'Recover-ExistingDevAccess.ps1')==intent['console_sha256'] and sha(folder/'windows-dev-access-recovery.zip')==intent['bundle_sha256'] and sha(folder/'README.txt')==intent['readme_sha256'] and sha(folder/'public-recovery.json')==intent['public_json_sha256'],'same immutable console recovery source/public package') + if phase=='server-enter': + require(review_sha==sha(folder/'intent.json'),'explicit reviewed server-only CAS');save(folder/'server-enter-intent.json',dict(once=True)) + payload=dict(intent['payload'],phase='enter' if phase=='server-enter' else 'readback') + result=access.rpc(payload);save(folder/('server-entered.json' if phase=='server-enter' else 'readback-'+str(uuid.uuid4())+'.json'),result) + print(json.dumps(dict(id=ident,result=result,windows_not_accessed=True,console_handoff_allowed=result.get('completed') is True))) + + +def main(): + os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','server-enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=ServerAccess(args.access_root) + if args.phase=='prepare':require(not(args.id or args.review_sha256),'fresh server-only preparation');prepare(access) + else:require(args.id and ((args.phase=='server-enter')==bool(args.review_sha256)),'same case, reviewed CAS once');run(access,args.id,args.phase,args.review_sha256) + + +if __name__=='__main__': + try:main() + except Exception as error:print('CONSOLE_ACCESS_RECOVERY_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None diff --git a/deploy/windows/dev_access_renewal.py b/deploy/windows/dev_access_renewal.py new file mode 100644 index 0000000..53dd070 --- /dev/null +++ b/deploy/windows/dev_access_renewal.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""One 24h renewal of the existing restricted development SSH transport. + +No new key, port, shell, RMM setting, download lease, stop/kill or reboot. +The unchanged tunnel expires naturally; one SYSTEM worker starts its original +scheduled task at original expiry+60s. This deliberately permits a short gap. +Lost mutation replies allow readback only. Main config publication is Root work. +""" +import argparse +import base64 +import datetime as dt +import inspect +import json +import os +from pathlib import Path +import subprocess +import uuid + +import client_bootstrap as cb +import system_pipe_upgrade as pair + +require, sha, canonical, save = pair.require, pair.sha, pair.canonical, pair.save +STATE = cb.EVIDENCE / 'dev-access-renewal' +OLD_EXPIRY = '2026-11-14T12:55:31.254999+00:00' +OLD_UTC = dt.datetime.fromisoformat(OLD_EXPIRY) +NEW_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(hours=24) +START_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(seconds=60) + + +def server(payload): + import datetime as dt + import re + import stat + root=Path('/opt/rust-discovery/devstate/windows-bootstrap') + authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys') + profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf') + ident=str(uuid.UUID(payload['id']));case=root/('renew-'+ident) + require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase') + def check(path,mode): + s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file') + def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest() + check(authorized,0o644);check(profile,0o644) + account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account') + public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2]) + fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1] + require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key') + raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw) + require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options') + effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout + for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile') + def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell) + if payload['phase']=='state':return state() + if payload['phase']=='readback': + value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value + old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc) + require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and new==old.replace(microsecond=0)+dt.timedelta(hours=24) and dt.datetime.now(dt.timezone.utc)0&&bytes.ToUInt64()<65536,"ATTRIBUTE_SIZE"); + attrs=Marshal.AllocHGlobal((int)bytes.ToUInt64());Need(InitializeProcThreadAttributeList(attrs,2,0,ref bytes),"ATTRIBUTE_INIT");initialized=true; + jobValue=Marshal.AllocHGlobal(IntPtr.Size);Marshal.WriteIntPtr(jobValue,job);Need(UpdateProcThreadAttribute(attrs,0,new UIntPtr(0x2000d),jobValue,new UIntPtr((uint)IntPtr.Size),IntPtr.Zero,IntPtr.Zero),"ATOMIC_JOB_LIST"); + handleValue=Marshal.AllocHGlobal(3*IntPtr.Size);Marshal.WriteIntPtr(handleValue,0,input);Marshal.WriteIntPtr(handleValue,IntPtr.Size,output);Marshal.WriteIntPtr(handleValue,2*IntPtr.Size,error); + Need(UpdateProcThreadAttribute(attrs,0,new UIntPtr(0x20002),handleValue,new UIntPtr((uint)(3*IntPtr.Size)),IntPtr.Zero,IntPtr.Zero),"HANDLE_LIST"); + SIX si=new SIX();si.si.cb=(uint)Marshal.SizeOf(typeof(SIX));si.attrs=attrs;si.si.flags=0x100;si.si.input=input;si.si.output=output;si.si.error=error; + string exe=Path.Combine(folder,"input","midl.exe"); + var cmd=new StringBuilder("\""+exe+"\" /nologo /no_cpp /env amd64 /Oicf /robust /Zp8 /protocol dce /client stub /server none /h w32time.h /cstub w32time_c.c \""+Path.Combine(folder,"input","w32time.idl")+"\""); + Need(CreateProcessW(exe,cmd,IntPtr.Zero,IntPtr.Zero,true,0x80000|0x8000000|4,IntPtr.Zero,Path.Combine(folder,"output"),ref si,out pi),"CODEGEN_CREATE"); + bool member;Need(IsProcessInJob(pi.process,job,out member)&&member,"ATOMIC_JOB_MEMBERSHIP");Need(ResumeThread(pi.thread)!=0xffffffff,"CODEGEN_RESUME"); + Result result=new Result();result.pid=pi.pid;result.atomic_job_assignment=true; + var began=System.Diagnostics.Stopwatch.StartNew(); + while(true){ + uint waited=WaitForSingleObject(pi.process,25);Need(waited==0||waited==258,"CODEGEN_WAIT"); + foreach(string path in new[]{Path.Combine(folder,"stdout.txt"),Path.Combine(folder,"stderr.txt"),Path.Combine(folder,"output","w32time.h"),Path.Combine(folder,"output","w32time_c.c")})if(File.Exists(path)&&new FileInfo(path).Length>262144)result.output_exceeded=true; + if(waited==0)break; + if(began.ElapsedMilliseconds>=10000||result.output_exceeded){result.timed_out=began.ElapsedMilliseconds>=10000;Need(TerminateJobObject(job,0xdead),"OWN_JOB_TERMINATE");break;} + } + // One total two-second observation budget, not one timeout per child. + var closing=System.Diagnostics.Stopwatch.StartNew();ACCOUNT account; + do{Need(QueryInformationJobObject(job,1,out account,(uint)Marshal.SizeOf(typeof(ACCOUNT)),IntPtr.Zero),"JOB_ACCOUNTING");if(account.active==0)break;System.Threading.Thread.Sleep(25);}while(closing.ElapsedMilliseconds<2000); + result.active_processes=account.active;result.all_own_children_exited=account.active==0; + Need(GetExitCodeProcess(pi.process,out result.exit_code),"CODEGEN_EXIT_CODE");return result; + }finally{ + // Closing only this unnamed job kills any remaining own compiler child. + if(job!=IntPtr.Zero)CloseHandle(job); + if(pi.thread!=IntPtr.Zero)CloseHandle(pi.thread);if(pi.process!=IntPtr.Zero)CloseHandle(pi.process); + if(initialized)DeleteProcThreadAttributeList(attrs);if(attrs!=IntPtr.Zero)Marshal.FreeHGlobal(attrs);if(jobValue!=IntPtr.Zero)Marshal.FreeHGlobal(jobValue);if(handleValue!=IntPtr.Zero)Marshal.FreeHGlobal(handleValue); + foreach(var h in new[]{input,output,error})if(h!=IntPtr.Zero&&h!=new IntPtr(-1))CloseHandle(h); + } + } +} +''' + +SCRIPT = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if([guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('prepare','admit','start','readback')){throw 'Fixed codegen case'} +foreach($n in @('runner_sha256','script_sha256')){if($p.$n-notmatch'^[a-f0-9]{64}$'){throw 'Source binding'}} +$root='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $root ('midl-codegen-'+$p.id) +$inputsDir=Join-Path $folder 'input';$output=Join-Path $folder 'output' +$pins=@(@('midl.exe','7a2a717be64f755390ad8b04cb034549b2606acec646ec7cbe44c67516ccba83',154048),@('midlc.exe','34293d7bd256f2d43311d197f13bbb8a1ae26c92cc1605d9f35dd3ddfe264b65',1366464),@('w32time.idl','37da4acb622daf9acf1aa6f1218ff9f52e5a2def14e58d8d9dd8da65078b3c6c',2004)) +function Check($path,[bool]$directory){ + $item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Codegen regular private path'} + $parent=$item.Parent;if(!$directory){$parent=$item.Directory};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Codegen ancestor reparse'};$parent=$parent.Parent} + $a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$a.Access.Count){throw 'Codegen private owner'} + foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or[int64]$r.FileSystemRights-ne2032127){throw 'Codegen exact controller ACL'}} +} +function Protect($path){$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));foreach($sid in @('S-1-5-18','S-1-5-32-544')){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $path -AclObject $a;Check $path $true} +function NewRecord($name,$value){$path=Join-Path $folder $name;$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};Check $path $false} +function Hash($path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +function Intent{ + Check $folder $true;Check $inputsDir $true;Check $output $true;Check (Join-Path $folder 'intent.json') $false + $i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json + if($i.id-cne$p.id-or$i.runner_sha256-cne$p.runner_sha256-or$i.script_sha256-cne$p.script_sha256){throw 'Immutable codegen intent'} +} +function VerifyInputs{ + $info=@();foreach($pin in $pins){$path=Join-Path $inputsDir $pin[0];Check $path $false;if((Get-Item -LiteralPath $path).Length-ne$pin[2]-or(Hash $path)-cne$pin[1]){throw 'Fixed codegen input bytes'} + if($pin[0]-like'*.exe'){ + $sig=Get-AuthenticodeSignature -LiteralPath $path;if($sig.Status-ne'Valid'-or!$sig.SignerCertificate-or$sig.SignerCertificate.Subject-notmatch'(^|,\s*)O=Microsoft Corporation(,|$)'){throw 'Valid Microsoft Authenticode required'} + $chain=New-Object Security.Cryptography.X509Certificates.X509Chain;try{$chain.ChainPolicy.RevocationMode='Online';$chain.ChainPolicy.RevocationFlag='ExcludeRoot';$chain.ChainPolicy.VerificationFlags='NoFlag';$chain.ChainPolicy.UrlRetrievalTimeout=[TimeSpan]::FromSeconds(2);if(!$chain.Build($sig.SignerCertificate)){throw 'Microsoft chain validation required'}}finally{$chain.Dispose()} + $v=(Get-Item -LiteralPath $path).VersionInfo;if($v.FileMajorPart-ne8-or$v.FileMinorPart-ne1-or$v.FileBuildPart-ne628-or$v.FilePrivatePart-ne1){throw 'Exact pinned compiler version'} + $info+=,[ordered]@{name=$pin[0];sha256=$pin[1];authenticode_status='Valid';signer_thumbprint=$sig.SignerCertificate.Thumbprint;chain_valid=$true;file_version='8.1.628.1'} + } + };return ,$info +} +Check $root $true +if($p.action-ceq'prepare'){ + if(Test-Path -LiteralPath $folder){throw 'Existing case: readback only'} + New-Item -ItemType Directory -Path $folder|Out-Null;Protect $folder + foreach($path in @($inputsDir,$output)){New-Item -ItemType Directory -Path $path|Out-Null;Protect $path} + NewRecord 'intent.json' @{id=$p.id;runner_sha256=$p.runner_sha256;script_sha256=$p.script_sha256;inputs=$pins;no_jobs=$true;no_rpc=$true;no_installation=$true} + @{prepared=$true;id=$p.id;tool_executed=$false}|ConvertTo-Json -Compress;return +} +Intent +if($p.action-ceq'admit'){$tools=VerifyInputs;NewRecord 'admitted.json' @{id=$p.id;tools=$tools;source_sha256=$pins[2][1];tool_executed=$false};@{admitted=$true;id=$p.id;tools=$tools;tool_executed=$false}|ConvertTo-Json -Depth 8 -Compress;return} +if($p.action-ceq'readback'){ + $report=$null;$reportPath=Join-Path $folder 'result.json';if(Test-Path -LiteralPath $reportPath){Check $reportPath $false;$report=Get-Content -LiteralPath $reportPath -Raw|ConvertFrom-Json} + $files=@();foreach($pair in @(@('stdout.txt',$folder),@('stderr.txt',$folder),@('w32time.h',$output),@('w32time_c.c',$output))){$path=Join-Path $pair[1] $pair[0];if(Test-Path -LiteralPath $path){Check $path $false;$size=(Get-Item -LiteralPath $path).Length;if($size-gt262144){throw 'Codegen output bound'};$files+=,@{name=$pair[0];bytes=$size;sha256=(Hash $path);base64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}} + @{id=$p.id;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $folder 'started.json'));result=$report;files=$files}|ConvertTo-Json -Depth 16 -Compress;return +} +if(Test-Path -LiteralPath (Join-Path $folder 'started.json')){throw 'No compiler restart: readback only'} +Check (Join-Path $folder 'admitted.json') $false +$tools=VerifyInputs +$held=@();try{ + foreach($pin in $pins){$held+=,[IO.File]::Open((Join-Path $inputsDir $pin[0]),'Open','Read','Read')} + $null=VerifyInputs + Add-Type -TypeDefinition @' +__CS__ +'@ + NewRecord 'started.json' @{id=$p.id;single_start_reserved=$true;atomic_job_list_required=$true;no_rpc=$true;no_jobs=$true} + $run=$null + try{$run=[RmmMidlJob]::Run($folder);$ok=($run.exit_code-eq0-and!$run.timed_out-and!$run.output_exceeded-and$run.all_own_children_exited) + foreach($name in @('w32time.h','w32time_c.c')){$path=Join-Path $output $name;Check $path $false;if((Get-Item -LiteralPath $path).Length-gt262144){$ok=$false}} + $other=@(Get-ChildItem -LiteralPath $output -Force|Where-Object{$_.Name-notin@('w32time.h','w32time_c.c')});if($other.Count){$ok=$false} + NewRecord 'result.json' @{id=$p.id;complete=$ok;run=$run;tools=$tools;no_jobs=$true;no_rpc=$true;no_installation=$true;clock_qualified=$false} + }catch{NewRecord 'result.json' @{id=$p.id;complete=$false;run=$run;error_class=$_.Exception.GetType().Name;error_line=$_.InvocationInfo.ScriptLineNumber;no_retry=$true;clock_qualified=$false};throw} + @{id=$p.id;complete=$ok;tool_executed=$true;clock_qualified=$false}|ConvertTo-Json -Compress +}finally{foreach($f in $held){$f.Dispose()}} +'''.replace('__CS__', CS) + + +STAGE = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if($p.sha256-notmatch'^[a-f0-9]{64}$'-or$p.bytes-le0-or$p.bytes-gt32768){throw 'Fixed codegen source'} +$root='C:\ProgramData\RustDiscoveryBootstrap' +function Check($path,[bool]$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular controller source'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$a.Access.Count){throw 'Source owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or[int64]$r.FileSystemRights-ne2032127){throw 'Source controller ACL'}}} +Check $root $true +$dir=Join-Path $root $p.sha256;if(!(Test-Path -LiteralPath $dir)){New-Item -ItemType Directory -Path $dir|Out-Null};Check $dir $true +$path=Join-Path $dir 'MidlCodegen.ps1';$exists=Test-Path -LiteralPath $path +if($exists){Check $path $false;if((Get-Item -LiteralPath $path).Length-ne$p.bytes-or(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.sha256){throw 'Immutable codegen source'}} +@{already_uploaded=$exists}|ConvertTo-Json -Compress +''' +LAUNCH = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if($p.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed codegen source hash'} +$file='C:\ProgramData\RustDiscoveryBootstrap\'+$p.script_sha256+'\MidlCodegen.ps1' +$i=Get-Item -LiteralPath $file -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Immutable codegen source file'} +$json=$p|ConvertTo-Json -Depth 8 -Compress +$raw=$json|& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $file +if($LASTEXITCODE-ne0){throw 'Exact codegen phase failed; retain case and readback only'} +$raw +''' + + +def upload(cb, local, remote, folder, label): + prefix=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix'] + batch='put '+json.dumps(str(local.resolve()))+' '+json.dumps(remote)+'\n' + result=subprocess.run(['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]],input=batch.encode(),capture_output=True,timeout=40) + save(folder,label+'.transfer.json',{'returncode':result.returncode,'stdout_sha256':hashlib.sha256(result.stdout).hexdigest(),'stderr_sha256':hashlib.sha256(result.stderr).hexdigest()}) + if result.returncode:raise RuntimeError('EXACT_CODEGEN_UPLOAD_FAILED_READBACK_ONLY') + + +def stage_source(cb, folder, source, digest): + meta={'sha256':digest,'bytes':source.stat().st_size} + state=cb.powershell(STAGE,meta,timeout=40,remote_signed=True) + if not state['already_uploaded']: + upload(cb,source,'/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/MidlCodegen.ps1',folder,'source') + if not cb.powershell(STAGE,meta,timeout=40,remote_signed=True)['already_uploaded']:raise RuntimeError('EXACT_SOURCE_READBACK_FAILED') + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def save(folder, name, value): + fd = os.open(folder/name, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as out: + json.dump(value, out, indent=2);out.flush();os.fsync(out.fileno()) + + +def transport(access_root): + if access_root.resolve() != ACCESS: + raise RuntimeError('EXACT_EXISTING_ACCESS_ROOT_REQUIRED') + sys.path.insert(0, str(ACCESS/'deploy/windows')) + return importlib.import_module('client_bootstrap') + + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('prepare','start','readback'));p.add_argument('--id');p.add_argument('--access-root',type=Path,default=ACCESS);a=p.parse_args() + os.umask(0o077);cb=transport(a.access_root) + script_sha=hashlib.sha256(SCRIPT.encode()).hexdigest();runner_sha=sha(__file__) + if a.action=='prepare': + if a.id:raise RuntimeError('FRESH_CREATE_ONLY_CASE_REQUIRED') + local={'midl.exe':TOOLS/'midl.exe','midlc.exe':TOOLS/'midlc.exe','w32time.idl':IDL} + for name,path in local.items(): + if path.is_symlink() or not path.is_file() or (sha(path),path.stat().st_size)!=PINS[name]:raise RuntimeError('EXACT_FIXED_INPUTS_REQUIRED') + STATE.mkdir(parents=True,exist_ok=True,mode=0o700);folder=STATE/str(uuid.uuid4());folder.mkdir(mode=0o700) + payload={'id':folder.name,'runner_sha256':runner_sha,'script_sha256':script_sha} + save(folder,'intent.json',{'payload':payload,'inputs':PINS,'transport_sha256':sha(cb.__file__),'no_rpc':True,'no_jobs':True}) + save(folder,'prepare-attempt.json',{'once':True}) + source=folder/'MidlCodegen.ps1' + with source.open('xb') as out:out.write(SCRIPT.encode());out.flush();os.fsync(out.fileno()) + stage_source(cb,folder,source,script_sha) + result=cb.powershell(LAUNCH,dict(payload,action='prepare'),timeout=40,remote_signed=True);save(folder,'remote-prepared.json',result) + for name,path in local.items(): + upload(cb,path,'/C:/ProgramData/RustDiscoveryBootstrap/midl-codegen-'+folder.name+'/input/'+name,folder,name) + admitted=cb.powershell(LAUNCH,dict(payload,action='admit'),timeout=60,remote_signed=True);save(folder,'admitted.json',admitted) + print(json.dumps({'case_id':folder.name,'prepared':True,'tool_executed':False}));return + if not a.id or str(uuid.UUID(a.id))!=a.id:raise RuntimeError('EXACT_EXISTING_CASE_REQUIRED') + folder=STATE/a.id;intent=cb.contract.protected_json(folder/'intent.json');payload=intent['payload'] + if payload['id']!=a.id or payload['runner_sha256']!=runner_sha or payload['script_sha256']!=script_sha or intent['transport_sha256']!=sha(cb.__file__):raise RuntimeError('IMMUTABLE_RUNNER_AND_TRANSPORT_REQUIRED') + if a.action=='start': + cb.contract.protected_json(folder/'admitted.json');save(folder,'start-attempt.json',{'once':True,'lost_reply_readback_only':True}) + result=cb.powershell(LAUNCH,dict(payload,action=a.action),timeout=60,remote_signed=True) + save(folder,('start-result.json' if a.action=='start' else 'readback-'+str(uuid.uuid4())+'.json'),result) + if a.action=='readback': + for item in result['files']: + import base64 + if item['name'] not in ('stdout.txt','stderr.txt','w32time.h','w32time_c.c'):raise RuntimeError('FIXED_OUTPUT_NAME_REQUIRED') + raw=base64.b64decode(item['base64'],validate=True) + if len(raw)>262144 or len(raw)!=item['bytes'] or hashlib.sha256(raw).hexdigest()!=item['sha256']:raise RuntimeError('EXACT_OUTPUT_BYTES_REQUIRED') + dest=folder/('native-'+item['name']) + if dest.exists(): + if sha(dest)!=item['sha256']:raise RuntimeError('RETAINED_OUTPUT_CHANGED') + else: + with dest.open('xb') as out:out.write(raw);out.flush();os.fsync(out.fileno()) + report=result.get('result') or result + print(json.dumps({'case_id':a.id,'complete':report.get('complete',False),'readback_only':a.action=='readback','clock_qualified':False})) + +if __name__=='__main__':main() diff --git a/deploy/windows/publish_precision_recovery.py b/deploy/windows/publish_precision_recovery.py new file mode 100644 index 0000000..856f2de --- /dev/null +++ b/deploy/windows/publish_precision_recovery.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Replace the withdrawn public recovery ZIP; preserve all previous evidence. + +Same existing TLS bootstrap service and port, one new URL and 45 minute limit. +No SSH, RMM, certificate, key, account or Windows changes in this publisher. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import inspect +import json +import os +from pathlib import Path +import ssl +import sys +import urllib.request +import uuid +import zipfile +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import remote_client_bootstrap as transport + +STATE = transport.ROOT / 'devstate/windows-precision-publication' + + +def server(p): + import datetime as dt + import stat + cfg = Path('/etc/rmm-bootstrap-download.json') + code = Path('/usr/local/libexec/rmm-bootstrap-public.py') + archive = Path('/srv/rmm-bootstrap-download/windows-dev-access-recovery.zip') + old_timer = 'rmm-recovery-download-close-7f549bc4-cf12-4292-aae6-377ac9ecb2d4' + history = Path('/opt/rmm-bootstrap-download') / ('precision-' + str(uuid.UUID(p['id']))) + def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() + def run(args): return subprocess.run(args, capture_output=True, check=True, timeout=30).stdout + def safe(path, mode): + s = path.lstat() + require(stat.S_ISREG(s.st_mode) and s.st_uid == 0 and stat.S_IMODE(s.st_mode) == mode and not path.is_symlink(), 'protected existing download file') + safe(cfg, 0o644); safe(code, 0o755); safe(archive, 0o644) + def snapshot(): + return dict(config_sha256=digest(cfg), code_sha256=digest(code), archive_sha256=digest(archive), + service_state=run(['systemctl', 'show', 'rmm-bootstrap-download.service', '-p', 'ActiveState', '--value']).decode().strip()) + if p['action'] == 'readback': + return dict(snapshot=snapshot(), history_present=history.exists(), completed=(history / 'completed.json').exists()) + before = snapshot() + require(before == dict(config_sha256='1aa119f0355754e2ba054e6e1c4276f484c1287750cb853dd73bffe552ef8f93', + code_sha256='b4f85778dd356377b95e04d6736b3fb6f4e272a276a9466f28efeaccd6ef1b7d', + archive_sha256='7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7', + service_state='inactive'), 'only exact withdrawn original publication') + service = '[Unit]\nDescription=Close temporary public recovery download\n[Service]\nType=oneshot\nExecStart=/usr/bin/systemctl stop rmm-bootstrap-download.service\nExecStart=/usr/sbin/ufw delete allow proto tcp from 0.0.0.0/0 to any port 8443\nNoNewPrivileges=true\n' + original_timer = '[Unit]\nDescription=Expire public recovery download\n[Timer]\nOnCalendar=2026-11-14 13:53:24 UTC\nPersistent=true\nUnit=' + old_timer + '.service\n[Install]\nWantedBy=timers.target\n' + for suffix, expected in (('.service', service), ('.timer', original_timer)): + path = Path('/etc/systemd/system') / (old_timer + suffix) + safe(path, 0o644); require(path.read_text() == expected, 'only original download close timer may be superseded') + run(['openssl', 'x509', '-in', '/opt/rmm-bootstrap-download/chain.pem', '-noout', '-checkhost', 'discovery.ease-technologies.de', '-checkend', '3600']) + run(['openssl', 'verify', '-CAfile', '/etc/ssl/certs/ca-certificates.crt', '-untrusted', '/opt/rmm-bootstrap-download/chain.pem', '/opt/rmm-bootstrap-download/chain.pem']) + if p['action'] == 'prepare': return before + require(p['action'] == 'publish' and before == p['before'], 'same independently reviewed original generation') + expiry = dt.datetime.fromisoformat(p['expires_at']) + require(dt.datetime.now(dt.timezone.utc) < expiry <= dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45), 'new download limited to 45 minutes') + require(not history.exists(), 'existing precision publication: readback only') + raw = base64.b64decode(p['bundle'], validate=True) + require(len(raw) < 262144 and hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'exact corrected public archive') + history.mkdir(mode=0o700) + def write(path, data, 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 out: + out.write(data); out.flush(); os.fsync(out.fileno()); os.fchmod(out.fileno(), mode) + write(history / 'intent.json', json.dumps({k: v for k, v in p.items() if k != 'bundle'}).encode()) + write(history / 'original-config.json', cfg.read_bytes()) + write(history / 'original-recovery.zip', archive.read_bytes()) + next_cfg = cfg.parent / ('rmm-precision-' + p['id'] + '.next') + next_zip = archive.parent / ('rmm-precision-' + p['id'] + '.next') + write(next_cfg, json.dumps(dict(url_path=p['url_path'], expires_at=p['expires_at'], public_files={p['url_path']: archive.name})).encode(), 0o644) + write(next_zip, raw, 0o644) + name = 'rmm-precision-download-close-' + p['id'] + timer = '[Unit]\nDescription=Expire corrected public recovery download\n[Timer]\nOnCalendar=' + expiry.strftime('%Y-%m-%d %H:%M:%S UTC') + '\nPersistent=true\nUnit=' + name + '.service\n[Install]\nWantedBy=timers.target\n' + for suffix, data in (('.service', service), ('.timer', timer)): + unit = Path('/etc/systemd/system') / (name + suffix) + write(unit, data.encode(), 0o644); run(['systemd-analyze', 'verify', str(unit)]) + require(snapshot() == before, 'immediate config/code/archive CAS while download is stopped') + write(history / 'replace-intent.json', b'{"once":true}') + os.replace(next_zip, archive); os.replace(next_cfg, cfg) + require(digest(archive) == p['bundle_sha256'] and digest(code) == before['code_sha256'], 'corrected ZIP and unchanged server code') + run(['systemctl', 'daemon-reload']) + run(['systemctl', 'enable', '--now', name + '.timer']) + write(history / 'supersede-old-timer-intent.json', json.dumps(dict(timer=old_timer + '.timer')).encode()) + run(['systemctl', 'disable', '--now', old_timer + '.timer']) + write(history / 'start-intent.json', b'{"once":true}') + run(['ufw', 'allow', 'proto', 'tcp', 'from', '0.0.0.0/0', 'to', 'any', 'port', '8443']) + run(['systemctl', 'start', 'rmm-bootstrap-download.service']) + result = dict(published=True, expires_at=p['expires_at'], bundle_sha256=digest(archive), snapshot=snapshot(), close_timer=name + '.timer', old_timer_superseded=old_timer + '.timer', rmm_deployment_changed=False, ssh_expiry_changed=False, private_keys_read=False) + write(history / 'completed.json', json.dumps(result).encode()) + return result + + +def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def save(path, value): + with path.open('x') as out: + json.dump(value, out, indent=2); out.flush(); os.fsync(out.fileno()) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare', 'publish', 'readback')) + parser.add_argument('--bundle', type=Path); parser.add_argument('--id'); parser.add_argument('--review-sha256') + args = parser.parse_args() + if args.action == 'prepare': + transport.require(args.bundle and not args.id and not args.review_sha256, 'new corrected public package') + with zipfile.ZipFile(args.bundle) as z: + transport.require(len(z.namelist()) == 3 and set(z.namelist()) == {'Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt'} and all(i.file_size < 65536 for i in z.infolist()), 'only three public recovery files') + public = json.loads(z.read('public-recovery.json')) + transport.require(public['no_private_keys'] is True and hashlib.sha256(z.read('Recover-ExistingDevAccess.ps1')).hexdigest() == public['script_sha256'], 'bound corrected public script') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(parents=True, mode=0o700) + p = dict(id=ident, expires_at=(dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45)).replace(microsecond=0).isoformat(), url_path='/windows/' + uuid.uuid4().hex + '/windows-dev-access-recovery.zip', bundle_sha256=sha(args.bundle), bundle=base64.b64encode(args.bundle.read_bytes()).decode()) + before = transport.rpc('server.conf', server, dict(p, action='prepare')) + save(folder / 'intent.json', dict(source_sha256=sha(__file__), bundle_path=str(args.bundle.resolve()), payload=dict(p, before=before))) + print(json.dumps(dict(id=ident, prepared=True, review_sha256=sha(folder / 'intent.json')))); return + transport.require(args.id and str(uuid.UUID(args.id)) == args.id, 'same canonical precision publication case') + folder = STATE / args.id; intent = json.loads((folder / 'intent.json').read_text()); p = intent['payload'] + transport.require(intent['source_sha256'] == sha(__file__) and sha(intent['bundle_path']) == p['bundle_sha256'], 'same reviewed source and corrected package') + if args.action == 'publish': + transport.require(args.review_sha256 == sha(folder / 'intent.json'), 'reviewed publication intent') + save(folder / 'publish-attempt.json', dict(once=True, lost_reply_readback_only=True)) + result = transport.rpc('server.conf', server, dict(p, action=args.action)) + save(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), result) + if args.action == 'publish': + transport.require(result.get('published') is True, 'corrected publication completed') + url = 'https://discovery.ease-technologies.de:8443' + p['url_path'] + with urllib.request.urlopen(url, context=ssl.create_default_context(), timeout=15) as response: raw = response.read(262145) + transport.require(hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'external normal TLS and exact corrected ZIP') + save(folder / 'external-verified.json', dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True)) + print(json.dumps(dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True))); return + print(json.dumps(result)) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/publish_recovery_download.py b/deploy/windows/publish_recovery_download.py new file mode 100644 index 0000000..5aa9d66 --- /dev/null +++ b/deploy/windows/publish_recovery_download.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Republish one public recovery ZIP for 45 minutes using existing bootstrap TLS. + +The expired original downloads remain unavailable. No ACME, port80, RMM +deployment, SSH key or production TLS change. Lost replies use readback only. +""" +import argparse +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import ssl +import sys +import urllib.request +import uuid +import zipfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import remote_client_bootstrap as transport + +ROOT = transport.ROOT +STATE = ROOT / 'devstate/windows-recovery-publication' + + +def server(p): + import datetime as dt + import stat + cfg = Path('/etc/rmm-bootstrap-download.json') + code = Path('/usr/local/libexec/rmm-bootstrap-public.py') + history = Path('/opt/rmm-bootstrap-download') / ('recovery-' + str(uuid.UUID(p['id']))) + def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() + def run(args): return subprocess.run(args, capture_output=True, check=True, timeout=30).stdout + def safe(path, mode): + s = path.lstat() + require(stat.S_ISREG(s.st_mode) and s.st_uid == 0 and stat.S_IMODE(s.st_mode) == mode and not path.is_symlink(), 'existing protected download file') + safe(cfg, 0o644); safe(code, 0o755) + def snapshot(): + return dict(config_sha256=digest(cfg), code_sha256=digest(code), + service_state=run(['systemctl', 'show', 'rmm-bootstrap-download.service', '-p', 'ActiveState', '--value']).decode().strip()) + if p['action'] == 'readback': + return dict(snapshot=snapshot(), history_present=history.exists(), completed=(history / 'completed.json').exists()) + before = snapshot() + if p['action'] == 'prepare': + require(before['service_state'] == 'inactive', 'expired original download must be inactive') + require(dt.datetime.fromisoformat(json.loads(cfg.read_text())['expires_at']) < dt.datetime.now(dt.timezone.utc), 'original download expired') + require(before['code_sha256'] == p['old_code_sha256'], 'known reviewed original download server') + run(['openssl', 'x509', '-in', '/opt/rmm-bootstrap-download/chain.pem', '-noout', '-checkhost', 'discovery.ease-technologies.de', '-checkend', '3600']) + run(['openssl', 'verify', '-CAfile', '/etc/ssl/certs/ca-certificates.crt', '-untrusted', '/opt/rmm-bootstrap-download/chain.pem', '/opt/rmm-bootstrap-download/chain.pem']) + return before + require(p['action'] == 'publish' and before == p['before'] and before['service_state'] == 'inactive', 'same reviewed inactive download generation') + expiry = dt.datetime.fromisoformat(p['expires_at']) + require(dt.datetime.now(dt.timezone.utc) < expiry <= dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45), 'bounded new 45 minute download') + require(not history.exists(), 'existing publication: readback only') + raw = base64.b64decode(p['bundle'], validate=True) + require(len(raw) < 262144 and hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'exact public recovery archive') + old_code = code.read_bytes() + old = b"('windows-dev-access.zip','windows-dev-repair.zip')" + new = b"('windows-dev-access.zip','windows-dev-repair.zip','windows-dev-access-recovery.zip')" + require(old_code.count(old) == 1 and digest(code) == p['old_code_sha256'], 'one additional fixed recovery filename only') + history.mkdir(mode=0o700) + def write(path, data, mode): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode) + with os.fdopen(fd, 'wb') as out: + out.write(data); out.flush(); os.fsync(out.fileno()); os.fchmod(out.fileno(), mode) + write(history / 'intent.json', json.dumps({k: v for k, v in p.items() if k != 'bundle'}).encode(), 0o600) + write(history / 'original-server.py', old_code, 0o600) + write(history / 'original-config.json', cfg.read_bytes(), 0o600) + archive = Path('/srv/rmm-bootstrap-download/windows-dev-access-recovery.zip') + write(archive, raw, 0o644) + next_cfg = cfg.parent / ('rmm-bootstrap-recovery-' + p['id'] + '.next') + next_code = code.parent / ('rmm-bootstrap-recovery-' + p['id'] + '.next') + write(next_cfg, json.dumps(dict(url_path=p['url_path'], expires_at=p['expires_at'], public_files={p['url_path']: archive.name})).encode(), 0o644) + write(next_code, old_code.replace(old, new), 0o755) + name = 'rmm-recovery-download-close-' + p['id'] + service = '[Unit]\nDescription=Close temporary public recovery download\n[Service]\nType=oneshot\nExecStart=/usr/bin/systemctl stop rmm-bootstrap-download.service\nExecStart=/usr/sbin/ufw delete allow proto tcp from 0.0.0.0/0 to any port 8443\nNoNewPrivileges=true\n' + timer = '[Unit]\nDescription=Expire public recovery download\n[Timer]\nOnCalendar=' + expiry.strftime('%Y-%m-%d %H:%M:%S UTC') + '\nPersistent=true\nUnit=' + name + '.service\n[Install]\nWantedBy=timers.target\n' + for suffix, data in (('.service', service), ('.timer', timer)): + unit = Path('/etc/systemd/system') / (name + suffix) + write(unit, data.encode(), 0o644); run(['systemd-analyze', 'verify', str(unit)]) + require(snapshot() == before, 'immediate original config/code CAS') + write(history / 'replace-intent.json', b'{"once":true}', 0o600) + os.replace(next_cfg, cfg); os.replace(next_code, code) + run(['systemctl', 'daemon-reload']) + run(['systemctl', 'enable', '--now', name + '.timer']) + write(history / 'start-intent.json', b'{"once":true}', 0o600) + run(['ufw', 'allow', 'proto', 'tcp', 'from', '0.0.0.0/0', 'to', 'any', 'port', '8443']) + run(['systemctl', 'start', 'rmm-bootstrap-download.service']) + result = dict(published=True, expires_at=p['expires_at'], bundle_sha256=digest(archive), snapshot=snapshot(), close_timer=name + '.timer', rmm_deployment_changed=False, private_keys_read=False) + write(history / 'completed.json', json.dumps(result).encode(), 0o600) + return result + + +def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def save(path, value): + with path.open('x') as out: + json.dump(value, out, indent=2); out.flush(); os.fsync(out.fileno()) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare', 'publish', 'readback')) + parser.add_argument('--bundle', type=Path); parser.add_argument('--id'); parser.add_argument('--review-sha256') + args = parser.parse_args() + if args.action == 'prepare': + transport.require(args.bundle and not args.id and not args.review_sha256, 'new public bundle preparation') + with zipfile.ZipFile(args.bundle) as z: + transport.require(set(z.namelist()) == {'Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt'} and all(i.file_size < 65536 for i in z.infolist()), 'only three public recovery files') + public = json.loads(z.read('public-recovery.json')) + transport.require(public['no_private_keys'] is True and hashlib.sha256(z.read('Recover-ExistingDevAccess.ps1')).hexdigest() == public['script_sha256'], 'bound public script') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(parents=True, mode=0o700) + payload = dict(id=ident, old_code_sha256=sha(ROOT / 'deploy/windows/download_service.py'), expires_at=(dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45)).replace(microsecond=0).isoformat(), url_path='/windows/' + uuid.uuid4().hex + '/windows-dev-access-recovery.zip', bundle_sha256=sha(args.bundle), bundle=base64.b64encode(args.bundle.read_bytes()).decode()) + before = transport.rpc('server.conf', server, dict(payload, action='prepare')) + save(folder / 'intent.json', dict(source_sha256=sha(__file__), bundle_path=str(args.bundle.resolve()), payload=dict(payload, before=before))) + print(json.dumps(dict(id=ident, prepared=True, review_sha256=sha(folder / 'intent.json')))); return + transport.require(args.id and str(uuid.UUID(args.id)) == args.id, 'same canonical publication case') + folder = STATE / args.id; intent = json.loads((folder / 'intent.json').read_text()); p = intent['payload'] + transport.require(intent['source_sha256'] == sha(__file__) and sha(intent['bundle_path']) == p['bundle_sha256'], 'same reviewed source and bundle') + if args.action == 'publish': + transport.require(args.review_sha256 == sha(folder / 'intent.json'), 'reviewed exact publication intent') + save(folder / 'publish-attempt.json', dict(once=True, lost_reply_readback_only=True)) + result = transport.rpc('server.conf', server, dict(p, action=args.action)) + save(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), result) + if args.action == 'publish': + transport.require(result.get('published') is True, 'publication completed') + url = 'https://discovery.ease-technologies.de:8443' + p['url_path'] + with urllib.request.urlopen(url, context=ssl.create_default_context(), timeout=15) as response: + raw = response.read(262145) + transport.require(hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'external TLS verified exact download') + save(folder / 'external-verified.json', dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True)) + print(json.dumps(dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True))); return + print(json.dumps(result)) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/system_delegation_recovery.py b/deploy/windows/system_delegation_recovery.py new file mode 100644 index 0000000..be2a33e --- /dev/null +++ b/deploy/windows/system_delegation_recovery.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""One reviewed recovery of the unchanged failed6d2 joint upgrade; no retries. + +Uses explicit File.Replace backup paths, preserving the original failed source, +attempt, four backups, journals and intent. Readback never swaps or starts. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import uuid + +import client_bootstrap as cb +import system_delegation_upgrade as u + +CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437' +ORIGINAL_SOURCE = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38' +STATE = cb.EVIDENCE / 'system-delegation-recovery' +require = cb.contract.require +PREFIX = u.SCRIPT.split('\nCheckControl $boot $true\n', 1)[0] + +SCRIPT = PREFIX + r''' +$r=$global:RmmDelegationRecoveryPayload +if(!$r-or[guid]::ParseExact($r.recovery_id,'D').ToString()-cne$r.recovery_id-or$r.phase-notin@('prepare','enter','readback')-or$p.id-cne'6d2df065-0877-41c4-983c-2c9fdb6e5437'-or$r.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Only the original failed6d recovery'} +CheckControl $boot $true +$ownScript=Join-Path (Join-Path $boot $r.script_sha256) 'SystemDelegationRecovery.ps1' +if($PSCommandPath-cne$ownScript-or(Hash $PSCommandPath)-cne$r.script_sha256){throw 'Exact actually executing recovery source'} +CheckControl $ownScript $false +$intent=ReadIntent +$recovery=Join-Path $boot ('system-delegation-recovery-'+$r.recovery_id) +$recoveryActive=Join-Path $boot 'system-delegation-6d2-recovery-once.json' +function ReadService($role){$name=$agentName;if($role-ceq'helper'){$name=$helperName};$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10;if(!$s){throw 'Fixed existing service'};return @{state=$s.State;pid=$s.ProcessId;account=$s.StartName;mode=$s.StartMode;path=$s.PathName;exit_code=$s.ExitCode}} +function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path} +function RecoveryReadback{ + $original=[ordered]@{};foreach($name in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$original[$name]=Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))} + $own=[ordered]@{};foreach($name in @('intent','prepared','enter-attempt','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-intent','agent-start-intent','entered')){$own[$name]=Test-Path -LiteralPath (Join-Path $recovery ($name+'.json'))} + return @{read_only=$true;original_id=$p.id;recovery_id=$r.recovery_id;hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)};service=(ReadService 'agent');helper_service=(ReadService 'helper');original_phases=$original;recovery_phases=$own;recovery_active_exists=(Test-Path -LiteralPath $recoveryActive);no_repeated_start=$true} +} +if($r.phase-ceq'readback'){RecoveryReadback|ConvertTo-Json -Depth 20 -Compress;exit 0} +Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +public static class RmmDelegationRecoveryFileId { + [StructLayout(LayoutKind.Sequential)] public struct Id { + public ulong VolumeSerialNumber; + [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)] public byte[] FileId; + } + [DllImport("kernel32.dll", SetLastError=true)] + public static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, out Id info, uint length); +} +'@ +function FileIdentity($path){ + Check $path $false;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read) + try{$id=New-Object RmmDelegationRecoveryFileId+Id;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmDelegationRecoveryFileId+Id]);if($size-ne24-or![RmmDelegationRecoveryFileId]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Exact native file identity'} + return [ordered]@{volume_serial=$id.VolumeSerialNumber.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.FileId)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path)} + }finally{$file.Dispose()} +} +function CheckOriginalStopped{ + foreach($name in @('intent','agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt')){CheckControl (Join-Path $folder ($name+'.json')) $false} + foreach($name in @('helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){if(Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))){throw 'Original case progressed; no recovery replay'}} + $frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json + $current=State $false + if($current.service.state-cne'Stopped'-or$current.helper_service.state-cne'Stopped'){throw 'Both own original services must remain stopped'} + Preserved $frozen $current $true + $checks=@(@('agent',$p.old_agent,$p.new_agent),@('helper',$p.old_helper,$p.new_helper),@('settings',$p.old_policy,$p.new_policy),@('pin',$p.old_pin,$p.new_pin)) + foreach($item in $checks){$backup=Join-Path $folder ($item[0]+'-original');CheckControl $backup $false;if((Hash $backup)-cne$item[1]){throw 'Original exact backup'};$receipt=Get-Content -LiteralPath (Join-Path $folder ($item[0]+'-backup.json')) -Raw|ConvertFrom-Json;if($receipt.sha256-cne$item[1]){throw 'Original backup receipt'}} + $attempt=Get-Content -LiteralPath (Join-Path $folder 'agent-replace-attempt.json') -Raw|ConvertFrom-Json + if($attempt.old_sha256-cne$p.old_agent-or$attempt.new_sha256-cne$p.new_agent){throw 'Original unchanged failed agent attempt'} + if((Hash (Join-Path $folder 'agent-candidate'))-cne$p.new_agent){throw 'Retain exact original agent candidate'} + foreach($label in @('helper','settings','pin')){if(Test-Path -LiteralPath (Join-Path $folder ($label+'-candidate'))){throw 'No other old candidate expected'}} + if((Hash (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe'))-cne$p.new_agent-or(Hash (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe'))-cne$p.new_helper-or(Hash (Join-Path $folder 'new-helper.json'))-cne$p.new_policy-or(Hash (Join-Path $folder 'new-agent-pin.json'))-cne$p.new_pin){throw 'All four complete new sources'} + $current['recovery_file_identities']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);agent_candidate=(FileIdentity (Join-Path $folder 'agent-candidate'))} + return $current +} +if($r.phase-ceq'prepare'){ + if((Test-Path -LiteralPath $recovery)-or(Test-Path -LiteralPath $recoveryActive)){throw 'Existing recovery: readback only'} + $before=CheckOriginalStopped + New-Item -ItemType Directory -Path $recovery|Out-Null;CheckControl $recovery $true + WriteNew $recoveryActive @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;create_only=$true} + WriteNew (Join-Path $recovery 'intent.json') @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;original_payload=$p;before=$before} + WriteNew (Join-Path $recovery 'prepared.json') @{prepared=$true;no_service_changes=$true;original_failed_attempt_retained=$true} + @{prepared=$true;original_id=$p.id;recovery_id=$r.recovery_id;both_stopped=$true;preserved=$true}|ConvertTo-Json -Compress;exit 0 +} +CheckControl $recovery $true;foreach($name in @('intent.json','prepared.json')){CheckControl (Join-Path $recovery $name) $false};CheckControl $recoveryActive $false +$saved=Get-Content -LiteralPath (Join-Path $recovery 'intent.json') -Raw|ConvertFrom-Json;$currentActive=Get-Content -LiteralPath $recoveryActive -Raw|ConvertFrom-Json +if($saved.original_id-cne$p.id-or$saved.recovery_id-cne$r.recovery_id-or$saved.script_sha256-cne$r.script_sha256-or!(JsonEqual $saved.original_payload $p)-or$currentActive.original_id-cne$p.id-or$currentActive.recovery_id-cne$r.recovery_id-or$currentActive.script_sha256-cne$r.script_sha256){throw 'Exact original recovery admission'} +if(Test-Path -LiteralPath (Join-Path $recovery 'enter-attempt.json')){throw 'Recovery already attempted: readback only'} +$before=CheckOriginalStopped;Preserved $saved.before $before $true +if(!(JsonEqual $saved.before.recovery_file_identities $before.recovery_file_identities)){throw 'Original destination/candidate file IDs or ACL/bytes changed'} +WriteNew (Join-Path $recovery 'enter-attempt.json') @{enter_once=$true;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256} +function RecoverSwap($label,$destination,$source,$oldHash,$newHash,[bool]$reuse){ + if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'No component start during four-file recovery'} + $candidate=Join-Path $folder ($label+'-candidate');$nativeBackup=Join-Path $recovery ($label+'-native-original') + $oldReceipt=Get-Content -LiteralPath (Join-Path $folder ($label+'-backup.json')) -Raw|ConvertFrom-Json;$sddl=$oldReceipt.original_sddl + if((Hash $destination)-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))-or(Test-Path -LiteralPath $nativeBackup)){throw 'Exact old destination/backup/ACL and new source CAS'} + if($reuse){if((Hash $candidate)-cne$newHash){throw 'Retain original exact candidate'}}else{if(Test-Path -LiteralPath $candidate){throw 'Candidate exists; no overwrite'};[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate} + if((Hash $candidate)-cne$newHash){throw 'Complete candidate'} + $destinationIdentity=FileIdentity $destination;$candidateIdentity=FileIdentity $candidate + if(!(JsonEqual $destinationIdentity $before.recovery_file_identities.$label)-or($reuse-and!(JsonEqual $candidateIdentity $before.recovery_file_identities.agent_candidate))){throw 'Fresh native CAS identities/ACL/bytes'} + WriteNew (Join-Path $recovery ($label+'-replace-attempt.json')) @{old_sha256=$oldHash;new_sha256=$newHash;native_backup=$nativeBackup;recovery_id=$r.recovery_id;source_sha256=$r.script_sha256;destination_identity=$destinationIdentity;candidate_identity=$candidateIdentity} + [IO.File]::Replace($candidate,$destination,$nativeBackup) + PrivateBackupAcl $nativeBackup + $acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination + if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))){throw 'Actual exact replacement and explicit original backup'} + $receipt=@{old_sha256=$oldHash;new_sha256=$newHash;backup_sha256=(Hash (Join-Path $folder ($label+'-original')));acl_sha256=(AclHash $destination);native_backup_sha256=(Hash $nativeBackup);recovery_id=$r.recovery_id;source_sha256=$r.script_sha256} + WriteNew (Join-Path $recovery ($label+'-replaced.json')) $receipt + WriteNew (Join-Path $folder ($label+'-replaced.json')) $receipt +} +try{ + RecoverSwap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent $true + RecoverSwap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper $false + RecoverSwap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy $false + RecoverSwap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin $false + $swapped=State $true;Preserved $before $swapped $true + if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files checked before first start'} + $swapped['recovery_id']=$r.recovery_id;$swapped['recovery_source_sha256']=$r.script_sha256 + WriteNew (Join-Path $recovery 'swapped.json') $swapped;WriteNew (Join-Path $folder 'swapped.json') $swapped + WriteNew (Join-Path $recovery 'helper-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'helper' + WriteNew (Join-Path $recovery 'agent-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'agent' + $after=State $true;Preserved $intent.before $after $false;Preserved $before $after $false + $after['recovery_id']=$r.recovery_id;$after['recovery_source_sha256']=$r.script_sha256 + WriteNew (Join-Path $recovery 'entered.json') $after;WriteNew (Join-Path $folder 'entered.json') $after + @{entered=$true;original_id=$p.id;recovery_id=$r.recovery_id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress +}catch{WriteNew (Join-Path $recovery ('incomplete-'+[guid]::NewGuid().ToString()+'.json')) @{error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;readback_only=$true;no_retry=$true};throw} +''' + +PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1') +LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1').replace('RmmTransportPayload', 'RmmDelegationRecoveryPayload') +# Prefix reads the immutable original payload; the recovery data is separate. +LAUNCH = LAUNCH.replace('& $script', '$global:RmmDelegationUpgradePayload=$p.payload.original_payload\n& $script') + + +def load(recovery_id): + require(str(uuid.UUID(recovery_id)) == recovery_id, 'canonical recovery UUID') + folder = STATE / recovery_id; intent = cb.contract.protected_json(folder / 'intent.json') + require(u.sha(u.__file__) == ORIGINAL_SOURCE and intent['runner_sha256'] == u.sha(__file__) and intent['script_sha256'] == u.raw_sha(SCRIPT.encode()), 'original and new source remain immutable') + _, original = u.load_case(CASE) + require(intent['original_intent_sha256'] == u.sha(u.STATE / CASE / 'intent.json') and intent['original_payload'] == original['payload'], 'unchanged original case') + return folder, intent + + +def remote(intent, phase): + original_action = 'readback' if phase == 'readback' else 'enter' + payload = dict(recovery_id=intent['recovery_id'], phase=phase, script_sha256=intent['script_sha256'], original_payload=dict(intent['original_payload'], action=original_action)) + return cb.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=payload), timeout=180, remote_signed=True) + + +def prepare(): + require(u.sha(u.__file__) == ORIGINAL_SOURCE, 'original failed runner must not change') + _, original = u.load_case(CASE) + original_folder = u.STATE / CASE + require((original_folder / 'enter-attempt.json').is_file() and (original_folder / 'reply-incomplete.json').is_file(), 'actual original failed entry retained') + u.original_helper.private_dir(STATE) + recovery_id = str(uuid.uuid4()); folder = STATE / recovery_id; folder.mkdir(mode=0o700) + intent = dict(schema_version=1, type='rmm.windows.passive-joint-recovery', recovery_id=recovery_id, original_id=CASE, original_payload=original['payload'], original_intent_sha256=u.sha(original_folder / 'intent.json'), runner_sha256=u.sha(__file__), script_sha256=u.raw_sha(SCRIPT.encode())) + u.save(folder / 'intent.json', intent) + source = folder / 'SystemDelegationRecovery.ps1' + fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno()) + u.original_helper.transfer(source, 'SystemDelegationRecovery.ps1', intent['script_sha256'], PREPARE) + result = remote(intent, 'prepare'); u.save(folder / 'prepared.json', result) + require(result.get('prepared') is True and result.get('both_stopped') is True and result.get('preserved') is True, 'actual preserved recovery admission') + print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'prepared': True, 'no_start': True})) + + +def run(recovery_id, phase): + folder, intent = load(recovery_id) + if phase == 'enter': + require(cb.contract.protected_json(folder / 'prepared.json')['prepared'] is True, 'actual prepared admission') + u.save(folder / 'enter-attempt.json', {'once': True, 'lost_reply_readback_only': True}) + try: + result = remote(intent, phase) + except Exception as error: + u.save(folder / ('reply-incomplete-' + str(uuid.uuid4()) + '.json'), {'error_type': type(error).__name__, 'readback_only': True}) + raise + u.save(folder / ('entered.json' if phase == 'enter' else 'readback-' + str(uuid.uuid4()) + '.json'), result) + print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'entered': result.get('entered', False), 'read_only': result.get('read_only', False), 'original_phases': result.get('original_phases'), 'recovery_phases': result.get('recovery_phases')})) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=['prepare', 'enter', 'readback']); parser.add_argument('--id'); args = parser.parse_args() + os.umask(0o077) + if args.phase == 'prepare': + require(args.id is None, 'create a new recovery admission'); prepare() + else: + require(args.id is not None, 'exact existing recovery UUID required'); run(args.id, args.phase) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/system_pipe_upgrade.py b/deploy/windows/system_pipe_upgrade.py new file mode 100644 index 0000000..02eeeb9 --- /dev/null +++ b/deploy/windows/system_pipe_upgrade.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""One preserving passive pipe-v2 pair upgrade; no target actions by default. + +prepare stages immutable bootstrap artifacts and captures a read-only baseline. +enter needs that exact separately reviewed baseline hash and runs once. A lost +reply permits readback/finish only. Main access-root is read-only, including the +current indices: Root publishes those separately after reviewing this result. +""" +import argparse +import base64 +import hashlib +import inspect +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +import uuid + +import client_bootstrap as cb +import system_delegation_upgrade as u + +require = cb.contract.require +ROOT = cb.ROOT +STATE = cb.EVIDENCE / 'system-pipe-upgrade' +ORIGINAL_RUNNER = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38' +OLD_AGENT = '89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676' +OLD_HELPER = 'e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662' +OLD_POLICY = '007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703' +OLD_PIN = '126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15' +OLD_CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437' +OLD_RESULT_SHA = 'ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460' +PIPE_VERIFIER_SHA = '2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf' +sha, raw_sha, canonical, save = u.sha, u.raw_sha, u.canonical, u.save + + +def replace_once(text, old, new): + require(text.count(old) == 1, 'exact reviewed bootstrap splice') + return text.replace(old, new, 1) + + +def write_bytes(path, data): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(data); output.flush(); os.fsync(output.fileno()) + + +# Reuse read-only witnesses only, bound to the historical runner hash below. +# None of its original hard-PID stop, File.Replace(NULL), start, or case logic +# is included. Every new mutation is visible in this file. +PREFIX = u.SCRIPT.split('\nfunction ReadIntent', 1)[0] +PREFIX = replace_once(PREFIX, 'RmmDelegationUpgradePayload', 'RmmPipeUpgradePayload') +PREFIX = replace_once(PREFIX, "@('state','enter','finish','readback')", "@('baseline','enter','finish','readback')") +PREFIX = replace_once(PREFIX, "('system-delegation-'+$p.id)", "('system-pipe-'+$p.id)") +PREFIX = replace_once(PREFIX, "'system-delegation-active-intent.json'", "'system-pipe-active-intent.json'") +for old, new in ((u.OLD_AGENT, OLD_AGENT), (u.OLD_HELPER, OLD_HELPER), (u.OLD_POLICY, OLD_POLICY), (u.OLD_PIN, OLD_PIN)): + PREFIX = replace_once(PREFIX, old, new) + +NATIVE = r''' +Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using Microsoft.Win32.SafeHandles; +public static class RmmPipeNative { + public sealed class Held : SafeHandleZeroOrMinusOneIsInvalid { + public Held(IntPtr h):base(true){SetHandle(h);} + protected override bool ReleaseHandle(){return CloseHandle(handle);} + } + [StructLayout(LayoutKind.Sequential)] public struct FileId { + public ulong Volume; + [MarshalAs(UnmanagedType.ByValArray,SizeConst=16)] public byte[] Id; + } + [StructLayout(LayoutKind.Sequential)] struct SidAndAttributes {public IntPtr Sid;public uint Attributes;} + [StructLayout(LayoutKind.Sequential)] struct Groups {public uint Count;public SidAndAttributes First;} + [DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid); + [DllImport("kernel32.dll",SetLastError=true)] static extern bool CloseHandle(IntPtr h); + [DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(Held h,out long creation,out long exit,out long kernel,out long user); + [DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(Held h,uint flags,StringBuilder image,ref uint size); + [DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(Held h,uint millis); + [DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(Held process,uint access,out IntPtr token); + [DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,int bytes,out int needed); + [DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int kind,out FileId id,uint size); + [DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] public static extern SafeFileHandle CreateFile(string path,uint access,uint share,IntPtr security,uint creation,uint flags,IntPtr template); + public static Held Open(int pid){IntPtr h=OpenProcess(0x101000,false,pid);if(h==IntPtr.Zero)throw new Win32Exception();return new Held(h);} + public static bool Alive(Held h){return WaitForSingleObject(h,0)==258;} + public static bool Exited(Held h,uint timeout){return WaitForSingleObject(h,timeout)==0;} + static IntPtr Info(IntPtr token,int kind,out int bytes){ + int needed;GetTokenInformation(token,kind,IntPtr.Zero,0,out needed); + if(needed<=0||needed>65536)throw new InvalidOperationException("Token size"); + IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p; + } + public static Dictionary Proof(Held h,int pid,string owner,string serviceSid,string image){ + if(!Alive(h))throw new InvalidOperationException("Process not alive"); + long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception(); + StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image"); + IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception(); + try { + int bytes;IntPtr info=Info(token,1,out bytes);string actual; + try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);} + if(actual!=owner)throw new InvalidOperationException("Process owner"); + info=Info(token,2,out bytes);bool found=false; + try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes)); + if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size"); + for(int n=0;n{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}}; + }finally{CloseHandle(token);} + } +} +'@ +function FileIdentity($path,[bool]$actor=$false){ + Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read) + try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'} + return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)} + }finally{$file.Dispose()} +} +function Kernel($role,$record,$held){ + $owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary} + $proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image) + if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof +} +function ActualState([bool]$new){ + $value=State $new + $value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))} + foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service} + $proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}} + $value[$role+'_kernel']=$proof + };return $value +} +# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds +# the private key's actual native FileID, not merely a timestamp/name. +function FileIdentityMetadata($path){ + Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero) + try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()} +} +function SameOriginal($before,$after){ + Preserved $before $after $false + if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'} + foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}} +} +function PreserveImmutableFiles($before,$after,[bool]$frozen){ + Preserved $before $after $frozen + foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}} +} +''' + +# The original fixed-role SCM configuration checks are reused exactly. Unlike +# Service(), this readback projection makes no running-process proof claim and +# honestly exposes pending/raw State/PID without changing a service. +READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r''' + $state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'} + return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true} +} +''' + +PHASES = r''' +CheckControl $boot $true +if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'} +if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0} +function ReadCase{ + CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false + $i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json + if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'} + foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}} + if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i +} +if($p.action-ceq'readback'){ + function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path} + $i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))} + @{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0 +} +if($p.action-ceq'finish'){ + $i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false + CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false + foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}} + @{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0 +} +if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'} +$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json +$before=ActualState $false;SameOriginal $baseline $before +if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'} +$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null +try{ + $null=Kernel 'agent' $before.service $heldAgent + if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper} + New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true + WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true} + function StopHeld($role,$record,$held){ + $live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held + $name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record} + Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'} + WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true} + } + StopHeld 'agent' $before.service $heldAgent + if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}} + $frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen + function Backup($label,$path,$expected){ + $identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'} + $backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup + if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl} + } + Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin + $settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'} + WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes + function Swap($label,$destination,$source,$oldHash,$newHash){ + if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'} + foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}} + $old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate') + if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'} + [IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'} + WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256} + if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'} + [IO.File]::Replace($candidate,$destination,$nativeBackup) + PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination + if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'} + WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))} + } + Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent + Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper + Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy + Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin + $swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped + function StartOnce($role){ + $checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName} + WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true} + Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20)) + $s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()} + } + StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after + @{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress +}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}} +''' +SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES +PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1') +LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload') + + +class Access: + """Explicit read-only access roots; never redirects source/manifest globals.""" + def __init__(self, root): + self.root = Path(root).absolute() + require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy') + self.evidence = self.root / 'devstate/windows-client' + + def powershell(self, source, payload, timeout=180): + access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json') + wrapped = "try {\n" + source + "\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}" + command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode() + result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout) + if result.returncode: + # Fixed error identifiers/line only; never raw stderr/payload/commands. + safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr)) + try: + error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object) + if error.get('bootstrap_error') is True: + safe.update(error_id=error.get('error_id'), line=error.get('line')) + except (ValueError, AttributeError): + pass + save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe) + raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only') + return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object) + + def stage(self, path, name): + require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names') + path = Path(path) + digest = sha(path) + prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name) + observed = self.powershell(prepare, dict(sha256=digest)) + if not observed['already_uploaded']: + access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json') + prefix = access['ssh_prefix'] + args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]] + target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name + result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60) + require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry') + observed = self.powershell(prepare, dict(sha256=digest)) + require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage') + + def server(self, function, payload): + cloud = u.transport.cloud + require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses') + # The inherited parser is strict data parsing, not source/eval. Its ROOT + # only checks the source .gitignore; its supplied path remains Main. + cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf') + ssh = ['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 = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n') + result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60) + require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness') + value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object) + require('error' not in value, 'readonly server witness incomplete') + return value + + def server_state(self): + cloud = u.transport.cloud + linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json') + require(linux['verified'] is True, 'accepted Linux target only') + counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in ( + ('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))} + flags = self.server(u.auto.server_state, {}) + require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate') + return dict(counts=counts, flags=flags) + + def observe(self, ident): + return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident)) + + def device_and_denials(self): + bridge = self + class ReadBackend(u.transport.cloud.Backend): + def request(self, body): + if body['method'] == 'tools/call': + require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads') + else: + require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session') + return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal)) + device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET)) + require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory') + denied = [] + backend = ReadBackend('b') + for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'): + backend.sequence += 1 + response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET)))) + data = response.get('data', {}) + require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied') + denied.append(dict(tenant_id=tenant, denied=True)) + return device, denied + + +def dependencies(): + modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper] + return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules} + + +def guards(): + require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source') + require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded') + require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup') + ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")] + require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts') + require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives') + require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback') + + +# Fresh isolated interpreter: the Pipe pack deliberately imports its transport +# modules from Main. Reusing its module in this interpreter would accidentally +# reuse our cached worktree client_bootstrap and corrupt the source/access split. +# This code calls verification/read-only proof parsing ONLY, never native(). +VERIFY_PACK = r''' +import hashlib,importlib.util,json,re,sys,uuid +from pathlib import Path +path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path) +pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack) +manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve() +manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs +proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require +case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace') +require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability') +intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json') +require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest') +require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent') +before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json') +require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope') +actual=proof['native'] +require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only') +for kind,count in pack.COUNTS.items(): + report=actual['reports'][kind];listed=report['listed'];run=report['result'] + names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M) + require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout') +print(json.dumps(manifest)) +''' + + +def qualified(manifest_path, proof_path): + verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py' + require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier') + result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60) + require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld') + value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object) + require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling') + return value + + +def prior(access): + runtime_path = access.evidence / 'current-runtime.json' + components_path = access.evidence / 'current-components.json' + runtime = cb.contract.protected_json(runtime_path) + components = cb.contract.protected_json(components_path) + result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json') + require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result') + result = cb.contract.protected_json(result_path) + require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation') + evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA) + require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback') + recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json' + require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved') + original = cb.contract.protected_json(result_path.parent / 'intent.json') + settings = base64.b64decode(original['payload']['settings_base64'], validate=True) + require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings') + return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object) + + +def passive_settings(old, agent, helper): + require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings') + require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes') + new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper + settings = canonical(new); policy = raw_sha(settings) + pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper'])) + return settings, pin, policy + + +def leaves(access): + path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json' + require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation') + proof = cb.contract.protected_json(path) + require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification') + created_path = path.parent / 'created.json' + require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt') + created = cb.contract.protected_json(created_path) + items = {v['name']: v for v in created['leaves']} + require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves') + return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]} + + +def remote(access, intent, action): + require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source') + return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action))) + + +def load(ident, access): + require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID') + folder = STATE / ident + intent = cb.contract.protected_json(folder / 'intent.json') + require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case') + manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path'])) + require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair') + return folder, intent + + +def prepare(access, manifest_path, proof_path): + guards() + manifest = qualified(manifest_path, proof_path) + indices, accepted, old = prior(access) + settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256']) + require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round') + ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True) + script_sha = raw_sha(SCRIPT.encode()) + payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access)) + draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True) + save(folder / 'prepare-intent.json', draft) + for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]: + write_bytes(folder / name, data) + for kind in ('agent', 'helper', 'probe', 'system_probe'): + item = manifest['artifacts'][kind] + require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes') + access.stage(item['path'], item['name']) + access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1') + before = remote(access, draft, 'baseline') + expected = accepted['native'] + for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'): + require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read') + for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'): + require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity') + for field in ('helper_ledger', 'executor_lock', 'intent_store'): + require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves') + for role in ('service', 'helper_service'): + for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'): + require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL') + baseline = canonical(before) + write_bytes(folder / 'baseline.json', baseline) + payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline)) + draft['payload'] = payload + save(folder / 'intent.json', draft) + save(folder / 'server-before.json', access.server_state()) + central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device') + save(folder / 'central-before.json', central) + print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True))) + + +def enter(access, ident, baseline_sha): + folder, intent = load(ident, access) + require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required') + indices, _, _ = prior(access) + require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged') + save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True)) + result = remote(access, intent, 'enter') + require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply') + save(folder / 'entered.json', result) + print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter'))) + + +def finish(access, ident, read_only=False): + folder, intent = load(ident, access) + action = 'readback' if read_only else 'finish' + observed = remote(access, intent, action) + save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed) + require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback') + if read_only: + print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return + require(observed['completed'] is True, 'actual complete pair preservation') + result_path = folder / 'result.json' + if result_path.exists(): + previous = cb.contract.protected_json(result_path) + require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation') + print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return + # Two genuinely new server heartbeats after both single starts, not cached + # contacts from baseline, and no new network-agent jobs/capabilities. + after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json') + watermark = access.observe(ident)['device'] + require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark') + deadline = time.monotonic() + 150; first = None + while True: + evidence = access.observe(ident); device = evidence['device'] + if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']): + require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity') + if first is None: first = evidence + elif device['last_contact_at'] != first['device']['last_contact_at']: break + require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing') + time.sleep(2) + final = remote(access, intent, 'finish'); native = final['native'] + original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object) + require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK') + device, denied = access.device_and_denials() + require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory') + require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged') + indices, _, _ = prior(access) + require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication') + pipe = u.actual_pipe_proof(native, intent) + result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256']) + save(result_path, result) + print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False))) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards')) + parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256') + args = parser.parse_args(); guards() + if args.phase == 'guards': + require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return + require(args.access_root, 'explicit separate read-only Main access root') + access = Access(args.access_root) + if args.phase == 'prepare': + require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation') + prepare(access, args.manifest, args.qualification) + elif args.phase == 'enter': + require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash') + enter(access, args.id, args.baseline_sha256) + else: + require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish') + finish(access, args.id, args.phase == 'readback') + + +if __name__ == '__main__': + try: main() + except Exception as error: + print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__) + raise SystemExit(2) from None diff --git a/deploy/windows/test_system_pipe_upgrade.py b/deploy/windows/test_system_pipe_upgrade.py new file mode 100644 index 0000000..825fc2a --- /dev/null +++ b/deploy/windows/test_system_pipe_upgrade.py @@ -0,0 +1,70 @@ +"""Four local orchestration guards; no credentials/VM/Windows API calls.""" +import contextlib +import copy +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +import system_pipe_upgrade as p + + +def settings(): + return dict(schema_version=1, binding={'public_fixture': True}, agent=dict(binary_sha256=p.OLD_AGENT), helper=dict(binary_sha256=p.OLD_HELPER), allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False) + + +class PipeUpgradeGuards(unittest.TestCase): + def test_closed_reciprocal_settings_only_change_two_image_pins(self): + original = settings(); preserved = copy.deepcopy(original) + raw, pin, policy = p.passive_settings(original, 'a' * 64, 'b' * 64) + changed = json.loads(raw); changed['agent']['binary_sha256'] = p.OLD_AGENT; changed['helper']['binary_sha256'] = p.OLD_HELPER + self.assertEqual(changed, preserved); self.assertEqual(original, preserved) + self.assertEqual(p.raw_sha(raw), policy); self.assertEqual(json.loads(pin)['policy_sha256'], policy) + for field, value in [('enable_effects', True), ('allow_reboot', True), ('allowed_services', ['foreign']), ('max_runtime_seconds', 120), ('schema_version', True)]: + bad = settings(); bad[field] = value + with self.subTest(field=field), self.assertRaises(RuntimeError): p.passive_settings(bad, 'a' * 64, 'b' * 64) + + def test_historical_mutation_helpers_excluded_and_explicit_backups_ordered(self): + p.guards() + self.assertNotIn('function PinProcess', p.PREFIX) + self.assertNotIn('[IO.File]::Replace($candidate,$destination,$null)', p.SCRIPT) + self.assertIn('[RmmPipeNative]::Open([int]$before.service.pid)', p.SCRIPT) + self.assertNotIn('$expected=5140', p.SCRIPT) + self.assertIn("'helper-already-stopped.json'", p.SCRIPT) + self.assertIn('stop_called=$false;start_called=$false', p.SCRIPT) + self.assertIn("@('config','ca','identity','certificate','private_key')", p.SCRIPT) + self.assertEqual(p.SCRIPT.count('PreserveImmutableFiles '), 5) + readback = p.PHASES.split("if($p.action-ceq'readback'){", 1)[1].split("if($p.action-ceq'finish'){", 1)[0] + self.assertIn("(ReadbackService 'agent')", readback) + self.assertNotIn('(Service ', readback) + self.assertIn('process_identity_verified=$false', p.READBACK_SERVICE) + self.assertIn('pack.verified(manifest_path)', p.VERIFY_PACK) + self.assertIn("names==report['names']==pack.TESTS[kind]", p.VERIFY_PACK) + with patch.object(p.subprocess, 'run', return_value=Mock(returncode=0, stdout=b'{"type":"rmm.windows.system-delegation-build"}')): + with self.assertRaises(RuntimeError): p.qualified(Path('unused-fixture'), Path('unused-proof')) + + def test_lost_enter_reply_cannot_repeat_target_mutation(self): + with tempfile.TemporaryDirectory() as temporary: + folder = Path(temporary); p.write_bytes(folder / 'baseline.json', b'{}') + digest = p.sha(folder / 'baseline.json'); indices = {'unit_fixture': True} + intent = dict(payload=dict(baseline_sha256=digest), original_indices=indices) + p.save(folder / 'server-before.json', {'unit_counts': 0}) + access = Mock(); access.server_state.return_value = {'unit_counts': 0} + with patch.object(p, 'load', return_value=(folder, intent)), patch.object(p, 'prior', return_value=(indices, {}, {})), patch.object(p, 'remote', side_effect=TimeoutError('unit fixture lost reply')) as remote: + with self.assertRaises(TimeoutError): p.enter(access, 'fixture', digest) + self.assertTrue((folder / 'enter-attempt.json').exists()) + with self.assertRaises(FileExistsError): p.enter(access, 'fixture', digest) + self.assertEqual(remote.call_count, 1) + + def test_readback_never_queries_server_starts_or_publishes_main_indices(self): + with tempfile.TemporaryDirectory() as temporary: + access = Mock(); access.server_state.side_effect = AssertionError('server unavailable in readback') + with patch.object(p, 'load', return_value=(Path(temporary), {})), patch.object(p, 'remote', return_value=dict(read_only=True, id='fixture', phase_receipts={})) as remote, contextlib.redirect_stdout(io.StringIO()): + p.finish(access, 'fixture', read_only=True) + remote.assert_called_once_with(access, {}, 'readback') + self.assertFalse(access.server_state.called) + + +if __name__ == '__main__': unittest.main() diff --git a/deploy/windows/time_service_after_boot.py b/deploy/windows/time_service_after_boot.py new file mode 100644 index 0000000..2f7f649 --- /dev/null +++ b/deploy/windows/time_service_after_boot.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Fresh, once-only W32Time start after the user-confirmed console boot. + +Reuse the previously reviewed preservation checks, with a separate admission +record. Historical start intents and reports are never reset or overwritten. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import uuid + +import time_service_start as original +import auto_transport_acceptance as auto + +cb = original.cb +require = original.require +BOOT = '2026-11-14T12:26:50.5000000Z' +ORIGINAL_SHA = 'ef5d4ce8ec2e8f3486da8540b3f47230406c6604157b7920e1e5202c88b97e6e' +require(original.digest(original.__file__) == ORIGINAL_SHA, 'frozen original time bootstrap') +STATE = cb.EVIDENCE / 'time-service-after-console-boot' +SCRIPT = original.SCRIPT + + +def substitute(old, new): + global SCRIPT + require(SCRIPT.count(old) == 1, 'exact reviewed source derivation') + SCRIPT = SCRIPT.replace(old, new) + + +substitute("$active=Join-Path $boot 'w32time-start-once.json'", + "$active=Join-Path $boot 'w32time-start-after-console-20261114T122650.json'") +substitute('function Snapshot{', r'''function Snapshot{ + $actualBoot=(Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().ToString('o') + if($actualBoot-cne'2026-11-14T12:26:50.5000000Z'){throw 'Exact user-confirmed console boot required'}''') +substitute("$service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'}", + """$service=ServiceState $pair[0] + $stoppedHelper=($pair[0]-ceq'RmmDiscoverySystemHelper'-and$service.state-ceq'Stopped'-and$service.pid-eq0-and$service.definition.start_mode-ceq'Manual'-and$service.definition.account-ceq'LocalSystem') + if(!$stoppedHelper-and($service.state-cne'Running'-or$service.pid-le0)){throw 'Exact running agent or stopped manual helper required'} + if($stoppedHelper){$birth=$null;$image=$pair[1]}else{""") +substitute("finally{$proc.Dispose()}\n if(![string]", "finally{$proc.Dispose()}}\n if(![string]") +PREPARE = original.PREPARE.replace('TimeServiceStart.ps1', 'TimeServiceAfterBoot.ps1') +LAUNCH = original.LAUNCH.replace('TimeServiceStart.ps1', 'TimeServiceAfterBoot.ps1') + + +def remote(folder, payload): + try: + return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), + 'payload': payload}, timeout=100, remote_signed=True) + finally: + original.preserve_failure(folder) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare', 'start', 'readback')) + parser.add_argument('--id') + args = parser.parse_args() + os.umask(0o077) + if args.action == 'prepare': + require(args.id is None, 'fresh separate case') + original.helper.private_dir(STATE) + folder = STATE / str(uuid.uuid4()); folder.mkdir(mode=0o700) + counts, flags = auto.scopes(), auto.status() + require(auto.flags_disabled(flags), 'closed test hooks') + pins = dict(agent_sha256='89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676', + helper_sha256='e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662', + config_sha256='7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851', + policy_sha256='007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703', + pin_sha256='126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15') + payload = dict(id=folder.name, **pins) + original.save(folder, 'intent.json', dict(payload=payload, boot=BOOT, + source_sha256=original.digest(__file__), script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(), + server_before=dict(counts=counts, flags=flags))) + source = folder / 'TimeServiceAfterBoot.ps1' + with source.open('xb') as out: + out.write(SCRIPT.encode()); out.flush(); os.fsync(out.fileno()) + original.helper.transfer(source, source.name, hashlib.sha256(SCRIPT.encode()).hexdigest(), PREPARE) + before = remote(folder, dict(payload, action='state')) + original.save(folder, 'before.json', before) + require(before['read_only'] is True and before['snapshot']['time_service']['state'] == 'Stopped', 'fresh stopped time-service baseline') + print(json.dumps(dict(case_id=folder.name, prepared=True, start_executed=False))) + return + require(args.id and str(uuid.UUID(args.id)) == args.id, 'original canonical case') + folder = STATE / args.id + intent = cb.contract.protected_json(folder / 'intent.json') + before = cb.contract.protected_json(folder / 'before.json') + require(intent['source_sha256'] == original.digest(__file__) and intent['boot'] == BOOT + and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same source and user-confirmed boot') + if args.action == 'start': + require(dict(counts=auto.scopes(), flags=auto.status()) == intent['server_before'], 'same closed central context') + original.save(folder, 'start-attempt.json', dict(once=True, lost_reply_readback_only=True)) + payload = intent['payload'] + result = remote(folder, dict(payload, action=args.action, baseline_sha256=before['baseline_sha256'], + expected_sha256=hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(',', ':')).encode()).hexdigest())) + original.save(folder, 'result.json' if args.action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json', result) + require(dict(counts=auto.scopes(), flags=auto.status()) == intent['server_before'], 'central context preserved') + require(result.get('preserved') is True, 'original components and time configuration preserved') + current = result.get('current') or result.get('after') + require(current and current['time_service']['state'] == 'Running', 'actual running readback') + print(json.dumps(dict(case_id=args.id, running=True, preserved=True, + readback_only=args.action == 'readback', clock_qualified=False))) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/time_service_start.py b/deploy/windows/time_service_start.py new file mode 100644 index 0000000..490152b --- /dev/null +++ b/deploy/windows/time_service_start.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Start the existing W32Time once after review; lost replies use readback only. + +This bootstrap never changes service configuration, NTP, policy, ACLs or RMM +components. A running W32Time is not evidence of a qualified/trusted clock. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import uuid + +import client_bootstrap as cb +import system_helper_bootstrap as helper +import transport_acceptance as source_stage + +STATE = cb.EVIDENCE / 'time-service-start' +CONTEXT = cb.EVIDENCE / 'time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973/before.json' +require = cb.contract.require + +SCRIPT = r'''$ErrorActionPreference='Stop' +$p=$global:RmmTimeServiceStartPayload +if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','start','readback')){throw 'Fixed time-service case'} +foreach($name in @('agent_sha256','helper_sha256','config_sha256','policy_sha256','pin_sha256')){if($p.$name-notmatch'^[a-f0-9]{64}$'){throw 'Exact retained component pins'}} +$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-service-'+$p.id);$active=Join-Path $boot 'w32time-start-once.json' +function HashBytes([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}} +function JsonHash($value){return HashBytes ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress)))} +function CheckControl($path,[bool]$directory){ + $item=Get-Item -LiteralPath $path -Force + if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed private bootstrap path'} + $acl=Get-Acl -LiteralPath $path + if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$acl.Access.Count){throw 'Bootstrap owner/DACL'} + foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Bootstrap controller only'}} +} +function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));$file=[IO.File]::Open($path,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()};CheckControl $path $false} +function FileMeta($path,[bool]$hash){ + $item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original component'} + $parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original ancestor reparse'};$parent=$parent.Parent} + $acl=Get-Acl -LiteralPath $path + return [ordered]@{length=$item.Length;created_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();written_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();owner_sid=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;acl_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($acl.Sddl)));sha256=if($hash){(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}else{$null}} +} +function ServiceState($name){ + $service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10 + if(!$service){throw 'Existing fixed service required'} + $security=& "$env:WINDIR\System32\sc.exe" sdshow $name;if($LASTEXITCODE-ne0){throw 'Read service security'} + $sidtype=& "$env:WINDIR\System32\sc.exe" qsidtype $name;if($LASTEXITCODE-ne0){throw 'Read service SID type'} + $definition=[ordered]@{account=$service.StartName;start_mode=$service.StartMode;image_path=$service.PathName;service_type=$service.ServiceType;security_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($security-join "`n").Trim())));sid_type_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($sidtype-join "`n").Trim())))} + return [ordered]@{name=$name;state=$service.State;pid=$service.ProcessId;definition=$definition} +} +function TimeConfigHash{ + # Selected stable configuration only. Normal synchronization may update other + # runtime registry state; neither values nor NTP hostnames leave this function. + $specs=@( + @('SYSTEM\CurrentControlSet\Services\W32Time',@('Start','DelayedAutoStart','ImagePath','ObjectName','Type')), + @('SYSTEM\CurrentControlSet\Services\W32Time\Parameters',@('Type','NtpServer','ServiceDll','ServiceMain')), + @('SYSTEM\CurrentControlSet\Services\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval','FrequencyCorrectRate','PhaseCorrectRate','LocalClockDispersion')), + @('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')), + @('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')), + @('SOFTWARE\Policies\Microsoft\W32Time\Parameters',@('Type','NtpServer')), + @('SOFTWARE\Policies\Microsoft\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval')), + @('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')), + @('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName'))) + $entries=@();foreach($spec in $specs){$path='Registry::HKEY_LOCAL_MACHINE\'+$spec[0];$exists=Test-Path -LiteralPath $path;$values=@() + if($exists){$key=Get-Item -LiteralPath $path;try{foreach($name in $spec[1]){if($key.GetValueNames()-ccontains$name){$values+=,[ordered]@{name=$name;kind=$key.GetValueKind($name).ToString();value=$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}}}}finally{$key.Close()}} + $entries+=,[ordered]@{path=$spec[0];exists=$exists;values=$values} + };return JsonHash $entries +} +function Snapshot{ + $rmm=@();foreach($pair in @(@('RmmDiscoveryWindows','C:\Program Files\RustDiscovery\rmm-agent-windows.exe',$p.agent_sha256),@('RmmDiscoverySystemHelper','C:\Program Files\RustDiscovery\rmm-helper-windows.exe',$p.helper_sha256))){ + $service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'} + $proc=[Diagnostics.Process]::GetProcessById([int]$service.pid);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();$image=$proc.MainModule.FileName}finally{$proc.Dispose()} + if(![string]::Equals($image,$pair[1],[StringComparison]::OrdinalIgnoreCase)){throw 'Actual retained RMM image'} + $binary=FileMeta $pair[1] $true;if($binary.sha256-cne$pair[2]){throw 'Independently pinned RMM binary'} + $rmm+=,[ordered]@{service=$service;process_birth_filetime=$birth;binary=$binary} + } + $files=[ordered]@{};foreach($pair in @(@('config','C:\ProgramData\RustDiscovery\config.json',$p.config_sha256),@('helper_settings','C:\ProgramData\RustDiscoverySystem\helper.json',$p.policy_sha256),@('agent_pin','C:\ProgramData\RustDiscoverySystem\agent-pin.json',$p.pin_sha256))){$value=FileMeta $pair[1] $true;if($value.sha256-cne$pair[2]){throw 'Retained original config/pins'};$files[$pair[0]]=$value} + foreach($pair in @(@('ca','C:\ProgramData\RustDiscovery\server-ca.pem'),@('identity','C:\ProgramData\RustDiscovery\state\identity.json'),@('certificate','C:\ProgramData\RustDiscovery\state\device.pem'))){$files[$pair[0]]=FileMeta $pair[1] $true} + $files['private_key_metadata_only']=FileMeta 'C:\ProgramData\RustDiscovery\state\device.key' $false + $cfg=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\config.json' -Raw|ConvertFrom-Json + if(($cfg.PSObject.Properties.Name-ccontains'enable_jobs')-and$cfg.enable_jobs-ne$false){throw 'No RMM jobs enabled'} + if(($cfg.PSObject.Properties.Name-ccontains'job_binding_file')-and$null-ne$cfg.job_binding_file){throw 'No new job binding'} + $policy=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\helper.json' -Raw|ConvertFrom-Json + if($policy.enable_effects-ne$false-or$policy.allow_reboot-ne$false-or@($policy.allowed_services).Count-ne0){throw 'Closed original helper policy'} + return [ordered]@{rmm=$rmm;original_files=$files;time_service=(ServiceState 'W32Time');selected_time_config_sha256=(TimeConfigHash);time_config_coverage='fixed_service_NTP_and_policy_configuration_values_only'} +} +function BaselineHash($snapshot){return JsonHash ([ordered]@{rmm=$snapshot.rmm;original_files=$snapshot.original_files;time_definition=$snapshot.time_service.definition;selected_time_config_sha256=$snapshot.selected_time_config_sha256})} +function Preserved($before,$after){ + if((JsonHash $before.rmm)-cne(JsonHash $after.rmm)-or(JsonHash $before.original_files)-cne(JsonHash $after.original_files)){throw 'RMM components or original config/PKI metadata changed'} + if((JsonHash $before.time_service.definition)-cne(JsonHash $after.time_service.definition)-or$before.selected_time_config_sha256-cne$after.selected_time_config_sha256){throw 'Service configuration/security or selected NTP/policy values changed'} +} +CheckControl $boot $true +if($p.action-ceq'state'){$snapshot=Snapshot;@{id=$p.id;snapshot=$snapshot;baseline_sha256=(BaselineHash $snapshot);read_only=$true;no_jobs=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return} +if($p.expected_sha256-notmatch'^[a-f0-9]{64}$'-or$p.baseline_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Retained reviewed case hashes'} +if($p.action-ceq'readback'){ + if(!(Test-Path -LiteralPath $folder)){@{id=$p.id;entered=$false;readback_only=$true;start_repeated=$false;current=(Snapshot);clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return} + CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false + $intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json + if($intent.id-cne$p.id-or$intent.expected_sha256-cne$p.expected_sha256){throw 'Exact retained time-service intent'} + $after=Snapshot;Preserved $intent.before $after + $receipt=Join-Path $folder 'result.json';$result=$null;if(Test-Path -LiteralPath $receipt){CheckControl $receipt $false;$result=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json} + @{id=$p.id;entered=$true;readback_only=$true;start_repeated=$false;original_result=$result;start_intent_exists=(Test-Path -LiteralPath (Join-Path $folder 'start-intent.json'));current=$after;preserved=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return +} +if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing start case: readback only, never repeat start'} +$before=Snapshot +if((BaselineHash $before)-cne$p.baseline_sha256){throw 'Exact reviewed baseline changed; do not rebase'} +if($before.time_service.state-notin@('Stopped','Running')){throw 'Pending or unknown time-service state: no start'} +if($before.time_service.state-ceq'Stopped'){$controller=Get-Service -Name W32Time;try{if(@($controller.ServicesDependedOn).Count-ne0-or$controller.Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'No implicit dependency starts or changed service state'}}finally{$controller.Dispose()}} +New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true +WriteNew (Join-Path $folder 'intent.json') @{id=$p.id;expected_sha256=$p.expected_sha256;before=$before;create_only=$true;clock_trust_assessed=$false} +if($before.time_service.state-ceq'Running'){ + $after=Snapshot;Preserved $before $after + $result=@{id=$p.id;status='already_running';start_called=$false;already_running_read_only=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true} + WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Compress;return +} +# Durable local and global admission precede the one exact SCM start. Nothing +# catches/retries the start; an incomplete receipt can only be read back. +WriteNew $active @{id=$p.id;expected_sha256=$p.expected_sha256;service='W32Time';create_only=$true} +WriteNew (Join-Path $folder 'start-intent.json') @{id=$p.id;service='W32Time';start_reserved=$true;observed_at=[DateTime]::UtcNow.ToString('o')} +Start-Service -Name W32Time +$service=Get-Service -Name W32Time +$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20)) +$after=Snapshot;Preserved $before $after +if($after.time_service.state-cne'Running'){throw 'No running-state confirmation'} +$result=@{id=$p.id;status='started';start_called=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true;after=$after} +WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 24 -Compress +''' + +PREPARE = source_stage.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1') +LAUNCH = source_stage.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1').replace('RmmTransportPayload', 'RmmTimeServiceStartPayload') + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def save(folder, name, value): + return helper.store(folder, name, value) + + +def preserve_failure(folder): + path = cb.EVIDENCE / 'bootstrap-private-last-error.json' + if not path.exists(): + return + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + info = os.fstat(source.fileno()) + require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 4 * 1024 * 1024, 'private original bootstrap failure') + raw = source.read() + target = folder / ('retained-bootstrap-error-' + hashlib.sha256(raw).hexdigest() + '.json') + if not target.exists(): + fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(raw); output.flush(); os.fsync(output.fileno()) + + +def remote(folder, payload): + preserve_failure(folder) + try: + return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), 'payload': payload}, timeout=100, remote_signed=True) + finally: + preserve_failure(folder) + + +def prepare(pins): + require(all(re.fullmatch('[0-9a-f]{64}', value) for value in pins.values()), 'independently known retained hashes') + helper.private_dir(STATE); ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700) + source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest() + payload = dict(id=ident, **pins) + save(folder, 'intent.json', {'schema_version': 1, 'type': 'rmm.windows.time-service-start', 'payload': payload, 'source_file_sha256': digest(__file__), 'script_sha256': source_sha, 'closed_central_before': {'path': str(CONTEXT), 'sha256': digest(CONTEXT)}}) + source = folder / 'TimeServiceStart.ps1' + fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno()) + preserve_failure(folder) + try: + helper.transfer(source, 'TimeServiceStart.ps1', source_sha, PREPARE) + before = remote(folder, dict(payload, action='state')) + finally: + preserve_failure(folder) + require(before.get('read_only') is True and before.get('clock_trust_assessed') is False, 'actual readonly baseline') + save(folder, 'before.json', before) + print(json.dumps({'case_id': ident, 'prepared': True, 'time_state': before['snapshot']['time_service']['state'], 'clock_trust_assessed': False, 'start_executed': False})) + + +def run(ident, action): + require(str(uuid.UUID(ident)) == ident, 'exact existing case UUID') + folder = STATE / ident; intent = cb.contract.protected_json(folder / 'intent.json') + require(intent['source_file_sha256'] == digest(__file__) and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same reviewed source; no case rebase') + baseline = cb.contract.protected_json(folder / 'before.json')['snapshot'] + # Powershell creates its canonical baseline hash during state. It is sent + # back verbatim rather than approximating ConvertTo-Json in Python. + payload = dict(intent['payload'], action=action, baseline_sha256=cb.contract.protected_json(folder / 'before.json')['baseline_sha256'], expected_sha256=hashlib.sha256(json.dumps(intent['payload'], sort_keys=True, separators=(',', ':')).encode()).hexdigest()) + require(baseline is not None and digest(CONTEXT) == intent['closed_central_before']['sha256'], 'retained actual baseline and closed central context') + if action == 'start': + save(folder, 'start-attempt.json', {'case_id': ident, 'once': True, 'lost_reply_readback_only': True}) + result = remote(folder, payload) + save(folder, ('result.json' if action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json'), result) + original = result.get('original_result') or result + current = result.get('current') or result.get('after') + print(json.dumps({'case_id': ident, 'status': original.get('status', 'unconfirmed'), 'running': current['time_service']['state'] == 'Running' if current else original.get('status') == 'already_running', 'preserved': result.get('preserved', False), 'readback_only': result.get('readback_only', False), 'clock_trust_assessed': False})) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('action', choices=['prepare', 'start', 'readback']); parser.add_argument('--id') + for name in ['agent', 'helper', 'config', 'policy', 'pin']: + parser.add_argument('--' + name + '-sha256') + args = parser.parse_args() + if args.action == 'prepare': + pins = {name + '_sha256': getattr(args, name + '_sha256') for name in ['agent', 'helper', 'config', 'policy', 'pin']} + require(all(isinstance(value, str) for value in pins.values()), 'all five independent hashes required'); prepare(pins) + else: + require(args.id is not None, 'explicit retained case required'); run(args.id, args.action) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows_signed_clock_linux_acceptance.py b/deploy/windows_signed_clock_linux_acceptance.py new file mode 100644 index 0000000..0d96e2a --- /dev/null +++ b/deploy/windows_signed_clock_linux_acceptance.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +"""Frozen three Windows clock 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/qualification-763baf69-10b1-4307-9c99-6942c0f8945f' +STATE = ROOT / 'devstate/windows-signed-clock-native-linux' +PROFILE = 'rmm.windows-signed-clock.three-linux-guards.v1' +RECEIPT_SHA = 'e013738caed2d8e02b98ffd1b41e47a80840c44d3dbf895e9a3952b4311ce927' +INPUTS_SHA = 'eb4609c5fca6a32ddb8ebf364775efdb59cd89f99a24b3b731212da08eac6a6e' +BINARY_SHA = '0896a3098f493b67b48e774de5cfe9bca682d2a19ff10971c62c9c7b9681ec14' +BINARY_BYTES = 3374576 +TESTS = sorted(['signed_clock::tests::bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters', 'signed_clock::tests::job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case', 'signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution']) +ALL_TESTS = sorted(['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::job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case', 'signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution']) +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 <= 4 * 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) == 184 and source == value['source_files'], 'exact frozen 184 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') + 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-clock-guards-linux-' + 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') + 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']) == 4499436, 'bounded binary transfer') + raw = base64.b64decode(p['binary_b64'], validate=True) + require(len(raw) == 3374576 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed three-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) == 13 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['all_listed_tests'], 'exact full thirteen-test list before three 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'3 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']), 'three native guards with ten filtered and retained target state') + receipt = dict(id=ident, profile=p['profile'], passed=3, ignored=0, filtered=10, listed=13, 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) == 184 + and receipt['kind'] == 'windows-signed-clock-source-qualification-v2' + and receipt['all_source_inputs_preserved'] is True + and receipt['independent_review']['source_sha256'] == '6b66612b7a53377c91bc8e41864ac8fb9393ad40b0a6a98aa6ce746fce091ddb' + and next(x for x in receipt['results'] if x['name'] == 'linux-three-targeted') == dict(name='linux-three-targeted',exit_code=0,passed=3,failed=0,ignored=0,filtered_other_crate_tests=10,tests=TESTS), 'reviewed three-guard 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 / 'qualified-linux-tests' + support.require(receipt['artifacts'][0] == dict(name='qualified-linux-tests', platform='linux', bytes=BINARY_BYTES, sha256=BINARY_SHA), '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['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/agent-updater-linux-native-results.md b/docs/agent-updater-linux-native-results.md index 877bb86..48509ec 100644 --- a/docs/agent-updater-linux-native-results.md +++ b/docs/agent-updater-linux-native-results.md @@ -1,4 +1,4 @@ -# Linux-Updaterport: nativer Fünfertest bestanden +# Linux-Updaterport: native Fünfer- und Sechsertests bestanden 2026-11-14. Dieser Schritt prüft ausschließlich die fünf isolierten OS-Units des Linuxports. **Auf der Cloud-VM als UID0 bestanden:5/5, kein Skip/Filter.** Kein Apply-, Autoupdater- oder @@ -121,3 +121,86 @@ Dieser isolierte Unitlauf ändert diese Einstellung nicht und belegt keine Bereitschaft nach einem Neustart. Keine RMM-Jobs oder Servicekontrolle. Der MVP einschließlich Windows und vollständigem Selbstupdater ist weiterhin nicht abgeschlossen. + +## Separater lesender Dienstkontextbefund + +Nach dem isolierten Fünfertest wurde im eigenen Fall +`accb1ce1-9cbc-4301-bdfb-04a310c9e5a5` ausschließlich der tatsächliche +General-/Full-Prozessstatus gelesen: gleiche Usernamespace, aktuelle Images +jeweils79442727, stabile PID/Geburt/Invocation-ID vor und nach dem Lesen. +General-CapEff enthält weder die gesamte Full-CapPrm-Menge noch CAP_SYS_PTRACE. +Resultat-SHA256 `9c1629d6ec0d821b50912a2cb6932b6f263c945649a341c7b8f312832aac70c2`. +Keine neue Prozesseigenschaft, Unit, Capability oder Konfiguration verändert. + +Der Kernel verlangt beim entsprechenden Prozesszugriff eine ausreichende +Capabilitymenge oder CAP_SYS_PTRACE +([commoncap-Implementierung](https://github.com/torvalds/linux/blob/master/security/commoncap.c)). +Daraus folgt eine konkrete Integrationsgrenze für die gegenläufige +General→Updater→Full-Imageprüfung. Das ist eine aus tatsächlichen Masken und +Kernelvertrag abgeleitete Einschränkung; **kein im echten Generalkontext +bereits ausgeführter Open-/IPC-Nachweis**. Die Unitprobe ersetzt diesen nicht. +Konkrete Rollen-/Dienstkonfiguration und tatsächlicher wechselseitiger +Peerzugriff müssen vor Bootstrap geklärt werden. Kein PID-/Pfadfallback und +keine vorsorgliche Lockerung der Generalhärtung. + +## Herkunft nach Zusammenführung des Quellencheckpoints + +Die sieben OSportdateien dieses nativen Nachweises sind im gepushten +Checkpoint1e89c45 bytegleich erhalten. Von den22 eingefrorenen Eingaben stimmen +17 mit dem zusammengeführten Stand überein; fünf Domaininputs wurden für die +spätere Plan-/Health-/Provisionierungsintegration erweitert. Der neue gesamte +Workspace ist damit nicht pauschal nativ qualifiziert. Seine separaten lokalen +Compiler-/Prüfbelege bleiben von diesem ursprünglichen Fünfertest getrennt. + + +## Neuer Sechsernachweis nach gebundenem Stage-Reopen + +Der getrennte Quellenstand328e440 (Mainmerge7d328ee) ergänzt das gebundene +Wiederöffnen eines bereits verifizierten Stagings. Der neue Runner +`deploy/updater_linux_reopen_acceptance.py`, SHA256 +`8a27924b829946e24e9870b9e6af71508dee6495ee7840c51f809cfecf94c10a`, +bindet23 eingefrorene Inputs und die neue Sechserexe:1555392Byte, SHA256 +`c78d24d9b3f543fc4eba3fa1d02bf82e72aea26493ae689f2fc82ee1067d33fc`. +Der lokale Qualifikationsreceipt hat SHA256 +`c3e1ee619ef01630b296aaf7669d04f39ea952b1ec2d7adc1a791f69f6a6ee08`. +Die sieben OSportquellen entsprechen diesem öffentlichen Stand; spätere +Worker-/Runtimeänderungen sind dadurch nicht qualifiziert. + +Die ursprünglichen fünf Namen bleiben enthalten. Hinzu kommt exakt +`files::reopen_tests::bound_reopen_rejects_same_byte_name_substitution_and_added_stage_hardlink`. +Die Probe verwendet ausschließlich ein eigenes geschütztes UUID-Verzeichnis +unter `/run`: positive interne FD-Prüfung, Verweigerung eines gleichbyteigen +Namensaustauschs sowie eines nachträglich hinzugefügten Hardlinks. Der öffentliche +API verweigert den Fixture-Elternpfad. Noch kein positiver Produktpfadtest, +keine Autorität zur Wiederaufnahme eines unklaren Applys. + +Der erste lokale Prepareversuch stoppte vor Fallanlage und SSH: Das vom +Sourceworker erzeugte private Qualifikationspaket hatte zu offene Rechte +(Verzeichnisse775, JSON664). Im gesonderten lokalen Reparaturfallf3c44696 wurden +46 eigene Objekte auf700/600, die qualifizierte Exe auf500 begrenzt; Besitzer, +Inodes und Dateibytes blieben erhalten. Der Reader wurde nicht gelockert. +Erst danach entstand der neue Originalfall349ffb0b-ec46-4eb0-b0e6-0867f3cd392b. + +Tatsächlich einmal ausgeführt, anschließend separat nur gelesen: + +```sh +python3 deploy/updater_linux_reopen_acceptance.py prepare +python3 deploy/updater_linux_reopen_acceptance.py execute --case 349ffb0b-ec46-4eb0-b0e6-0867f3cd392b +python3 deploy/updater_linux_reopen_acceptance.py read --case 349ffb0b-ec46-4eb0-b0e6-0867f3cd392b +``` + +Ergebnis auf der Cloud-Linux-VM als UID0: **6/6,0ignored/filtered, Exit0**. +Originalmanifest SHA256 +`3278a9ffbcbf460f2304f570165a4c6cb4292ef22604b9639af82088ef9b046c`; +Execute-Beleg SHA256 +`0d9a522d7e25d49af47bbe4950bde544a0f84ba9d40a8f60d067512a9638433b`; +separater Readback SHA256 +`4fc2f86a18b83bfa536d1d657eee87304db8c7ce096459c5f366940241e0b6ba`. +Die bekannten Prozess-, Boot-, Kontrollbyte- und Dateiidentitätszeugen waren +vor/nach sowie beim Readback gleich. APT inaktiv/disabled; Full aktiv, weiterhin +Autostart disabled. Keine Dienststeuerung, RMM-Jobs oder Produktdateitausche. +Der eingefrorene Fünferrunner und sein ursprünglicher Beleg bleiben unverändert. + +Auch dieser Nachweis belegt keine vollständige SQL-/PKI-Historienprüfung, +keinen geschlossenen Readercensus und keine vollständige Apply-/Health-/ +Rollbackstrecke. Windows und der Selbstupdater bleiben offen. diff --git a/docs/development.md b/docs/development.md index 1b10fb3..73bc957 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Linux-first-Entwicklung und reale VM-Abnahme -Stand: 2026-11-14 · Spezifikation 1.21. Das begrenzte Linux-MVP ist inzwischen +Stand: 2026-11-14 · Spezifikation 1.22. Das begrenzte Linux-MVP ist inzwischen dokumentiert abgenommen; aktuelle Nachweise stehen in [handover.md](handover.md). Die getrennte Windows-SYSTEM-Grenze ist in Spezifikation0.1 und [windows-system-policy.md](windows-system-policy.md) präzisiert; Quellen-/Build- @@ -17,6 +17,22 @@ Deploymentnachweise: [server-deployment.md](server-deployment.md). Die folgenden PC-Server-/Reverse-Tunnel-Abläufe und Nachweise sind historisch. TLS/mTLS, Credentialschutz, Linux-first und WebUI-Plangenehmigung gelten weiter. +## Unabhängiger signierter Windows-Zeitvergleich (Version1.22) + +Der User erlaubt ausdrücklich den signierten Onlinevergleich mit dem festen +Server. [Angenommener Vertrag](windows-clock-attestation-proposal.md) und +SpezifikationKapitel0 ersetzen den früheren Ausschluss dieser Trustsource. +Agent und SYSTEM-Helper halten eigene Challenges, Beobachtungen und geschützte +Zeitpins. W32Time-Rohstatus bleibt separat; kein Clocksetter oder impliziter +manueller Resync. Fehlende native Server-/Windowsqualität sperrt weiter Jobs. +Ein signierter Zeitbeleg ersetzt weder SignedSync noch Startgrant oder WebUI. + +Zuerst reale Cloud-Linux-Prüfungen des gemeinsamen Vertrags und der Serverquelle, +danach Windows getrennt je tatsächlicher Identität. Isolierte Codecunits belegen +keine reale Zeitqualität. Caller dürfen die gesamte frische UTCspanne nicht auf +einen ungesicherten Mittelpunkt reduzieren; Start- und Syncablauffristen müssen +konservativ eingehalten werden. Notebook bleibt nur Entwicklung. + ## Enger paralleler Agentupdater (Version1.21) Der User hat signiertes Agent-Selbstupdate parallel vorgezogen. Es bleibt ein diff --git a/docs/handover.md b/docs/handover.md index 1479235..31d95b7 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -1,5 +1,163 @@ # Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt +**Windows-Zeitguards Linux-first bestanden:** Originalfall6ea36dec, +volle13er-Liste geprüft, ausschließlich neue3Tests bestanden/10andere bewusst +gefiltert; separater Readback vollständig, bekannte Runtimezeugen erhalten. +Geschütztes Verifiermodul6b66612b unabhängig geprüft und lokal Windowsgelinkt; +[Nachweise und Grenzen](windows-signed-clock-source.md). +Keine Windowszeit-/Jobbereitschaft; Rohcapturequalifikation folgt separat. + + +**Aktueller Zeitcodec-Endpunkt nativ geprüft:** Die Audiencekorrektur auf +/agent/v1/time-attestation hat einen eigenen Linuxfall a22de8d2 mit4/4 und +separatem vollständigem Readback; Originalfall2b282376 unverändert. +[Belege](signed-time-contract-results.md#nachfolgender-quellenstand-tatsächlicher-agent-endpunkt). +Linux-Providerquelle lokal4/4 plus unabhängiger Review bestanden; noch kein +nativer Chrony-/Kernelprovider. Ein getrennter lesender Serverkernelbefund +meldet state0/flags0/maxerror55.773ms; keine gemeinsame Qualitätsabnahme oder +Clockgateöffnung. [Grenzen](server-time-source.md). + + +**Signierter Zeitvergleich, erster tatsächlicher Linuxbeleg:** Gemeinsamer +Codec/Verifier nach Nonce-Replayfix im Originalfall2b282376 nativ4/4 bestanden, +separater Readback abgeschlossen, bekannte Runtimezeugen erhalten. +[Ergebnisse und klare Integrationsgrenzen](signed-time-contract-results.md). +Keine Server-/Windows-Zeitqualifikation oder Jobgateöffnung; Audiencepfad vor +Transportintegration noch an bestehenden /agent/v1-Vertrag angleichen. + + +**Userentscheidung1.22:** Signierter unabhängiger Windows-Zeitvergleich mit +festgelegtem Server ausdrücklich zur Umsetzung erlaubt; Agent und SYSTEM +prüfen separat, fehlende Qualität sperrt. Normativ Kapitel0/Projektentscheidungen, +[angenommener ADR](windows-clock-attestation-proposal.md). Keine Uhrstellung, +kein impliziter manueller Resync und noch kein Clockgatewechsel. + + +**Neuer nativer Linux-Sechsernachweis:** Quellenstand328e440/Main7d328ee, +Originalfall349ffb0b, Cloud-VM UID0:6/6 ohne Skip/Filter; separater Readback +abgeschlossen. Ein vorheriger lokaler Rechtefehler stoppte vor SSH und wurde +unter Erhalt von Inodes/Bytes behoben. Details samt Belegshashes: +[Linux-Updaterport](agent-updater-linux-native-results.md#neuer-sechsernachweis-nach-gebundenem-stage-reopen). +Keine Apply-/Rollback-/Windowsqualifikation; Full weiter Autostart disabled. + + +**Quellencheckpoint1.21, noch kein Runtimewechsel:** Der zusammengehörige +Updaterstand `1e89c45` ist geprüft und nach Gitea gepusht, anschließend in Main +zusammengeführt. Neue Plan-/Healthschlüsselbindung, atomarer Handoff samt +nativen Effect-CAS, Serverkatalog/Streaming/WebUI, separat signierte +Baseline-/Policycodecs und erste konkrete Worker-Fence-/Truststrecke sind im +Quellcode. Quelle allein eröffnet keine Capability. Tatsächlich lokal: +Core64/64, Domain23/23, Server45/45; fünf bestehende DB-Harnessprüfungen explizit +ignored. Gemeinsames Targetcheck, Clippy mit verweigerten Warnungen und +Formatcheck bestanden. Worker1/1 mit echter Baselinesignatur und gezieltem +historischem Floor-Gegenfehler; Kandidat weiter strikt aktuell/über Floor. +Receipt `bdcfb1b319398899cbadd1101255f4dc25108455d665a197ddcbe993080c1870`. + +Die bis dahin gemeldeten beiden Reviewfehler sind geschlossen: historische +Baselineprüfung verlangt die exakte aktive Manifestbindung; Record-Publish +muss dasselbe beobachtete Save-Hashpaar benutzen. Die sieben OSportdateien +stimmen bytegleich mit dem tatsächlich nativ geprüften Fünfersnapshot überein; +fünf Domaininputs wurden danach erweitert. Der gesamte neue Quellencheckpoint +hat deshalb **noch keinen neuen vollständigen Linux-/Windows-VM-Nachweis**. +Aktuelle laufende Cloudimages/Indizes bleiben die separat dokumentierten alten +Runtimegenerationen. Konkrete Fullbridge-/Ownerguards, vollständige Engine, +Baselinebootstrap, Updated-Recordhistory, Rollbackvertrag und tatsächlicher +WebUI-genehmigter Apply bleiben offen. Kein aktiver Selbstupdater. + + +**Aktueller Nachtrag2026-11-14:** Linux-Skriptkonsole ist nativ bestanden; +Windows und der vollständige Agent-Selbstupdater sind noch nicht abgeschlossen. +Nach dem Acht-Handoffkern bestand auch der Linux-OS-Port nativ5/5 mit separatem +Readback, ohne RMM-Job, Dateitausch oder Dienststeuerung +([Ergebnis](agent-updater-linux-native-results.md), Giteac35c440). +Der private aktuelle Linuxruntimeindex wurde im eigenen lokalen CAS-Fall99048876 +nach Erhaltungsnachweis fortgeschrieben (SHA256 +`4b98189f68b1671ed64b9ed0ab808fc53f43b2a819f5044d7e81796d8a5bb25a`). +Er ist Herkunftsindex, kein signierter Release-/InstalledRecord und keine frische +Zielbeobachtung. Darin ausdrücklich: Fullhelper aktiv, **Autostart disabled**; +keine Bootbereitschaft behaupten. Der Server-Herkunftsindex ist anschließend lokal exklusiv unter +`devstate/cloud-server-current-runtime.json` angelegt und nachgelesen +(SHA256 `671913a8e97bcf137b08fee5f5700541a42856f98744289b562e33df9ae56d98`). +Er bindet Originalmanifest43d4af86 und akzeptierten Postdeploybeleg5df21b55 +aus Fall14dcc27d: Image6f8383f7/Migration14 und exakte Webdateien. +Kein neuer Zielaufruf, keine aktuellen Job-/Policywerte aus alten Deploydaten +übernommen. Historische Indizes unverändert; kein signierter Releasebeleg. + +Windows: Privilegaktivierung allein beseitigte RPC5 nicht; der getrennte +Impersonate3-Vergleich erreichte danach eine echte Statusquery mit RPC0/Stage80. +Dies qualifiziert weder Dienstidentität noch Zeitbereitschaft. Die erste +QOS5-SID-/Service-Descriptorprobe scheiterte vor der Query mit87/Stage30 +([Befund](windows-clock-identity-result.md)). Produktclock/Windowsjobs bleiben +geschlossen. Der lesende native W32Time-Status meldete Leap3/Stratum0; zwei +separate NTPantworten sind kein Synchronisierungsbeleg. Manueller Resync bleibt +bis zur konkret angefragten Userantwort unausgeführt. Die nachfolgende +Descriptorprobe ist einschließlich separater Cleanupauflösung dokumentiert: +[Originalfehler und Erhaltung](windows-clock-descriptor-result.md), +[statische Runtimeursache](windows-clock-rpc-qos5-analysis.md). Ein signierter +Serverzeitvergleich ist inzwischen [ausdrücklich angenommen](windows-clock-attestation-proposal.md); +Implementierung und Qualifikation stehen noch aus. + + +**Fortschreibung2026-11-14 nach tatsächlicher Skriptabnahme:** Die vollständige +MCP→WebUI→Rootskriptstrecke ist auf der Cloud-Linux-VM bestanden. V2-Fall +ced97b4d, ursprüngliche Plan-/Skriptbytes in der WebUI verglichen, +SIMULIERT-Freigabeklick, genau ein erfolgreicher UID0-Lauf; stdout28/stderr27 +Byte auch tatsächlich über die WebUI heruntergeladen und verglichen. +MCP-Ergebnis identisch, zwei authentisierte Fremdmandantenabfragen verweigert. +Root19/0, ServerLinux31Jobs/31Outbox/27Grants/0ungeklärt; Windows weiter0/0/0/0. +Beide temporären Rootscopes geschlossen, Originalpolicycf15cbb6 lesend +bestätigt. Details und Grenzen: [Linux-Skriptresultat](script-console-linux-full-results.md), +Gitea76440e1. Vollständiger dreiteiliger passiver Nachbeleg ebenfalls bestanden, +Giteaefd310b. Automation hat explizit root:execute erhalten, keine +Genehmigungsrechte. Noch offen bleiben Windowsclock/PowerShell/SYSTEM, +Selbstupdater-Runtime und native Applynachweise. Die oben ergänzten privaten +Linux-/Server-Herkunftsindizes lösen den früher offenen Indexabgleich, keine +neue Runtimequalifikation. Ältere Angaben darunter sind historische +Zwischenstände. Kein vollständiger Windows-/Updaterabschluss. + +**Windowsclock-Nachtrag:** SPNEGO liefert tatsächlich einen nicht-NULL leeren +Principalnamen. Erst die eigene ursprüngliche Nichtleerprüfung stoppte vor RPC; +der neue getrennte Empty-Case5e0e8ce9 führte genau eine Query aus und meldete +weiter RPC5/Stage90 ohne Status. SeSystemtimePrivilege ist im Diagnoseprozess +vorhanden, aber deaktiviert; das beweist noch keine alleinige Fehlerursache. +Readback, Cleanup und sechs unveränderte native RMM-Bereiche bestätigt; Windows +weiter0/0/0/0. Der parallele Linuxjob erklärt explizit31/31/27 statt30/30/26. +[Tatsächlicher Beleg98f4edf](windows-clock-spnego-empty-trace.md). +Der nächste isolierte Prozessprivilegvergleich ist noch kein Zielnachweis. + +**Updater-Kernnachtrag:** Acht feste Handoff-/Fullrenderer-/Healthverträge aus +a2efb79 sind danach tatsächlich auf Cloud-Linux als UID65534 bestanden, +kein Skip/Filter; separates lesendes Readback und bekannte Dienst-/Kontroll-/ +Stateidentität erhalten. [Ergebnis und Grenzen](agent-updater-handoff-linux-results.md). +Keine Applyruntime oder Windowsqualifikation daraus ableiten. + +**Vorheriger Betriebsstand der Skriptkonsole2026-11-14:** Cloudserver und WebUI +sind im separaten Fall14dcc27d tatsächlich erhaltend bereitgestellt (ARM64-Image +6f8383f7, Migration14; alte Geschichte/Identitäten unverändert). Die drei neuen +Linux-Dienste Agent0a7ad6ee sowie General/Full79442727 laufen nach einmaligen +Starts und separatem Readback, gleicher Boot; APT bleibtdisabled. Ursprüngliche +Installer-/Startprobeberichte bleiben fehlgeschlagen und erhalten. Quellen und +Nachweise jeweils nach Gitea gepusht: [Bereitstellung](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/cfd32ea/docs/script-console-bootstrap-results.md). +Aktuelle Skriptunits danach auch nativ Windows36+7 bestanden, keine Skips; +[Beleg5b2f07b](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/5b2f07b/docs/script-console-windows-link.md). +Ein erster lesender Linux-Historien-/SignedSyncnachweis ist bestanden; der +vollständige dreiteilige passive Nachbeleg wird noch vervollständigt. Neue WebUI +privat mit geprüftem TLS und Sandbox sichtbar als SIMULIERT angemeldet, kein +neuer Job/Approval. Windowsclock weiterfalse, Updater weiterhin nur Prüfkern. +Die alten privaten Runtimeindizes nicht als Pins der neuen Linux-Generation +verwenden; deren Fortschreibung folgt erst dem vollständigen Nachbeleg. + +**Fortschreibung2026-11-14:** Die parallele Weiterarbeit an Skriptkonsole, +Windowslaufzeit und Agent-Selbstupdater ist ausdrücklich beauftragt. +Der Windowszugang wurde tatsächlich wiederhergestellt und vollständig erhaltend +geprüft. Pipe-v2-Paarupgrade14fb ist inzwischen nativ bestanden; aktuelle +Agent-/Helpergenerationf10c78dd/5f8c62fa läuft, Pipepeerprobe positiv, +Clock/Jobs/Wirkungen bleiben gesperrt. Linux10→Windows42-Runtimeunits bestanden; +erster Harnessfehler bleibt dokumentiert. Microsoft-MIDL-Codegen nativ +abgeschlossen, noch keine positive Clockabnahme. Quellen-/Prüfstände und offene +Integrationsschritte: [paralleler MVP-Stand](parallel-mvp-status.md). +Die älteren gegenteiligen Zwischenstände unten sind historische Belege. + **M0–M5 sind im vereinbarten begrenzten dev/test-Umfang vollständig nachgewiesen.** Linuxabschluss unter Spezifikation1.15; aktueller Gesamtvertrag ist1.18. Umfang und Grenzen der Linuxabnahme stehen in @@ -53,17 +211,142 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Neue isolierte Quellenstände (jeweils nach Gitea gepusht, **keine neue +Windows-Runtime oder Cloudserverbereitstellung daraus ableiten**): + +- `codex/windows-msi-integration`/`ae82b27`: Spec1.19, striktes MSI-Manifest, + Tenantkatalog/Migration0014, exakte automatische Artefakt-/Rezeptmengen und + separate SYSTEM-Paketerlaubnis; unabhängig geprüft. Lokal118Rust/PG1 und + UI42/Typecheck/Build bestanden. Echte synthetische Rust-Planbytes1.0/1.1 + prüfen die UI; der zuerst gespiegelte None-/Null-Fehler ist korrigiert. + Anschließend **Cloud-Linux101 nativ bestanden**, Fall `d015f861…`, Manifest + `2d96a07b…`, Proof `09fa24e3…`. Danach **Windows79 nativ bestanden**, Fall `1b1aeff3…`, + Proof `666ed196…`, gleicher Manifest-/Linuxproofbezug. + Cache-/Helper-/Runtimeintegration im separaten `codex/windows-msi-runtime` + /`287a784` implementiert/unabhängig geprüft: deny-onlyCancel, geschützter + Cache, Originalbudget und Erhaltung unklarer Installerhandles. Lokal10 plus + WindowsClippy/Link bestanden; nativeCloud-Linux10 ebenfalls bestanden (050c33bd…, + 620255bc…/679ac094…), Windows35+7 noch erwartet. Keine Paketwirkung oder Capability veröffentlicht. +- `codex/windows-clock-diagnostic`/`ae9b271`: Trace nativ im Fall `2996df8c…` + bestätigte1783 als aufgefangene RPC-/NDR-Ausnahme vor normalem Stubreturn, + nicht eigenen Strukturguard (`572d70e1…`). Neuer lokal geprüfter WIDL- + Pointerkandidat `91889303…` erzeugt ref→unique statt ref→ref. Die komplette + Microsoft-IDL zeigt mit WIDL7 denselben rekursiven Attributfehler; kein + manueller Stubbytepatch. Kandidat danach **nativ ebenfalls fehlgeschlagen**, Fall `79896ca7…`: weiter + Named-Pipe1783/Stage90 ohne Status, ALPC1753; isolierter Dienst entfernt, + Erhaltung/geschlossene Zähler bestätigt (`fceb92c2…`). Clockfalse. Nativer + Microsoft-MIDL-Codegen ohne Installation mit festen zwei SDK-Tools vorbereitet + und lokal geprüft; noch nicht auf Windows ausgeführt. +- `codex/windows-pipe-drain`/`fc2d01d`: eigener V2-Endpunkt und begrenzter + Transport-Drain-ACK implementiert/lokal geprüft. Neuer Pack `59623db2…`, + Manifest `b2f77713…`, **23+7Windowsunits nativ bestanden**, Fall + `db25cd4a…`; keine RMM-Jobs, Produktdateien oder Dienste geändert. + Paarupgrader e4665766… separat geprüft: alle drei Befunde behoben. Fall14fb… + nach erstem180sStagingtimeout nur nach echter Abwesenheitsprüfung in seiner + unerreichten ersten Phase fortgesetzt, Baseline57b79e9c… gewonnen. **Kein + Enter/Stop/Swap/Start**; unveränderte aktuelle Generation890/e6, HelperStopped. + +Manueller Windows-Konsolenneustart nach konkreter Zeitabstimmung vom Benutzer +als abgeschlossen bestätigt und nativ nur lesend nachgewiesen: Boot +2026-11-14T12:26:50.5000000Z, Fall `d888645b…`, Bericht `ab4a99b7…`. +Agent89004ad3 läuft als LocalService/Auto mit neuem PID3172; Helpere6aacbdd +und W32Time waren entsprechend ihrer unveränderten Manual-Startart gestoppt. +Danach W32Time gezielt mit bestehender Userfreigabe im separaten bootgebundenen +Fall203ce31a… einmal gestartet und identisch lesend bestätigt (badcc320…); +Helper weiterhinStopped, keine Startart-/NTP-/ACLänderung oder RMM-Jobs. +WU-Neustartmarkerfalse, CBS-Neustartmarker weiterhintrue. Kein Remote-Reboot, +keine Startartänderung, kein Installer; MSVC bleibt deshalb gesperrt. Die alten +PIDs8108/2620 unten sind historische Wartungsbelege, keine aktuelle Baseline. +Windows79-Vertragstests anschließend nativ nach dem Linux101-Beleg bestanden. +Der bisherige Dev-Reversetunnel lief2026-11-14T12:55:31UTC ab. Zwei neue +Readonly-Bootstrapfehler verhinderten rechtzeitige Erneuerung, dritter lokaler +Fristguard ohne Zielaufruf; keinerlei Renewal-Enter oder Worker. Danach eigener +Server-only-CAS im Fall4b6506a7…: gleicher restriktiver Key und gleiches SSH- +Profil, neue Frist2026-11-15T13:05:58UTC. Windows-Konsolenphase ist per +asynchroner Benutzeranweisung angefragt, noch nicht bestätigt oder nativ +nachgewiesen; noch kein neuer Windowszugriff oder lokaler Accessmetadatenwechsel. +Öffentliches Recoverypaket7bf4… zuerst separat publiziert, dann wegen unbelegter +Accountzeit-Rundung gezielt zurückgezogen. Neuer eigener Präzisionsfall5c96d3d8… +leitet genau einen Sollwert aus Originalcfg-UTC ab (kein VM-Messwert, keine +Toleranz), gleiche bereits ausgeführte Serverfreigabe. Neuer öffentlicher +ZIPdbcd5ca8… bis14:17:54UTC tatsächlich publiziert/extern mit normaler TLS-Prüfung +verifiziert; eigener neuer Close-Timer aktiv für14:17:54UTC, alter Downloadtimer +tatsächlich inactive/disabled. Letzter lesender Servernachbeleg: kein Windows- +Reverselistener. Aktuelle Benutzeranweisung ersetzt alte Rückfrage; Details: +[Korrektur](windows-recovery-precision-download.md). + +Gemeinsame passive Komponentenwartung nach dokumentiertem ersten APIfehler +abgeschlossen, Originalfall `6d2df065…` und separate Recovery `595dd1da…`. +ActualAgent `89004ad3…` LocalService/Auto PID8108; Helper `e6aacbdd…` +SYSTEM/Manual PID2620; Policy `007adf5f…`, Pin `126670bc…`. Alle vier Dateien +mit expliziten Nativebackups und Datei-ID-/ACL-/Frozenprüfungen ersetzt, +danach beide eigenen Dienste jeweils einmal gestartet. Zwei frische WSS- +Heartbeats, konkretes Inventar-ACK, Tenantverweigerung und Erhaltung bestanden. +Runtime-/Komponentenindex per CAS veröffentlicht; Ursprung/Fehler/Backups erhalten. +Abschluss `ac00411f…`, Recoveryacceptance `5ad5925c…`. Keine Jobs/Bindings, +Clockfalse, Wirkungen/Rebootfalse, Intentablage weiter0B. Die ursprünglichen +Stoppedabschnitte unten sind jetzt historische Zwischenstände. + +Positive Pipeabnahme weiterhin **fehlgeschlagen**: tatsächlicher neuer Agent +8108 meldet `client_read_reply`/`HELPER_PIPE_IO`/Win32233; privater Helper- +Diagnosebeleg fehlt. Das grenzt den Clientpfad ein, beweist aber keine konkrete +Serverursache. [Wartung/Recovery](windows-system-delegation-upgrade.md). + +Clockkandidat nach W32Time-Start tatsächlich nativ ausgeführt, Fall `e1f3edbb…`: +LocalService bestätigt, beide ALPC-Proben1753, kein Endpunkteintrag; beide +Negativkontrollen ebenfalls1753, kein Identitätsnachweis. Named-Pipe-Diagnose1783 +ohne Status, Ursache noch unbewiesen. Originalbericht separat identisch gelesen, +eigener temporärer Dienst entfernt, Zentralstände/Flags erhalten. Clockabnahme +**nicht bestanden**, Gatefalse und keine Jobs. Microsoft spezifiziert für +MS-W32T Named Pipes, keinen zugesicherten ALPC-Endpunkt. [Native Details](windows-clock-readiness.md). + +Vorhandenes W32Time ausdrücklich autorisiert einmal gestartet, nativer Fall +`c3552c3f…`: Running und unveränderte RMM-PIDs5140/6240, Konfiguration, +PKI-Metadaten und Dienstdefinition bestätigt. Getrennter Readback identisch, +Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene Flags erhalten. Kein +Uhrqualifikations- oder Rebootbeleg; `ADAPTER_QUALIFIED=false`. [Startnachweis](windows-time-service-start.md). + +Separater M3-Branch `codex/windows-eventlog`, Commit `eb38b4b`: fester +Application-/Fixtureprovider, begrenzter authentisierter Worker und sichtbarer +hashgebundener Plan implementiert und unabhängig geprüft. Lokal238Rust, +isolierterPG-Fall und38Webtests/Build/Clippy bestanden; anschließend nativ +Cloud-Linux24→Windows23 ohne Skips, Manifest `ed1371e9…`, Fälle `6f9bdfb7…` +und `ccb258a7…`. Quellen und beide Abnahmeschritte jeweils gepusht. Dies sind +Vertragsunits, keine tatsächliche LocalService-Eventlog-Abfrage oder Jobwirkung. +Keine Capability aktiviert, keine Runtime ersetzt. [Quellen und genaue Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-eventlog/docs/windows-eventlog-source.md). + +Separater Profilbranch `codex/windows-powershell-profile`, Commit `207b91f`: +RemoteSigned als optionales festes Aktions-/Variantenfeld implementiert, alte +Bytes erhalten, UI-Planansichten streng gebunden. Lokal Rust-/Server-/35Web- +Prüfungen bestanden; danach nativ Cloud-Linux23 ohne Skips, Fall `f463acc9…`, +Manifest `26247a3a…`. Anschließend nativ Windows22 ohne Skips bestanden, +Fall `9abd3e0d…`, Proof `47cee8c9…`, an denselben Linuxbeleg gebunden. Keine +Profilcapability veröffentlicht und kein PowerShelljob gestartet. Der +Hauptcheckout bleibt für die Komponentenwartung unverändert. Quellen/Nachweise: +[Profilbranch](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-powershell-profile). +Ein separat tatsächlich bestätigter Schemars-Nullable-Metadatenunterschied +betrifft keine Berechtigung; sein enger Attributfix wird im isolierten folgenden +M3-Schnitt mitgeführt. Der ursprüngliche Nativebeleg wird nicht umgeschrieben. + Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung; manueller VM-Konsolenneustart erst nach konkreter Zeitabstimmung. Keine Remote- -oder RMM-Rebootfreigabe. Umsetzung des optionalen Skriptprofils noch offen. +oder RMM-Rebootfreigabe. Profilquelle und Vertragsunits im oben genannten +isolierten Branch vorhanden; tatsächlicher genehmigter Job weiterhin offen. [Begrenzter Vertrag](windows-powershell-policy.md). Gemeinsamer Upgradefall `6d2df065…` bisher vor dem Server-Beforecheckpoint abgebrochen, kein Enter-/Stop-/Swap-/Startintent. Bestehender RMM-Agent meldet weiter Heartbeats; Reverse-Tunnellistener vorhanden, aber TCP-Weiterleitung -liefert derzeit kein SSH-Banner. Kein Upgradefortschritt daraus ableiten. +lieferte zunächst kein SSH-Banner. Ein eng begrenzter Devtransport-Reset im +Fall `eed7dad0…` beendete genau den separat identifizierten Tunnel-Sessionchild +über sein gepinntes Prozesshandle; kein SSH-Master-/UID-Reset. Der bestehende +Windowsloop stellte den Listener neu her; Anmeldung mit unverändert gepinntem +Windows-Hostschlüssel und lesender Nachbeleg bestanden. Agent5140 und Helper6240 +laufen unverändert, W32Time weiterhin gestoppt. Ursache der ursprünglichen +Bannerblockade unbewiesen; keine neue Schlüssel-/Port-/Expiryfreigabe und kein +VM-Neustart. Kein Upgradefortschritt daraus ableiten. Konkrete Zeitabstimmung für den bereits zugesagten manuellen Konsolenneustart wurde angefragt; bis zur Antwort keine Ziel-Neustartaktion und keine Annahme eines erfolgten Neustarts. Aktuelle Artefakte weiterhin2bee/921c. diff --git a/docs/parallel-mvp-status.md b/docs/parallel-mvp-status.md new file mode 100644 index 0000000..924d6f4 --- /dev/null +++ b/docs/parallel-mvp-status.md @@ -0,0 +1,167 @@ +# Parallele MVP-Fortsetzung2026-11-14 + +**Updater-Quellenfortschritt1.21:** Gemeinsamer Checkpoint1e89c45 ist gepusht +und nach Main integriert. Server/Katalog/Streaming/UI, Healthpfad bei Ready=false, +Corehandoff/native CAS, geschützte Provisionierungscodecs und erster konkreter +Linuxworker sind implementiert und lokal geprüft. Core64, Domain23, Server45; +fünf DB-Harnessfälle ausdrücklich nicht ausgeführt. Check/Clippy/Format bestanden. +Worker-Signatur-/Floor-Gegenbeleg1/1. Siehe [Workerumfang und Grenzen](agent-updater-worker.md). +Noch keine neue Runtimebereitstellung, keine Applycapability und kein echter +Agent-Austausch. Baselinebootstrap, konkrete komplette Engine/Fullguards, +Updated-Recordhistory und Rollback bleiben offen; Windowsclock weiter geschlossen. + + +**Neuester Stand:** Linux-Skriptkonsole einschließlich MCP-Antrag, tatsächlicher +simulierter WebUI-Freigabe und Rootausführung ist bestanden. Windows und der +vollständige Selbstupdater bleiben offen. Linux-Updaterkern8 sowie isolierter +Linux-OS-Port5 sind inzwischen nativ und mit getrenntem Readback bestanden; +[OS-Ergebnis](agent-updater-linux-native-results.md). Das ist kein Applynachweis. +Der private Linuxruntimeindex ist erhaltend fortgeschrieben; Fullhelper läuft, +sein Autostart ist weiterhin deaktiviert. Windows-Impersonate3 liefert erstmals +RPC0/Stage80, die notwendige zusätzliche Dienstidentität ist nicht qualifiziert. +Erste QOS5-Bindung meldet87 vor jeder Query; W32Time war im separaten lesenden +Status unsynchronisiert. Keine neue Windowswirkung und keine Clockfreigabe. +Alle älteren Zahlen darunter gehören zu ihren jeweiligen historischen Schritten. + + +Der Benutzer hat die parallele Umsetzung ausdrücklich beauftragt. Schwerpunkt +ist die Skriptkonsole: AI/MCP hinterlegt vollständige Shell-/PowerShellskripte +als feste Anträge; erst die WebUI-Genehmigung erlaubt den genau gebundenen +Root-/SYSTEM-Versuch. Passive Heartbeats/gespeicherte Telemetrie bleiben davon +getrennt. Das Notebook ist ausschließlich Entwicklungsrechner, Linux läuft auf +der Cloud-Test-VM, der permanente Server ist discovery.ease-technologies.de. + +## Tatsächliche neue Nachweise + +- **Entwicklungszugang:** User-Konsolenrecovery und gepinnter SSH-Kontakt im + Fallfc7a6ad5 bestätigt; anschließend vollständige öffentliche Datei-/Key- + Metadaten-/Task-/SID-Erhaltung490e0180 geprüft. Lokale Accessfrist erst danach + per CAS erneuert; identische SSH-Pins und Schlüssel. Der zusätzliche + Downloadclose-Nachbelegb046e30d bestätigt nach tatsächlicher Timerwirkung: + Bootstrapdienst inaktiv, kein8443Listener und keine8443Allowregel, Closeaktion + erfolgreich. Kein neues Enrollment oder RMM-Job. +- **Pipe-v2:** Erhaltender Paarupgrade14fb einmal ausgeführt, tatsächlicher + LocalService/SYSTEM-Peertransport bestanden. Agentf10c78dd und Helper5f8c62fa + laufen unter unveränderten Konten/Startarten. Zwei neue Heartbeats, + Inventar-ACK, Tenantverweigerung und ursprüngliche PKI-/DB-/Lockdatei-IDs/ + Historie erhalten. Resultatd5c49968; lokale Mainindizes erst danach per CAS + fortgeschrieben. Windows0/0/0/0, Linux30/30/26/0, Clock/Jobs/Wirkungenfalse. + [Quellen und genaue Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/b4dbeba/docs/windows-system-pipe-upgrade.md). +- **Runtimeunits:** Erster Windowslauf25971084 scheiterte an einer fehlenden + `SystemDrive`-Variable im bereinigten Testprozess. Ausschließlich Runner + korrigiert, kein Test entfernt und keine Produktquelle geändert. Neues + Manifest341866b7: zuerst Cloud-Linux10 (a8978cd0/7c314685), danach + Windows35+7 (b377daad/9bf7aef4) bestanden, keine Skips/Filter. + [Ergebnis und ursprünglicher Fehler](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/1136707/docs/windows-msi-runtime-units.md). +- **Zeitdienstdiagnose:** Microsoft-MIDL-Tools vor Ausführung nativ mit gültiger + Authenticode-/Onlinekettenprüfung zugelassen (4b10a063). Codegen149bafe2 + abgeschlossen, Dateien getrennt lesend bestätigt (0dc23738). Tatsächliches + HeaderSHA256db5dbe5b, StubSHA256d806adb4. Das ist Compilererfolg, keine + erfolgreiche W32Time-RPC-Abfrage. Frühere1783Fehler bleiben fehlgeschlagen. + +## Aktueller Betrieb nach weiteren tatsächlichen Schritten + +Cloudserverfall14dcc27d ist gebaut und erhaltend bereitgestellt, Migration14 +angewandt; API/Gateway als UID10001, Loopbackports und private WebUI erhalten, +öffentliche Adminrouten geschlossen. Ursprüngliche Job-/Audit-/Identitätsgeschichte +bytegleich, keine neuen Jobs/Genehmigungen. [Nachweis7ef068f](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/7ef068f/docs/script-console-cloud-upgrade-v2.md). + +Linux nach separater erster Startfortsetzung66a537bb aktiv: Agent66132, +General65562 und Full66122, genaue neue Images0a7ad6ee/79442727, korrekte Konten, +gleicher Boot und erhaltene ursprüngliche SQL-/PKIzeugen vor Starts. Die alten +Install-/Probeberichte bleiben fehlgeschlagen. [Belegcfd32ea](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/cfd32ea/docs/script-console-bootstrap-results.md). +Aktuelle Windowsunits36+7 im Fall76bb47dd danach vollständig bestanden, +keineSkips/Filter, separatesReadback. [Beleg5b2f07b](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/5b2f07b/docs/script-console-windows-link.md). +Das ersetzt keine laufende Windows-Runtime-/Clock-/SYSTEM-Abnahme. + +Danach vollständige native passive Nachattestation mit drei Beobachtungen +bestanden (efd310b), ursprüngliche Identität/PKI/DBinodes/Root18 sowie +SignedSync und gespeicherte Kontakt-/Inventarfortschritte nachgewiesen. +Automation erhielt ausdrücklich nur das fehlende root:execute, keine +Genehmigungsrechte (afccf95). + +**Die erste vollständige Skriptkonsole ist auf Cloud-Linux nativ bestanden +(76440e1):** Einmal MCPplan/submit, persistentes pending_approval mit null +ausführbaren Artefakten; echte WebUI mit geprüftem TLS und Chromium-Sandbox, +Originalplanbytes vollständig verglichen, sichtbarer SIMULIERT-Freigabeklick. +Ein Root/Fullskript, Exit0, stdout28/stderr27Byte ungekürzt und bytegenau auch +über echte WebUI-Downloads geprüft; MCP-Ergebnis gleich. Zwei authentisierte +MCP-Fremdmandantenabfragen verweigert. Native Root19/0 mit18 unveränderten +Originalzeilen, ServerLinux31/31/27/0, Windows0/0/0/0. Der Zwischenzustand +running wurde im Browser verpasst und nicht durch Wiederholung erzeugt. +Temporäre Scopes geschlossen; Originalpolicycf15cbb6 separat lesend bestätigt. +[Genaue Ergebnisse und Grenzen](script-console-linux-full-results.md). +Die folgenden älteren Zwischenstände bleiben historische Belege. + +Windowsclock danach weiter gesperrt: tatsächlicher Discovery-Erfolg mit +nicht-NULL Emptyprincipal; eigener ursprünglicher Guard stoppte vor Query. +Separater Empty-Vergleich führte eine Opnum6 aus und ergab weiter RPC5/Stage90, +keinen Status. Vorhandenes SeSystemtimePrivilege im SYSTEM-Diagnoseprozess war +deaktiviert; daraus folgt noch keine bewiesene alleinige Ursache. Separates +Readback, Cleanup und vollständige native RMM-Erhaltung bestanden; Windows +weiter0/0/0/0. Die parallel genehmigte Linuxänderung ist ausdrücklich erfasst. +[Beleg98f4edf und Grenzen](windows-clock-spnego-empty-trace.md). +Ein separater Prozessprivilegvergleich wird vorbereitet, noch nicht nativ +ausgeführt. Updater-Handoffkernel nach unabhängigem Review als isolierter +Quellschritt a2efb79 gepusht und anschließend **Cloud-Linux8 nativ bestanden**, +keine Skips/Filter, separater Readback und bekannte Dienst-/Kontroll-/ +Stateidentität erhalten. [Ergebnis](agent-updater-handoff-linux-results.md). +Runtimeintegration läuft getrennt; weder Apply noch Windows dadurch abgenommen. + +## Fortschreibung: reale Quellenprüfungen und Bereitstellungsgrenzen + +- Skriptkonsole im Branch `codex/script-console`, Commit + [ff78b6a](https://gitea.incoso.eu/kevin_janssen/rust-discovery/commit/ff78b6a): + Vertrag1.20, Helper-Codepin und vollständiger Runtime-/UI-Pfad implementiert + und unabhängig geprüft. Tatsächlich Cloud-Linux84 bestanden; fünf DB-Fälle + dort explizit ausgelassen und separat in PostgreSQL45/45 bestanden. Web49, + Typecheck und Build bestanden. Windows derselben158 Eingaben ist gelinkt; + nativer Lauf offen. Erster Stagingfall4e59 stoppte an einem falschen absoluten + SFTP-Pfad vor Listen-/Testausführung; separates Readback bestätigt beide Marker + abwesend. Das ist ein Harnessfehler, kein Produktnachweis. +- Linux-Bootstrap2e27c312 hat die geprüften neuen Images installiert, + General-/APT-Steuerdateien und sämtliche ursprünglichen SQL-/PKI-/Dateizeugen + vor Restart unverändert geprüft. Danach Guardfehler vor erster Startwirkung: + die effektiven leeren systemd-Denylisten werden als `~` angezeigt, nicht als + leerer String. Originalreportf752258c bleibt fehlgeschlagen. Readback bestätigt + alle drei neuen Dienste inaktiv/PID0, APT weiterdisabled. Eine gesondert + geprüfte erstmalige Startfortsetzung ist offen; keine Wiederholung des + ursprünglichen Installers, kein Job und kein Reboot. +- Cloudserverfall499e stoppte vor Dockerbuild an wechselnder Reihenfolge + identischer vollständiger Mountobjekte. Originalfall unverändert, kein + Imagewechsel/Migration. Neuer getrennt geprüfter v2-Runner normalisiert nur + deren Reihenfolge und verlangt eine frische Baseline; Bereitstellung offen. +- Native Windows-Clockdiagnose mit echtem Microsoft-MIDL meldet unter + LocalService wie SYSTEM RPC5/Stage90 ohne Status. EEInfo-Falle4e6 lieferte + Runtime-Component2/Status5/Detection1750; die konkrete Ursache ist damit nicht + belegt. Separates Readback, gezieltes Cleanup und vollständige Erhaltung + bestanden. Clockgate bleibtfalse. + [Tatsächlicher Beleg und Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/commit/29e35c4/docs/windows-clock-eeinfo-trace.md). +- Updater-Verifier nach Linux9 auch Windows9 nativ bestanden; beide Schritte + separat gepusht. [Branchstand3543e07](https://gitea.incoso.eu/kevin_janssen/rust-discovery/commit/3543e07). + Das ist der signierte reine Prüfkern; Applydienst/Releasekatalog/Streaming/ + WebUI-Updatepläne und Wiederanlauf bleiben offen. Kein aktiver Autoupdater. + +Die nachfolgende Tabelle beschreibt den früheren Quellenzwischenstand; diese +Fortschreibung hat bei widersprechenden Build-/Betriebsangaben Vorrang. + +## Parallele Quellenarbeit und verbleibende MVP-Arbeit + +| Thema | Tatsächlich umgesetzt/geprüft | Noch offen | +|---|---|---| +| Skriptkonsole | Vertrag1.20 implementiert/geprüft, Cloudserver/WebUI und Linuxruntime bereitgestellt. Nativ CloudLinux84, Windows43 und separatPG45 bestanden; erste tatsächliche MCP/WebUI/Rootskriptstrecke samt Rohbyteausgabe und Mandantengrenze bestanden. | Native Windows-PowerShell/SYSTEM-Ausführung; weitere erforderliche aktuelle Abbruch-/Unknown-Gates, abschließende Integration und aktuelle private Runtimeindizes. | +| Windowslaufzeit | Positive echte Pipe-v2-Peerstrecke und passive Erhaltung; portable Runtime-/Domainunits nativ. | Tatsächliche TrustedClock-Abnahme, synchrone Helper-/Intent-/PERSIST-Strecke, genehmigte Skriptausführung und verbleibende Windows-MVP-Gates. | +| Agent-Selbstupdater | Reiner signierter Verifier auf CloudLinux9 und Windows9 nativ bestanden. Neuer isolierter Handoff-/Fullrenderer-/Healthkernel lokal8/8 und unabhängig geprüft; noch keine Applyruntime. | Atomare bestehende Ledgertransaktion, Inflight-/Serviceownership und authentisierter Healthanschluss, Katalog/Streaming, feste WebUI/MCP-Updatepläne, OSaustausch/Erhaltung/zulässiger Rollback und native Applynachweise. Kein aktiver Autoupdater. | + +APT-/MSI-Paketfixtures prüfen Verwaltung anderer Software; sie implementieren +keinen Agent-Selbstupdater. Weitere Paketfeatures sind der Skriptkonsole +nachgeordnet. EXE-Normvorschläge sind nicht freigegeben. Volle Hostwartung ist +ein explizites neues Profil: Root/SYSTEM kann selbst Agent, Dateien, Dienste oder +Neustartzustand verändern; daraus folgt keine Sandbox-/Rollback-/No-Reboot- +Zusage. Keine impliziten destruktiven Tests oder Hostneustarts. + +Alle tatsächlichen RMM-Wirkungen bleiben hinter der unveränderten +`pending_approval`→interaktiven WebUI-Grenze. Neue Profile, Builds, lokale Tests +und Bootstrapnachweise sind keine Produktionsfreigabe und kein vollständiger +Windows-MVP-Abschluss. Quellen und Dokumentation werden nach jedem +Abnahmeschritt nach Gitea gepusht; private Rohbelege bleiben ignoriert. diff --git a/docs/post-mvp.md b/docs/post-mvp.md index a1f4ab8..2ebf1ba 100644 --- a/docs/post-mvp.md +++ b/docs/post-mvp.md @@ -1,6 +1,6 @@ # Entdeckungen und Aufgaben nach dem Linux-MVP -Stand 2026-11-13. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind +Stand 2026-11-14. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und [Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht. @@ -10,6 +10,8 @@ Pfad bleiben dort sofort relevant. | Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe | | --- | --- | --- | +| Windows-PE nach erneutem Debugstrip | Zwei Lieferkopien mit identischen unveränderten Original-Linkdateien unterscheiden sich nach erneutem Strippen nur an vier Bytes: COFF-Zeitstempel/PE-Prüfsumme, Offsets136/137/216/217. Lokal tatsächlich verglichen; beide ursprünglichen Packs bleiben erhalten. Jeder Pack pinnt seine konkreten Lieferbytes. | Reproduzierbare PE-Werkzeugpipeline vor M7 festlegen. Bis dahin niemals gleichen Lieferhash aus gleicher Rustquelle/gleichem Original-Link behaupten oder ein altes Manifest überschreiben. Kein aktueller Autorisierungs- oder Abnahmebypass. | +| Dev-Reversetunnel ohne Zielbanner | Windows-RMM-Heartbeats liefen tatsächlich weiter, während Serverlistener/TCP-Verbindung auf127.0.0.1:22240 vorhanden waren, aber kein SSH-Banner durchkam. Der Bootstraploop überwacht nur das äußere ssh.exe und verbindet nach dessen Ende neu; der Task hat kein RestartOnFailure. Konkrete Ursache des blockierten SSH-Ziels unbewiesen. Keine SSH-/Hostkey-/Expirygrenze gelockert. | Nach dem MVP begrenzte Transport-/Workerdiagnose verbessern. Keine automatische Schlüsselverlängerung, öffentliche Windowsportfreigabe oder pauschalen sshd-/UID-Resets. Der aktuelle manuelle Konsolenneustart bleibt ausdrücklich zeitlich abzustimmen und ist kein RMM-Rebootnachweis. | | Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. | | Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. | | Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. | diff --git a/docs/project-decisions.md b/docs/project-decisions.md index 96aea52..ba4b95a 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,22 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-14**, Spezifikation **1.21** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. +Stand: **2026-11-14**, Spezifikation **1.22** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. + +## Signierter Windows-Zeitvergleich ausdrücklich erlaubt (Version1.22) + +2026-11-14 hat der User den konkret beschriebenen alternativen Zeitvergleich +mit „Ja, signierten Zeitvergleich umsetzen“ angenommen. Die unabhängige +Agent-/SYSTEM-Prüfung und bestehende WebUI-/Zeitgrenzen bleiben verbindlich. +Kapitel0 der Spezifikation1.22 ersetzt den früheren Ausschluss eines +Serverzeitankers ausschließlich durch den gebundenen Onlinevergleich mit dem +festgelegten Server. Separater Ed25519-Pin, eigene Challenges/Timer je Verifier, +mTLS-Geräte-/Verbindungsbindung, vollständiger RTT im Unsicherheitsintervall, +kein Holdover und kein neuer Grant durch Belegrefresh. W32Time-Rohstatus bleibt +separat; keine Zeitstellung, kein manueller Resync hiermit genehmigt. + +[Vertrag und offene Nachweise](windows-clock-attestation-proposal.md). +Angenommene Produktentscheidung, noch keine qualifizierte Zeitquelle oder +Windowsjobfreigabe. Fehlende tatsächliche Server-/Timerqualität bleibt deny. ## Präzisierung des engen Updatervertrags (Version1.21) diff --git a/docs/script-console-cloud-upgrade-v1.md b/docs/script-console-cloud-upgrade-v1.md index cb74483..f0ded51 100644 --- a/docs/script-console-cloud-upgrade-v1.md +++ b/docs/script-console-cloud-upgrade-v1.md @@ -37,7 +37,7 @@ beide SSH-Supportquellen, Quellarchiv, Webarchiv, alle Einzeldateien und die SHA384-Checksummen der SQLx-Migrationen. Der bestehende geprüfte SSH-Key-/Hostkeyweg wird wiederverwendet. `--access-root` bezeichnet nur den vorhandenen Hauptcheckout mit geschützter `credentials/server.conf`; dessen Quellen werden nicht gebaut. -Ziel ist ausschließlich Root-Bootstrap auf 88.99.80.202 bzw. dessen festem Namen. +Ziel ist ausschließlich Root-Bootstrap auf discovery.ease-technologies.de bzw. dessen festem Namen. TLS verwendet dieselbe getrennte Vertrauenszuordnung wie die bestehenden Compose-Mounts: API18443 mit Name `localhost` und diff --git a/docs/script-console-policy-scope.md b/docs/script-console-policy-scope.md index 77fb9e4..17af62f 100644 --- a/docs/script-console-policy-scope.md +++ b/docs/script-console-policy-scope.md @@ -161,7 +161,7 @@ python3 deploy/script_console_policy_scope.py read --id SCOPE_CASE Platzhalter sind absichtlich nicht ausführbar. Der bestehende Hauptcheckout mit geschützter `credentials/server.conf` ist der Standard-SSH-Zugangsroot; es gibt keinen Linux-VM-Aufrufpfad. Ausschließlich der bereits unabhängig vertraute -Cloudserver88.99.80.202 bzw. dessen fester Name ist zulässig. SSH ist +Cloudserverdiscovery.ease-technologies.de bzw. dessen fester Name ist zulässig. SSH ist Bootstraptransport, keine Job- oder Approvalautorität. ## Semantikgrenzen diff --git a/docs/server-time-source.md b/docs/server-time-source.md new file mode 100644 index 0000000..cc085ac --- /dev/null +++ b/docs/server-time-source.md @@ -0,0 +1,177 @@ +# Nativer Linux-Zeitprovider: Quellencheckpoint + +Der neue Quellpfad `crates/time-source-linux` beobachtet eine fest provisionierte +Chrony-Instanz und den Linux-Kernel lesend. Er ist weder eine Zeitstellung noch +ein Jobgrant. Dieser Stand ist implementierter, lokal geprüfter, noch nicht nativ +qualifizierter Quellcode. Es wurde durch diesen Implementierungsauftrag keine tatsächliche +Chrony-Abfrage, Provisionierung, Dienstaktion oder VM-Änderung ausgeführt. +Die tatsächlichen lokalen Dockerprüfungen sind unten getrennt dokumentiert. +Der Codec-Nachweis ersetzt diesen Providernachweis nicht. + +`NativeTimeSource::open()` benötigt einen engen Root-Brokerprozess. Der +unprivilegierte Anwendungsserver wird dadurch nicht zu Root. Die Runtime- +Brokerintegration und die getrennte Zeit-Signierschlüsselprovisionierung sind +separate Arbeitspakete. `sample()` liefert ausschließlich nach erfolgreicher +authentisierter Beobachtung einen privat konstruierten `QualifiedSample`. +UTC, Fehlerobergrenze, tatsächliches Referenzalter, Boot-ID sowie Monoton-/ +Boottime-Erfassungszeiten sind lesbar; Caller können keine Qualifikation per +Boolean oder eigenem Konstruktor erzeugen. Der Broker muss Zeit bis zum +Signieren konservativ ergänzen, Frische und Boot erneut prüfen und den +Sourcezustand ohne Holdover verwenden. Dieser Typ allein autorisiert keinen +HTTP-Aufrufer und keine Agentaktion. + +## Festes Provisionierungsprofil + +Die folgende Konfiguration beschreibt Voraussetzungen, keinen ausgeführten +Bootstrap. `/etc/rmm-time-source/chrony-pin.json` muss eine reguläre, +root-eigene Datei mit Modus0600 und genau einem Link unter geschützter +root-eigener Verzeichniskette sein. Striktes JSON-Schema1, keine Zusatzfelder: + +```json +{ + "schema_version": 1, + "daemon_pid": 1234, + "daemon_birth_ticks": 123456, + "daemon_uid": 999, + "daemon_gid": 999, + "daemon_image_sha256": "<64 kleingeschriebene Hexzeichen>" +} +``` + +Die Zahlen sind ausschließlich Platzhalter. Ein Operator muss die tatsächlichen +Werte unabhängig aus der vorgesehenen Instanz prüfen. Der Imagepfad ist fest +`/usr/sbin/chronyd`. PID-Startzeit, alle vier UID-/GID-Werte, lebendes pidfd, +gehaltenes und aktuelles `/proc/PID/exe`, aktueller fester Imagepfad und SHA256 +müssen übereinstimmen. Die geschützte Binärdatei wird vor und nach der Abfrage +geprüft. Neustart, Konto-/Imagewechsel oder unklarer Zustand bleiben deny; +keine automatische PID- oder Pinübernahme. Root muss einen neuen vertrauens- +würdigen Pin separat provisionieren und die Providerinstanz neu eröffnen. + +Ziel ist ausschließlich `/run/chrony/chronyd.sock`. Seine Identität und +Verzeichniskette werden vor und nach der Abfrage geprüft. Nicht-root-eigene +Verzeichnisse müssen dem gepinnten Chrony-Konto gehören; kein Gruppen- oder +Fremdschreibrecht. Der Socket muss dem gepinnten Daemonkonto gehören und darf +keine Rechte für Fremde haben. Andere Images oder Layouts bleiben vorerst +nicht unterstützt, ohne permissiven Fallback. + +Der vom Rootoperator separat anzulegende Clientbereich ist +`/run/rmm-time-source/clients`, root:ChronyGID0710 unter geschützter root-eigener +Kette. Eine einzelne Zufallsadresse `tracking-.sock` wird einmalig dort +gebunden, root:ChronyGID0660 gesetzt und mit Device/Inode/Name/Konto/Modus +gehalten. Chrony erhält nur Traversierungsrecht am Verzeichnis und Socket- +zugriff; es kann dort keine Namen ändern. Vor jedem Namespacezugriff werden +gehaltener Verzeichnis-FD und aktueller Pfad verglichen. Cleanup konsumiert +seine einmalige Autorität vor der Prüfung und verwendet ausschließlich +`unlinkat` für die exakt eigene Identität. Unklarer Cleanup bleibt liegen; +kein Retry, rekursives Entfernen oder Übernehmen fremder Dateien. Vor Beginn +wird das Clientverzeichnis exklusiv per nonblocking flock am gehaltenen +Verzeichnis-FD gesperrt und muss leer sein. Ein unbekannter Rest blockiert +auch neue Instanzen. Die laufende Providerinstanz bleibt nach einem unklaren +Clientpfad sticky gesperrt; keine neue UUID-Schleife. + +## Drahtvertrag und Qualität + +Primärquellen: Chrony [candm.h](https://github.com/mlichvar/chrony/blob/master/candm.h), +[pktlength.c](https://github.com/mlichvar/chrony/blob/master/pktlength.c), +[addressing.h](https://github.com/mlichvar/chrony/blob/master/addressing.h) und +[util.c](https://github.com/mlichvar/chrony/blob/master/util.c). + +Ein einzelner Unix-Datagrammaufruf verwendet Version6, Tracking-Befehl33, +Antworttyp5 und eine zufällige32-Bit-Sequenz. Request und erfolgreiche Antwort +sind jeweils104Bytes; das Requestpadding gehört dazu. Kein Retry, Shellaufruf, +CLI, UDP-/IP-Fallback, frei wählbarer Befehl oder Zeitsetter. `SO_PASSCRED` und +`recvmsg` verlangen genau eine unveränderte Kernel-Credential mit gepinnter +PID/UID/GID. Fremde Sequenz, fehlerhafte Status-/Headerfelder, abgeschnittene +Nutz- oder Kontrolldaten und fehlende Credentials verweigern. + +Die ursprünglich vorgesehene abstrakte Linux-Autobindadresse wird nicht +verwendet. Die Chrony-[Socketimplementierung](https://github.com/mlichvar/chrony/blob/master/socket.c) +behandelt Unix-Rückadressen als C-Strings und rekonstruiert sie mit `strlen`; +eine mit NUL beginnende abstrakte Clientadresse verliert dadurch ihren Namen. +Dieser reine Quellenbefund wurde auch in4.6.1 geprüft, nicht als reales +fehlgeschlagenes Runtimeexperiment ausgegeben. Die technische Entscheidung +des Hauptagenten erlaubt stattdessen den engen sichtbaren Clientbereich oben. + +Das Trackingalter wird aus Chronys tatsächlicher Referenzzeit berechnet, +nicht aus Abfragezeit oder Pollintervall. Unsynchronisiert, lokale Referenz/ +Refclock, Nullreferenz, Nicht-Netzwerkquelle, Loopback, ungültiger Stratum, +Leapstatus, Zukunftszeit oder ein Alter über1h verweigern. Die spezialisierte +Draht-Floatdarstellung wird als exakte ganzzahlige rationale Größe mit +Aufrundung nach Nanosekunden dekodiert, einschließlich negativer Korrektur; +negative Verzögerung/Dispersion oder Overflow verweigern. + +Vor und nach der Abfrage wird `adjtimex` ausschließlich mit modes0 abgefragt: +Status0–4, weder `STA_UNSYNC` noch `STA_CLOCKERR`, gültiger `maxerror`. +REALTIME, MONOTONIC und BOOTTIME werden zeitlich eingegrenzt beobachtet; +Bootwechsel, Rücksprung, Suspendabweichung, unpassende Wanduhrdifferenz und +überschrittenes Gesamtbudget verweigern. Eine Erfassung darf höchstens10ms, +das ist ausschließlich das gemessene Erfassungsfenster, keine Zusage +physikalischer Timerqualität oder Kalibrierung. Die gesamte Abfrage +einschließlich Auth-/Nachprüfung und Cleanup darf höchstens +100ms dauern. Fehlerobergrenze ist konservativ aufgerundet: +Betrag der Chrony-Korrektur + Rootdispersion + halbe Rootverzögerung + größter +Kernel-maxerror + vollständige verstrichene Abfrage-/Nachprüfzeit. Über500ms +verweigert. Nachlauf bis Signierung ist zusätzliche Brokerpflicht; es gibt +keine erfundene Timerkalibrierung und keinen Offline-Lease. + +## Tatsächlich lokal ausgeführt + +Im unveränderten Offline-Buildimage +`sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6`, +Quellmount read-only, UID1000, eigenes `devstate/provider-target`: + +- `cargo test --locked --offline -p rmm-time-source-linux --all-targets`: + 4bestanden,0fehlgeschlagen,0ignoriert,0gefiltert. Parserbindung und signed-Float- + Grenzen; synthetische Zeitbracket-Fehler; ausschließlich eigener temporärer + Socket mit echter Namenersetzung und genauem Inodecleanup. +- `cargo clippy --locked --offline -p rmm-time-source-linux --all-targets -- -D warnings`: + bestanden ohne Warnungsunterdrückung. +- Gezieltes `rustfmt --edition2024 --check --config skip_children=true` der + drei eigenen Rustdateien: bestanden. + +Der erste Compilerlauf meldete den konkreten `pread`-Offsettypkonflikt +`i64/isize`; er wurde explizit konvertiert und danach bestanden alle obigen +Prüfungen. Die Tests rufen weder den echten Chrony-Provider noch `adjtimex` +auf. Kein Rootlauf, keine Dienstinstallation, keine Server-/Clientwirkung. + +## Verbleibende reale Gates + +Unabhängiger Quellenreview, +Linux-first-Nachweis mit tatsächlichem Chrony-/Kernelzustand, geschützte +Provisionierung, Broker- und mTLS-HTTP-Anschluss sowie unabhängige Agent-/ +SYSTEM-Verifikation bleiben getrennt. Fehlende Plattformqualität bleibt deny. +WebUI-Genehmigung und sämtliche ursprünglichen Clock-/Jobgrenzen bleiben +bestehen. Auf dem Notebook wird kein RMM-Dienst oder Agent installiert. + + +## Unabhängiger Quellenreview und gezielter Parserfix + +Die enge unabhängige Prüfung korrigierte ausschließlich konkrete Fehlerpfade: +Chrony-Ownerausnahme nur am letzten `/run/chrony`-Verzeichnisteil, gebundene +Ancillary-Grenzen vor Credentiallesen sowie sticky Cleanupfence und exklusiver +Verzeichnislock/Leerverzeichnisprüfung. Keine unbekannten Namen automatisch +entfernen oder bei unklarem Cleanup neue UUID-Dateien anhäufen. + +Danach wurden zusätzlich IPv4-mapped und IPv4-compatible Loopback-/ +Unspecified-Adressen im IPv6-Feld verweigert. Der bestehende Parserfall prüft +vier Gegenfälle und zwei erlaubte Netzwerkdarstellungen; Testzahl bleibt4. +Neuer ReceiptSHA256 +`275e6661ad1342cf63df573cab4309ca49d1f7a1066ee2d03fdf686ac58370a6`; +lokale4/4,Clippy,Fmt und Release-Link bestanden. Originale4041333 bleibt +historisch unverändert. Kein nativer Provider-/Kernelquery durch diese Tests. +Der Quellenreview ist abgeschlossen; tatsächliche Providerqualität bleibt offen. + +## Getrennter tatsächlicher Kernelbefund auf dem Server + +Im nur lesenden Originalfall `09f56716-6175-41f6-8217-5de46854aaf1` wurde auf +dem festgelegten ARM64-Server genau eine Kernelabfrage mit modes0 ausgeführt. +Gemeldet: state0/flags0, kein STA_UNSYNC/STA_CLOCKERR, +maxerror55773us,esterror544us. Eigenes monotones Erfassungsfenster128082ns. +ResultatSHA256 +`5422ab7182fd7ff7896f56ce61ea3fe96e9b3a9ef236c39f74a6add8a538a61b`. +Keine Zeitstellung, kein Resync, keine Dienst-/Anwendungsänderung. + +Das ist ein einmaliger ABI-begrenzter LP64-Diagnosebefund. Er bildet mit dem +älteren separaten Chrony-CLI-Beleg keine neue gemeinsame native Qualitätsprobe. +Kein signierter Beleg oder freigegebenes Clockgate daraus. Der neue native +Provider muss diese Kernel- und Chronyprüfung selbst frisch zusammen ausführen. diff --git a/docs/signed-time-contract-results.md b/docs/signed-time-contract-results.md new file mode 100644 index 0000000..6db82f3 --- /dev/null +++ b/docs/signed-time-contract-results.md @@ -0,0 +1,116 @@ +# Signierter Zeitvergleich: gemeinsamer Prüfkern nativ auf Linux + +2026-11-14, Spezifikation1.22. Neuer gemeinsamer Codec/Verifier implementiert; +noch kein vertrauenswürdiger produktiver Zeitadapter oder Windowsjobgate. + +`rmm-time-attestation` bindet kanonische JSONbytes mit eigener Ed25519-Domäne, +geschützte Schlüsselgeneration/Serverinstanz, vollständigen Requesthash, +Geräte-/Boot-/Verbindungs-/Rollenbezug und eine pro Verifier gehaltene aktuelle +Nonce. Challenges sind nicht klonbar und werden auch bei Fehler verbraucht. +Der Verifier misst nach Signaturprüfung erneut über den nativen Caller. +Ganze RTT, drei Capturebudgets und Serverfehler gehen konservativ in die +UTCspanne ein; Startfristen müssen deren beide Grenzen erfüllen. Keine neue +Jobautorität, kein Synclease, kein Holdover und keine Uhrstellung. + +Das unabhängige Review fand einen echten Replayfehler: Nach fremder +Fehlerantwort konnte ein alter eigener Challenge unter einem neuen offenen +Slot akzeptiert werden. Der Fix hält die exakte aktuelle Nonce zusätzlich zu +Verifier-ID/Epoch/Context; ein gezielter Gegenfall prüft die gesamte Sequenz. +Der erste lokale Signatur-Negativtest konnte durch Ersetzen mit00 zufällig +unverändert bleiben; jetzt verändert XOR1 garantiert ein Signaturbyte. +Diese ursprünglichen Fehler werden nicht als erfolgreiche Prüfungen geführt. + +## Tatsächliche lokale und native Prüfungen + +Lokal debug4/4, keine Skips/Filter. Finale eingefrorene Quelle separat Release +gebaut und gelinkt, Clippy-Dwarnings und Formatcheck bestanden, Offlinebuilder +9a76ad3744eb. Qualifikationsreceipt SHA256 +`a50017a1a80042351a639ab2fa8f813435d7d40bd236331dd34f075e98cd09eb`. +Ein vorheriger Qualifikationsfall stoppte korrekt an `--locked`, als parallel +nur die neue Windows-Abhängigkeitskante ergänzt worden war. Nach deren enger +Lockdateiergänzung entstand ein neuer, vollständig bestandener lokaler Fall. +Keine alten Belege ersetzt, keine Abhängigkeitsversion geändert. + +Vier eingefrorene Inputs: Workspace-/Crate-Manifeste, Cargo.lock und Codecquelle. +Inputmanifest SHA256 +`c01a21bfa09a77b7fa529b85931ac111d08f0dcce137e6aa86a9a22c2c35cf73`. +Releaseexe1515200Byte, SHA256 +`0e06243dc6d9d502681fb62f755bf5267140a483f89ae61cd6a2e31201a85a13`. +Nur der gemeinsame Prüfkern, keine übrigen Workspacequellen qualifiziert. + +Der unabhängig geprüfte neue Runner +`deploy/time_attestation_linux_acceptance.py`, SHA256 +`7572171fee75b5e994253e8190871778e439f8575691256d644a405e23cdaac6`, +verlangt die exakte native Viererliste vor einem einzigen Lauf. Originalfall +`2b282376-5002-4a75-91e2-8928fa8688cd` auf der Cloud-Linux-VM: +**4/4,0ignored/filtered, Exit0**, separater lesender Rückabruf vollständig. + +Tatsächlich ausgeführte Originalbefehle: + +```sh +python3 deploy/time_attestation_linux_acceptance.py prepare +python3 deploy/time_attestation_linux_acceptance.py execute --case 2b282376-5002-4a75-91e2-8928fa8688cd +python3 deploy/time_attestation_linux_acceptance.py read --case 2b282376-5002-4a75-91e2-8928fa8688cd +``` + +Fallmanifest SHA256 +`60d306685fa8b37217cd973aa5ff19b3a520aaab9154eb3e77cc1450f802212c`; +Execute-Beleg SHA256 +`282a597183ed02f4c767407aa7ed94975f8e3571d56eaa6835bb9bbe429e8fb0`; +Readback SHA256 +`1156610d7b41d92b3f55932d3b39547c2e0f24ee906edf00fd43860419e952b5`. +Bekannte drei RMM-Prozessgenerationen, Boot, vier Kontrollbytebelege und +DB-/Lock-Dateiidentitäten blieben vor/nach sowie beim Readback gleich. +APT inaktiv/disabled, Full aktiv/Autostart disabled. Keine Dienststeuerung, +Produktzeitabfrage, RMM-Jobs, Dateitausche oder vollständige SQL-/PKI-Abnahme. +Die Tests erzeugen nur kurzlebige In-Memory-Signierschlüssel/Codecfixtures. + +## Offene Integration + +Der native Beleg prüft Codecbytes und Validatoren, keine Server-/Windows- +Zeitqualität oder komplette Runtime. Geschützte Pinprovisionierung, tatsächliche +Chrony-/Kernelquelle samt lokalem Signierbroker, mTLS-/SQL-Kontextprüfung, +unabhängiger Windows-Agent/SYSTEM-Timerbeleg und Jobintegration bleiben offen. +Der erste Codec bindet noch den provisorischen Audiencepfad +`/api/agent/v1/time-attestation`; die nachfolgende Korrektur an den +bestehenden `/agent/v1/...`-Vertrag ist unten mit eigenem Beleg dokumentiert. Keine zusätzliche öffentliche API-Wildcard vorsehen und den +ursprünglichen nativen Beleg dabei nicht nachträglich umetikettieren. + +Die unverbundene Windows-Slice-/Providerentwicklung parallel dazu eröffnet +keine Capability. Das Windows-MVP und der Selbstupdater sind nicht abgeschlossen. + + +## Nachfolgender Quellenstand: tatsächlicher Agent-Endpunkt + +Der feste Audiencepfad ist jetzt `/agent/v1/time-attestation`, passend zum +bestehenden Agentvertrag. Genau eine Codec-Konstante geändert; keine neue +öffentliche API-Wildcard oder geänderte Verifikationsregel. Der erste +Originalfall2b282376 bleibt unverändert und qualifiziert weiterhin seine alten +Bytes, nicht diese nachfolgende Generation. + +Neuer unabhängiger Runnerreview und eingefrorene lokale Release4/4, Clippy und +Fmt bestanden. ReceiptSHA256 +`b708000c9ca9ba8da2128003683ed26382d4349833c322663bdd393dd60ad751`, +InputmanifestSHA256 +`989bcd56c96747ce8f2c4020423360ce4a8c9d8057f7c3deccba4e44fbc30c9a`. +Neue Releaseexe1515168Byte/SHA256 +`4dc10170500912c703f815f8c13f9ac28715afe919ad94020fe713ade8fbafdb`. + +`deploy/time_attestation_uri_linux_acceptance.py` SHA256 +`b156729ef7e8bf4b19f6f95be87b4b3be2145dad820146d1d935191484386898` +verwendet eigene Fall-/Remote-/Profilnamen und denselben begrenzten +Einmal-/Readback-/Erhaltungsvertrag. Tatsächlich prepare, genau ein execute +und separater read mit Originalfall `a22de8d2-7cf7-4820-affa-79b4792132d1` +ausgeführt: **Cloud-Linux4/4,0ignored/filtered, Exit0**, Readback vollständig. +Bekannte Prozess-/Kontroll-/Stateidentitätszeugen erneut unverändert. +FallmanifestSHA256 +`c20c8ce40ea3fa55ec6db4aa5614a15ca63ded88b913835e2c29f78ae1eb3fcb`; +ExecuteSHA256 +`d2340962c7b1a56aa6d51d81eb7b2259ea2dcab80d0c9a1d251e8c5cbd23cf0e`; +ReadbackSHA256 +`2b5c4a428fab45f5f1e865dbb00bbacce2f0e86128134f31f6c3e9d3f4c3caf2`. + +Keine reale Zeitqualifikation oder Windowsfähigkeit daraus ableiten. Die +parallel hinzugefügte Linux-Providercrate ist separat lokal4/4 geprüft, +noch nicht nativ abgefragt; ihr Code wird durch diesen Codecbeleg nicht +mitqualifiziert. [Providerstand](server-time-source.md). diff --git a/docs/windows-clock-attestation-proposal.md b/docs/windows-clock-attestation-proposal.md new file mode 100644 index 0000000..bd12a07 --- /dev/null +++ b/docs/windows-clock-attestation-proposal.md @@ -0,0 +1,164 @@ +# ADR: unabhängiger signierter Zeitnachweis für Windows + +Status2026-11-14: **Vom User ausdrücklich angenommen: „Ja, signierten +Zeitvergleich umsetzen“.** Normativ in Spezifikation1.22/Kapitel0 und +Projektentscheidungen übernommen. Implementierung und tatsächliche +Qualifikation stehen noch aus; kein Schlüsselsetup oder Clockgatewechsel. +Vorausgehender konkreter OSF-Befund: +[QOS5-Analyse](windows-clock-rpc-qos5-analysis.md). + +## Angenommene Änderung der Trustsource + +Die vollständig gelesene Spezifikation1.18 samt aktuellen Main1.20-Deltas, +Projektentscheidungen und Entwicklungsregeln verlangen weiterhin tatsächliche +lokale Status-/Boot-/Unsicherheitsnachweise. Der aktuelle Windowsvertrag +verlangt lokalen W32Time-Sync höchstens1h alt, maximal2s Unsicherheit und nach +Diskontinuität einen neuen Sync; er schließt einen Serverzeitanker ausdrücklich +aus. Die VM meldet derzeit W32Time Leap3/Stratum0. Ein signierter Beleg darf +diesen Dienstzustand nicht nachträglich als synchronisiert ausgeben. + +Die angenommene Entscheidung erlaubt eine **andere zulässige Vertrauensquelle**: ein signierter +Onlinevergleich qualifiziert die aktuelle lokale Windows-Wallclock; er stellt +sie nicht und ersetzt sie nicht durch einen Hello-Zeitwert. Er ersetzt bewusst +lokalen W32Time-Sync als alleinige Voraussetzung durch streng begrenzte, +kryptografisch belegte Vergleichsqualität ersetzen. Auch „neuer Beleg nach +Diskontinuität“ wäre dann ein neuer expliziter Vertrag, kein behaupteter neuer +Windows-NTP-Sync. Die ausdrückliche normative +Produktentscheidung ist in Kapitel0/Projektentscheidungen1.22 festgehalten. +Review und eigene Qualifikation bleiben nötig. Bis dahin bleibt der +produktive Windowsclock-Adapter geschlossen. + +## Kleiner vorgeschlagener Vertrag + +Nur der bereits festgelegte Server `discovery.ease-technologies.de` darf mit +einem eigenen provisionierten Ed25519-Zeitschlüssel signieren. Domainkennung +`RMM-TIME-ATTESTATION/v1`, feste Version und exakte Codecbytes; kein frei +wählbarer Algorithmus. Schlüssel strikt getrennt von TLS, Jobs und Updates. +Der geschützte Helperpin bindet die erlaubten Zeitpublickeys samt monotoner +Konfigurationsgeneration. Der Netzwerkagent kann keinen Publickey ergänzen; +Rotation/Entzug brauchen den gesondert geschützten Konfigurationsweg. + +Agent und SYSTEM-Helper prüfen unabhängig. Jeder Verifier erzeugt selbst +256Bit CSPRNG-Nonce und eigene zufällige Prozessinkarnation, hält höchstens +eine Anfrage und beobachtet selbst Boot-ID, präzise Interrupt-/Unbiasedzeit +sowie Wallclock. Der Agent darf Helperanfrage und Antwort nur transportieren. +Seine behaupteten Zeiten oder Timer ersetzen keine Helperbeobachtung. + +Der signierte Beleg bindet Nonce, Anfragetype/-hash und Verifierrolle, +Serverinstanz/-boot, erlaubten Endpunkt, Tenant/Asset/Agent, +Enrollment-/Assignmentgeneration, aktuelle Connectiongeneration, +Windows-Boot-ID, Verifierinkarnation sowie beim Helper dessen gepinnten +Imagehash und Bindingschema. Serverseitig Tenant/Agent ausschließlich aus +gültigem mTLS ableiten; aktuellen Verbindungskontext selbst nachprüfen. +Eine solche signierte Kontextbestätigung darf initiale Clockprüfung vor dem +normalen Sync ermöglichen, ersetzt aber weder diesen Sync noch ein Startgrant. +Striktes TLS/SAN/SNI bleibt Pflicht; falsche OS-Zeit rechtfertigt keinen +Zertifikatsprüfungs-Bypass zur vermeintlichen Zeitreparatur. + +## Qualität und konkrete Zeitgrenzen + +Vor jeder Signatur braucht der Server eine frische, nur lesende native +Kernel-/Providerprüfung: kein `TIME_ERROR`, `STA_UNSYNC` oder `STA_CLOCKERR`, +eindeutige Einheiten, gültiger UTCwert und konservativer Gesamtfehler +`epsilon_server <= 500ms`. Die bestehende Linuxfunktion erlaubt Kernel- +`maxerror <= 5s`; sie ist dafür **nicht unverändert ausreichend**. Maximal1h +seit tatsächlichem letztem guten Quellensync bleibt erforderlich. `timex` +enthält Fehler-/Statusfelder, aber keinen universellen Last-good-sync-Zeitpunkt; +der tatsächlich vorhandene Zeitprovider muss dafür eine vertrauenswürdige +native Schnittstelle liefern. Fehlend bedeutet deny, kein aus Pollzeit oder +Heartbeat erfundenes Syncalter. +[Linux-UAPI](https://raw.githubusercontent.com/torvalds/linux/master/include/uapi/linux/timex.h). + +Vorläufige bewusst kurze Grenzen: vom verifiereigenen Challengebeginn bis zur +konkreten Prüfung maximal1s, davon nach Empfang höchstens100ms. Keine längere +Holdover-/Offlinephase. Capture-/Rundungs-/Timerunsicherheit wird explizit mit +`delta` berücksichtigt; dessen Höchstbudget50ms braucht einen tatsächlichen +Plattformnachweis und darf nicht aus Timerauflösung als Genauigkeit erfunden +werden. Microsoft trennt monotone Intervallmessung von UTC und setzt für VMs +einen korrekt implementierten Hypervisor voraus; diese OS-/Kernelannahme +bleibt ausdrücklich bestehen. +[Zeitstempelvertrag](https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps). + +Für signiertes Servercapture `T`, Fehler `epsilon_server` und selbst +gemessenes Gesamtintervall `R` ist die konservative UTCspanne zum Prüfzeitpunkt +`L = T - epsilon_server`, `U = T + epsilon_server + R + delta`. +Der gesamte RTT wird berücksichtigt; keine unbelegte Halbierung oder Annahme +symmetrischer Paketlaufzeiten. Die gleichzeitig selbst gelesene lokale +Wallclock `W` ist nur qualifiziert, wenn +`max(abs(W-L), abs(W-U)) <= 2s`. Spätere Vergleiche brauchen wieder einen +fristgerechten eigenen Beleg; keine freie Extrapolation einer Serverzeit. + +Deadlineprüfung muss konservativ die ganze Spanne verwenden: +`L >= not_before` und `U < start_before`, zusätzlich bestehende monotone +Laufzeit-/Verbrauchsgrenzen. Ein einzelnes `SyncClock::now()`-UTCdatum reicht +diesen Intervallvertrag nicht automatisch weiter; dessen konkrete Integration +ist vor Implementierung zu prüfen. Alte Grantbytes, Fristen und60s-Startfenster +werden weder geändert noch durch Belegrefresh verlängert. + +## Restart, Replay und Fehler + +Jeder Boot-/Prozess-/Connectionwechsel verwirft offene Nonces und Bereitschaft. +Kein auf Platte gespeicherter Zeitbeleg eröffnet nach Restart oder Restore. +Neue zufällige Nonce/Inkarnation und normaler unabhängiger Ledger-/Syncabgleich +sind nötig; Journale, Schlüsselidentitäten und Verbrauchshistorie erhalten. +Nur Schlüssel-/Konfigurationsgeneration und gebundene Jobprüfbelege werden +im bestehenden geschützten Persistenzmodell ergänzt, keine Ledgerresets. + +Rückwärtszähler, Wallstep oder Sleepdifferenz über der bisherigen1s-Grenze, +fehlerhafte Bootbeobachtung, falsche Nonce/Rolle/Bindung/Signatur, doppelte +Antwort, Überlauf oder Überschreitung einer Grenze sperren. Nach beobachteter +Diskontinuität darf nur eine danach erzeugte Challenge Bereitschaft herstellen. +Ein neuer Objektkonstruktor löscht keinen bestehenden Diskontinuitätsfence. +Ein bösartiger LocalService-Agent kann so höchstens verzögern/verhindern, +nicht Helpernonce oder Signatur fälschen. Server-/Zeitschlüsselkompromittierung +und bösartiger Hypervisor bleiben Vertrauensgrenzen; Signatur authentifiziert +den Beleg, nicht automatisch den vorgelagerten NTPserver. + +Ohne frischen gültigen Beleg `CLOCK_UNTRUSTED`; Telemetrie bleibt möglich. +W32Time-Rohstatus bleibt separat sichtbar. Keine Clocksetter, Resyncs, +NTP-/ACLänderungen, neue Jobfreigaben oder Ersatz menschlicher WebUI-Genehmigung. + +## Enger Review- und Nachweisplan + +Die ausdrückliche Entscheidung über die andere Trustsource und die +beibehaltenen Grenzen liegt vor. Als Nächstes ausschließlich lesend tatsächliche +Serverqualität/Provider-API, Windows-Timer und Sync-/Deadline-Integrationspunkte +prüfen. Fehlt eine belastbare Qualitäts-/Alters-/Timergrenze, bleibt der +Entwurf blockiert; keine Implementierung mit angenommener Güte. + +Nur nach bestandenem Review: wenige Byte-/Signatur-/Bindungs-/Intervallguards, +Serverseite zuerst auf der Linux-Cloud-VM qualifizieren, danach getrennt reale +Windows-Agent-/SYSTEM-Verifikation samt Replay, Delay, Restart und falscher +Rolle/Identität. Suspend/Clockstep zunächst injizierte Validatorinputs; kein +unangekündigter OS-Suspend/Uhrsprung. Quellen-/Buildnachweise eröffnen keine +Capability. Erst eigene reale Abnahme und anschließend tatsächlicher neuer +WebUI-genehmigter Windowsjob belegen eine nutzbare Strecke. + +## Separater tatsächlicher Serverproviderbefund + +Root hat nach diesem Entwurf nur lesend die vorhandenen Zeitdienste auf dem +festgelegten Cloudserver ermittelt: Chrony ist aktiv; chrony.service und +chronyd.service melden dieselbe vorhandene Dienstgeneration. Providerfall +`7534ada0-c4ce-47d0-a04f-8c0d94e9ba0d`, ResultatSHA256 +`11f7f1e9bd9af49127bb4745440a739e7a92faef70d17fb48291cc4688485181`. +Kein Dienststart, Zeitsetter, Resync oder D-Bus-Autoaktivieren. + +Eine getrennte feste `chronyc -n -c -h /run/chrony/chronyd.sock tracking`- +Abfrage lief mit Exit0, leerem stderr und14 CSVfeldern. Das geschützte +vorhandene Binary wurde gehasht, die Socketidentität vor/nach verglichen. +Fall `24390534-25f7-4f5f-a3c7-8ca3cb24aec1`, ResultatSHA256 +`33cffb1ec13647fbc09a7f989518e0162920aea3e99e9aba0ace4eb5b006fb20`. +Gemeldet wurden Stratum3/Normal; Peeradresse und Rohdaten bleiben privat. +Chrony dokumentiert CSV-Einheiten, Referenzmesszeit und die konservative +Fehlerschätzung aus verbleibender Systemkorrektur, Rootdispersion und halber +Rootverzögerung [im Primärhandbuch](https://chrony-project.org/doc/latest/chronyc.html). +Für genau diese Aufnahme ergeben sich 379.043210s Messalter und +0.011525568s geschätzte Fehlergrenze unter Chronys Referenzannahmen. +Das ist ein einmaliger Diagnosebefund, **keine qualifizierte Zeitquelle**. + +Vor einer Implementierung bleiben tatsächliche Kernelstatusprüfung, +authentisierte/beschränkte Provideranbindung aus der Serverlaufzeit, +frische gemeinsame Erfassung, konservative Gesamtschranken und deren +Linux-first-Nachweise offen. Die vorhandene CLI-Diagnose wird nicht als +fertiger Produktadapter übernommen. Die Userentscheidung genehmigt die Umsetzung; sie ersetzt diese technischen +Nachweise nicht. Windowsclock bleibt bis zur Qualifikation geschlossen. diff --git a/docs/windows-clock-descriptor-result.md b/docs/windows-clock-descriptor-result.md new file mode 100644 index 0000000..694da7b --- /dev/null +++ b/docs/windows-clock-descriptor-result.md @@ -0,0 +1,133 @@ +# V5-Serverdescriptor mit Discoveryprincipal: Fehler87 + +2026-11-14. Getrennter nicht qualifizierender Nachfolger der +[SID-/Descriptorprobe](windows-clock-identity-result.md). Der ursprüngliche +RPC-Befund ist vollständig erhalten. Der separat hängende Cleanupaufruf wurde +ohne Wiederholung des Originals aufgelöst; der eigene Diagnosedienst ist +inzwischen separat nachgewiesen entfernt. Produktclock und Windowsjobs +bleiben geschlossen; Fehler87 ist keine Clockabnahme. + +## Fester Vergleich und tatsächlicher Build + +Die vier eingefrorenen Quellen unter +`deploy/windows/clock-spnego-descriptor-trace/` behalten GSS9/Privacy6/ +Impersonate3 und QOS5 mit Mutual-Auth-Anforderung. Gegenüber dem vorherigen +SID-Vergleich verwenden sie `Sid=NULL` und exakt den tatsächlich vorhandenen +Discoveryprincipal, einschließlich einer vorhandenen leeren Zeichenfolge. +Ein NULL-Discoveryresultat bleibt verweigert. Discovery ist keine +Identitätsautorität. Der clientseitige Serverdescriptor bleibt absolut und +enthält genau eine feste ACE; keine Änderung einer OS-/Dienst-DACL. + +Kontrolle0 bindet darin die W32Time-Service-SID. Die fest kompilierten +Kontrollen1/2 sind falscher SYSTEM-Account beziehungsweise falsche +RmmDiscoveryWindows-Service-SID; beide wurden hier nicht nativ ausgeführt. +Einmalige Aktivierung und Wiederherstellung des eigenen vorhandenen Privilegs +bleiben diagnostische Tokenänderungen. Fremde Prozess-/Tokenhandles bleiben +QUERY-only. Kein Fallback, W32Time-Setter oder RMM-Job. + +Der vorbereitete lokale Build bestand C-Werror, unveränderten Microsoft-MIDL- +Compile, Link, Importgrenze, PowerShell-AST und Manifestprüfung. Keine erneute +Buildbehauptung aus der folgenden reinen Dokumentations-/Readerprüfung. +Manifest SHA256 +`34c51e005a90eb4344ffd31231a4b6df866d7f495f33fa81dcfcb8b34294dec7`; +PE117588Byte/SHA256 +`e7f2abc34b9c5ef5537892825724d15e488fdfd276de0d4468f6e1eae011769a`. +Die131 ursprünglichen Produktinputs,27 älteren Diagnoseinputs und die vier +neuen Descriptorquellen sind unverändert separat hashgeprüft. + +## Tatsächlicher VM-Befund + +Root führte nur Kontrolle0 im eigenen Fall +`4b1ae5cf-1573-4cac-8c01-17d1d36029c3` aus. Eigene Vorbereitung/Übertragung +und genau ein SYSTEM-Diagnosedienststart; anschließend getrennte Nur-Lese- +Readbacks desselben Falls: + +- SYSTEM-Token bestätigt, DienstStopped/Exit0; +- genau eine erfolgreiche Principaldiscovery, tatsächlich non-NULL und leer; +- QOS5/Control0 und vorhandener Serverdescriptor; +- `RpcBindingSetAuthInfoExW` verweigert87 bei Stage30; +- **null Statusqueries**, kein Statusobjekt oder normaler Statusreturn; +- EEInfo-Capture versucht, Start1761/keine Records; +- Principal- und Bindingfreigabe jeweils erfolgreich; +- eigenes Privileg vollständig wiederhergestellt, beobachtete Peertoken + unverändert; kein Agent-/W32Time-Konfigurationswechsel oder neuer RMM-Job. + +Original `diagnostic-result.json`, SHA256 +`27315e9a56735b929527f54309b3aecb372584f8f9a3efe689d7d3d230355121`. +`complete=true` bezeichnet den vollständig erhaltenen diagnostischen Fehler, +keinen positiven Clock-/Identitätsnachweis oder abgeschlossenen Cleanup. +Der Originalbericht enthält ausdrücklich `cleanup_completed=false`. + +Separater Erhaltungsbeleg vor/nach dem Diagnosebefund: sechs native +RMM-Bereiche und Servergate erhalten; Windows0/0/0/0, Linux31/31/27/0, +Rootpolicycf15 geschlossen, Transportfaults aus. Before-SHA256 +`54eb250bbdcbb49315bdb4dc23e01509497b8264249f5f4fc4756fe7290025e2`, +After-SHA256 +`eb0ee568745e488e38cc43a68c03424aab697c740168b8b22c31d627c2c035fe`. +Dieser Erhaltungsnachweis bestätigt noch keine spätere Cleanupauflösung. + +## Cleanupantwort verloren, eng begrenzter eigener Prozess beendet + +Der separat gestartete ursprüngliche Cleanupaufruf überschritt50s. +Sein lokaler Timeoutbeleg bleibt erhalten; remote war kein Cleanupmarker +nachgewiesen. Ein wiederholter Originalcleanup wurde ausdrücklich nicht +gestartet. Die Nur-Lese-Auflösung fand den eigenen hängenden +PowerShell-Bootstrapclient PID4460, exakte Erzeugungs-FILETIME +`134391586730921083`. + +Root prüfte dessen gehaltenes Prozesshandle, PID/Erzeugungszeit, Image und +genauen ursprünglichen Command und beendete ausschließlich diesen Client +einmal. Separater Beleg `spnego-descriptor-own-client-terminate-result.json` +im geschützten Pipefall14fb, SHA256 +`b3312d4abd8a2722f729eaac4a132909f6ae1f5072ced47be62b24ad788e5635`: +`terminated=true`, `wait_code=0`, `no_rmm_service_termination=true`, +`no_retry_original_cleanup=true`. + +Das beendet den alten Bootstrapclient und war alleine noch kein Beleg für +das Entfernen des Diagnosedienstes. Er blieb bis zur folgenden eigenen +Auflösung Stopped/registriert. Originalintent/-timeout/-result bleiben +unverändert; der Originalcleanup wurde nicht wiederholt. + +## Separate Cleanupauflösung tatsächlich abgeschlossen + +Root führte danach ausschließlich die neue eng gebundene Auflösung aus. +Das private Skript hat SHA256 +`573c0cf7512add7ef51f7c3d76609b1388536963c21ee5e435ba978921ec5d40`. +Es hält ein natives SCM-Servicehandle und prüft per `QueryServiceConfigW`/ +`QueryServiceStatusEx` exakt den ursprünglichen Image-/Argumentcommand, +LocalSystem, Manual, Servicetyp16 sowie Stopped/Exit0/PID0. Erst nach diesen +Prüfungen einmal `DeleteService`, Handle schließen und Abwesenheit prüfen. +Neue Resolution-Intent-/Completedmarker gehören ausschließlich zu dieser +separaten Phase; beide alten Remote-Cleanupmarker bleiben nachweislich false. + +Ergebnis `spnego-descriptor-cleanup-resolution-result.json`, SHA256 +`3c9bc0d4be2c5fb1cf404d4e94c492611662830c1867bc55bb96d53f4b80948d`; +separater Nur-Lese-Nachbeleg SHA256 +`d51b3c5e9811a04265c114ba3197c9d07f2700dd862d538b3735c6a5f4802a28`. +Beide bestätigen den eigenen Dienst als abwesend und keinen RMM-Wechsel. +Das originale `diagnostic-result.json` behält weiterhin seinen damaligen +Wert `cleanup_completed=false`; es wird nicht rückwirkend umgeschrieben. + +Vollständiger neuer Erhaltungsnachbeleg SHA256 +`df4b241d885d11c83c10562b8f31b9154f4c6dcfc54917e6a3d09257f3dd4c09`: +Root verglich erneut die sechs RMM-Erhaltungsbereiche `service`, +`helper_service`, `agent_kernel`, `helper_kernel`, `files`, `helper_witness` +mit dem vorigen eb0e-Beleg; bestanden. Der komplette Serverrecord ist gleich. Passive +Agenttelemetrie/Probe-/Journalbeobachtungen dürfen sich weiterentwickeln; +der gesamte native Rohbericht wird deshalb nicht als bytegleich behauptet. +Keine neue Diagnosequery, Jobwirkung oder W32Time-Änderung durch diese Auflösung. + +## Lokal nachgelesen und verbleibende Grenzen + +Der unveränderte lokale Manifestreader sowie Report-/Privilegewitnessreader +wurden auf den erhaltenen Originaldateien erfolgreich ausgeführt; beide +Pythonquellen zusätzlich per AST geparst. Diese Prüfungen starten weder SSH +noch einen Prozess auf einem Ziel. `git diff --check` betrifft die vorbereiteten +Quellen-/Dokumentationsänderungen. Kein erneuter Compiler-/VM-/Joblauf. + +Die anschließende [statische RPC-Runtimeanalyse](windows-clock-rpc-qos5-analysis.md) +grenzt die Verweigerung des konkreten OS-Stands ein. Sie ist kein nachträglich +erfundener dynamischer Trace und begründet keinen weiteren Formatclone. +Der [Zeitbeleg-ADR](windows-clock-attestation-proposal.md) ist ausschließlich +ein entscheidungsbedürftiger Vorschlag; keine angenommene Trustsource oder +implementierte Clockalternative. Keine Capability oder Policy aktiviert. diff --git a/docs/windows-clock-eeinfo-trace.md b/docs/windows-clock-eeinfo-trace.md new file mode 100644 index 0000000..dd7eb9d --- /dev/null +++ b/docs/windows-clock-eeinfo-trace.md @@ -0,0 +1,190 @@ +# Begrenzter EEInfo-Nachfolger: Fehlerlage statt Ursachenbehauptung + +Stand 2026-11-14: **separat implementiert, lokal gebaut und durch den +verantwortlichen Rootprozess einmal auf der Windows-VM ausgeführt**. Dieser +Subagent führte keine VM-Aktion aus. Der tatsächliche vorherige SYSTEM-Vergleich +`562ff9de-67ff-48a1-96f0-c2474b3b0777` meldete wie LocalService RPC5/Stage90 +ohne Status oder normalen RPCreturn. Die einfache Erklärung durch ausschließlich +LocalService ist damit nicht belegt. Authentifizierungs-/Autorisierungsschicht +und tatsächliche serverseitige Calleridentität bleiben offen. Kein Produktgate +wird aus diesem Befund geöffnet. + +## Microsoft-Quellen und konkrete Grenzen + +Die [V5-QoS-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w) +beschreibt den Serverdescriptor nur allgemein. Sie dokumentiert für unser +lokales `ncacn_np` keinen vollständigen Vertrag, der genau den tatsächlichen +Serverprozesstoken einschließlich W32Time-Service-SID beweist. Die +[SDK-Deklaration](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/shared/rpcdce.h) +belegt das Layout, nicht diese Laufzeitsemantik. Microsoft warnt außerdem, dass +NTLM erfolgreiche Mutual-Auth-Aushandlung melden kann, obwohl echte gegenseitige +Authentifizierung fehlt. V5, ein gesetztes Flag oder erfolgreicher SetAuth-Aufruf +sind deshalb kein selbständiger Konto-/Service-SID-Nachweis. Das ist eine +verbleibende Nachweislücke, keine Behauptung, der Descriptor könne grundsätzlich +nie wirksam sein. Microsoft-Q&A-Erfahrungsberichte wurden nicht als verbindliche +Produktgarantie verwendet. + +Die LocalService-Beschreibung anonymer **Netzwerk**credentials beweist keinen +anonymen SSPI-Caller dieser lokalen NPFS-Verbindung. Laut +[RPC-Credentialsvertrag](https://learn.microsoft.com/en-us/windows/win32/rpc/client-authentication-credentials) +werden implizite Credentials aus Thread-/Prozesstoken gewonnen. Die tatsächlich +vom Server verwendete Identität lässt sich nicht einfach aus einem Client- +Account oder den konfigurierten Bindungsoptionen ablesen. Die dokumentierte +[Callattributes-Struktur](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/ns-rpcasync-rpc_call_attributes_v2_w) +enthält Authentifizierungsdaten und NullSession, wird jedoch serverseitig mit +`RpcServerInqCallAttributes` abgefragt; sie ist keine Clientabfrage in W32Time. + +EEInfo kann die Fehlerlage eingrenzen: Microsoft benennt unter anderem SSP, +NPFS/Redirector/Named Pipe und Authz als +[GeneratingComponents](https://learn.microsoft.com/en-us/windows/win32/rpc/understanding-extended-error-information). +Eine einzelne Zahl beweist weiterhin weder einen anonymen Caller noch die +konkrete verweigernde ACL. Fehlende Records sind kein Gegenbeweis: +[EEInfo ist standardmäßig grenzüberschreitend deaktiviert](https://learn.microsoft.com/en-us/windows/win32/rpc/security-and-extended-error-information). +Der neue Versuch schaltet keine Registry-/Audit-/EEInfo-Policy um. + +## Exakt begrenztes Source-Delta + +Neue sibling-Dateien unter `deploy/windows/clock-eeinfo-trace/`, eigener Dienst +`RmmClockSystemEeInfoDiagnostic`, eigene History. Original131, alter Wrapper +und vorheriger SYSTEMrunner bleiben unverändert und readbackfähig. + +`clock_rpc_eeinfo.c` ist eine sichtbare Diagnosequellvariante gegenüber +`clock_rpc.c`, Original-SHA256 +`74aceb6e2b70c5dd628fae069a842c356c20300b8c8ab12754258c78eaf295c8`. +Der Build speichert `wrapper-source.diff` samt Hash. Änderungen ausschließlich: +`rpcasync.h`, fester104Byte-Numerikpuffer, Parameterweitergabe, neuer +Diagnoseexport und Capture im bestehenden `RpcExcept` direkt nach dem lokal +gespeicherten ursprünglichen Exceptioncode. Auth-/Endpunkt-/NDR-/QoSzeilen +bleiben gleich. Originalcode5 wird nicht durch Enum-Returncodes ersetzt. + +Die tatsächlichen SDK-Prototypen werden aus dem Header verwendet: +`RpcErrorStartEnumeration(RPC_ERROR_ENUM_HANDLE*)`, +`RpcErrorGetNextRecord(RPC_ERROR_ENUM_HANDLE*, BOOL, RPC_EXTENDED_ERROR_INFO*)` +und `RpcErrorEndEnumeration(RPC_ERROR_ENUM_HANDLE*)`. +Microsoft verlangt den [sofortigen Enumerationsstart](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorstartenumeration), +da spätere Aufrufe die Threaddaten überschreiben können. Der Start steht vor +jedem weiteren RPC-/BindingFree-Aufruf im Handler. + +Höchstens vier NextRecord-Aufrufe, keine fünfte Abfrage. Je Record verlassen +nur GeneratingComponent, Status, DetectionLocation, Flags und NumberOfParameters +C. Keine Parameterwerte, Strings, ComputerName, Binary-/Pointerdaten oder +Zeit-/Namensfelder werden kopiert/exportiert. Gemäß +[GetNextRecord](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorgetnextrecord) +werden Version, Flags und **MaxNumberOfEEInfoParams** als Eingabekapazität gesetzt; +Nullkapazität könnte sonst BUFFER_TOO_SMALL auslösen. CopyStringsFALSE bedeutet +geborgte RPC-Daten, die der Aufrufer weder verändert noch freigibt. Bei +erfolgreichem Start wird immer +[EndEnumeration](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorendenumeration) +aufgerufen. `limit_reached=1` bedeutet ausschließlich erreichtes Viererbudget, +keinen Beweis eines weiteren Records. + +Die neue SID18-Servicehülle ruft genau einmal denselben Tracepfad auf. Höchstens +4096Bytes Ergebnis, ausschließlich numerische Zusatzdaten und feste Labels; +clock/adapter/productgate bleiben false. Keine Impersonationserhöhung, +Anonymous-/unauthenticated-Fallbacks, ACL-, NTP- oder Accountänderung. +Prepare/Start/Readback/Cleanup bleiben getrennt; Cleanup nur eigener eindeutig +gebundener gestoppter Dienst, Remote-Readback ausschließlich lesend. + +## Tatsächlich lokal geprüft + +```text +python3 deploy/windows/clock-eeinfo-trace/build.py +``` + +Offline im gepinnten bisherigen Image gebaut. Neue C-Hülle/Wrapper bestehen +`-Wall -Wextra -Werror`; nur dieselben drei bekannten Stilwarnungen am +unveränderten echten Microsoft-MIDL-Stub bleiben sichtbar. Kein Typ-/Security- +Warning wurde unterdrückt. Link/PE-x64-/Import-/private Manifestguards bestanden, +ebenso der tatsächliche PowerShell-AST-Lauf; EncodedCommand16718Zeichen. +Imports nur ADVAPI32/KERNEL32/RPCRT4/msvcrt. + +Finaler Manifest: +`devstate/windows-clock-eeinfo-trace/build-8d33bc4b-a0ce-430e-aa5b-5d1dc112ecf0/manifest.json`, +SHA256 `2b10417c41ff5c293f71e303b703e8d883d3ba7bc361bb047417d5de66124b49`. +PE101312Bytes, SHA256 +`cef50aa281069c76494f88ef893191e3978f9a3c66d162658f5914a5193d2787`. +Der frühere lokale Pack `9ca2ff31…` bleibt erhalten und wird nicht für die +Probe verwendet; der finale Driver bindet zusätzlich den sichtbaren Diff und +prüft ursprünglichen Exceptioncode gegen Originaltrace. + +Acht manipulierte Record-/Reportfälle, Viererbudget, ursprünglicher RPCcode, +String-/Parameterverweigerung, kein Datenbeleg bei leerem EEInfo und rein +lesendes Readback wurden lokal mit ausdrücklich **simulierten** Reports geprüft. +Diese dürfen eine vollständig ausgeführte Diagnose darstellen, beweisen aber +keinen echten RPC-/Status-/Clockerfolg. `local-guards.json` kennzeichnet die +Mocks und `native_executed=false`; alte SYSTEMdateien wurden bytegleich +nachgeprüft. Keine SSH-/VM-/Dienst-/RMM-Aktion durch diesen Subagenten. + +## Tatsächliche einmalige Root-Probe und getrenntes Readback + +Root führte den freigegebenen finalen Pack im Fall +`e4e6e12f-6c1b-4bd2-8072-70c5e6634aa6` auf der Windows-VM aus. Der eigene +SYSTEM-Diagnosedienst meldete genau einen Queryaufruf und beendete sich mit +Service-Exitcode0; die RPC-Abfrage selbst blieb ausdrücklich fehlgeschlagen: +`token_system=true`, RPC5, Stage90, Exception5, kein normaler RPCreturn und kein +Statusobjekt. Service-Exit0 ist hier ausschließlich Abschluss der Diagnose. +Clock-, Adapter- und Produktgate blieben false. Kein RMM-Job entstand. + +Die unmittelbar im Exceptionhandler erfassten numerischen EEInfo-Daten sind: + +| Feld | Tatsächlicher Wert | +| --- | --- | +| capture_attempted / start_status | 1 / 0 | +| next_status / end_status | 1761 / 0 | +| count / limit_reached | 1 / 0 | +| generating_component / status | 2 / 5 | +| detection_location / flags / number_of_parameters | 1750 / 0 / 1 | + +Keine Parameterwerte, Strings, Rechnernamen oder Binary-/Pointerdaten wurden +exportiert. Der lokal erhaltene `diagnostic-result.json` hat SHA256 +`80accca4f99a2ede0ccb3fd0a21730f69a53a6310c6c6ead42aa4d958c56b6f4`. +Ein gesonderter lesender Aufruf lieferte dasselbe vollständige Reportobjekt: +`readback-2a256a82-5e0d-4895-b3d9-0a67cfa841e8.json`, SHA256 +`93a1655fa4327579580e6df661ec7243af282af1f175735d882ccbd1ec9002b5`. +Die Dateien liegen im privaten ursprünglichen Caseverzeichnis unter +`devstate/windows-clock-eeinfo-trace/`; keine Zugangsdaten oder Transportpräfixe +gehören zum publizierbaren Beleg. + +Root entfernte anschließend ausschließlich den eigenen gebundenen gestoppten +Diagnosedienst. Der separate Cleanupbeleg +`readback-a1ef841d-218e-4adc-9075-1af320baf1f5.json`, SHA256 +`c03b535f21f430399f9ae3fbdca8d1e869b80ae6567b762eded04f208a68fcc3`, +meldet `cleanup_verified=true`; das war eine explizite Cleanupaktion, kein +lesender Aufruf. Root hat zusätzlich die vollständige Preservationprüfung +abgeschlossen: ursprüngliche Agent-/Helperdienste und Prozessgeburten, Codehashes, +FileIDs, PKI-/Datenbankzeugen und serverseitiger Zustand stimmen vor/nach exakt +überein. Keine neuen Jobs, Clockgate weiterhin false. Vorherbeleg-SHA256 +`3d508df7a46b3ab181f9d9575432e544627609fed98c77dabb107a7798bcb87b`; +Nachherbeleg `eeinfo-trace-after.json` im ursprünglichen privaten +`windows-pipe-drain/devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`-Kontext, +SHA256 `921cd12b8f90c0921a6a11ec48d3ef61d4fffb2f6f3979f5f8731d2ac6425240`. +Das ist ein Erhaltungsnachweis der Diagnose, kein erfolgreicher Clock-/Jobnachweis. + +## Belegte Deutung und verbleibende Grenze + +Microsoft ordnet [GeneratingComponent2 der RPC-Runtime zu](https://learn.microsoft.com/en-us/windows/win32/rpc/understanding-extended-error-information). +Status5 bezeichnet [Access denied](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-). +Dies benennt den meldenden Layer und den Fehler, weder die konkrete verweigernde +ACL noch den tatsächlichen serverseitigen Caller oder einen anonymen SSPIkontext. + +DetectionLocation ist laut derselben EEInfo-Dokumentation ein von der +Implementierungsversion abhängiger interner Codeort. Die öffentliche +[Detection-Locations-Tabelle](https://learn.microsoft.com/en-us/windows/win32/rpc/extended-error-information-detection-locations) +gilt ausdrücklich für WindowsXP und enthält1750 nicht. Auch +[MS-EERR2.2.3](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-eerr/92064599-dc99-4e86-a887-b377a95ac678) +liefert keine Zuordnung für1750/Component2. Die geprüften Primärquellen erklären +diesen Windows-11-Codeort somit nicht. Die Zahl1750 ist hier außerdem kein +Win32-Returncode und darf nicht als dessen Fehlername dekodiert werden. + +Der Enumstatus1761 ist gemäß [GetNextRecord-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcasync/nf-rpcasync-rpcerrorgetnextrecord) +das normale Ende nach dem letzten erfolgreich gelesenen Record. Ein Record +wurde erfasst, das Viererbudget nicht erreicht; dies ist kein Enumfehler anstelle +des ursprünglichen RPC5. Flags0 meldet keine Missing-Record-Flags. Microsoft +beschreibt EEInfo dennoch ausdrücklich als [best effort und ungeeignet für Produktentscheidungslogik](https://learn.microsoft.com/en-us/windows/win32/rpc/reliability-of-extended-error-information): +eine vollständige Ursachen- oder Nichtanonymitätsgarantie folgt daraus nicht. + +Die enge Diagnose hat damit einen tatsächlichen Runtime-EEInfo-Beleg geliefert, +keinen W32Time-Status oder Clocknachweis. Eine weitere Deutung des Codeorts +braucht einen zum tatsächlichen Windows-/RPC-Build passenden Primärnachweis. +Keine ACL-/Konto-/Auth-/NTPänderung und keine Ersatzclock/Brokerarchitektur wird +aus diesem Record abgeleitet; sämtliche Produktgates bleiben geschlossen. diff --git a/docs/windows-clock-identity-result.md b/docs/windows-clock-identity-result.md new file mode 100644 index 0000000..fba4a44 --- /dev/null +++ b/docs/windows-clock-identity-result.md @@ -0,0 +1,69 @@ +# V5-SID-/Service-Descriptorprobe: Bindung verweigert + +2026-11-14. Nach dem [erfolgreichen reinen RPC-Vergleich](windows-clock-impersonate-result.md) +wurde eine getrennte, ausdrücklich nicht qualifizierende Identitätsprobe +vorbereitet. Die Produktdateien und alle früheren Reader/Belege blieben erhalten. + +Die vier Quellen `deploy/windows/clock-spnego-identity-trace/` verwenden +GSS9/Privacy6/Impersonate3 sowie QOS5 mit Mutual-Auth-Anforderung, fester +Account-SID als dokumentierter Alternative zum Authprincipal und einem +clientseitigen Serverdescriptor mit fester Service-SID. Die tatsächlich +zurückgegebene Discoveryzeichenfolge wird weiterhin geprüft und freigegeben; +sie wird nicht als Identitätsautorität übernommen. Die Bindung verwendet hier +ausdrücklich NULL für ServerPrincName und dafür den festen SID-Parameter. +[Dokumentierter QOS5-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w). + +Drei eng geschlossene Buildkontrollen sind vorgesehen:0 für LocalService/ +W32Time,1 für falschen Systemaccount,2 für falsche RmmDiscoveryWindows-Service-SID. +Die Kontrolle wird fest kompiliert und im Manifest gebunden; der tatsächliche +numerische Report muss exakt dazu passen. Kein Setter, Fallback, RMM-Job oder +Produktgate. Derselbe eigene Enable-/Restoreablauf mit ausschließlich lesenden +fremden Tokenhandles und erhaltener Prozessbindung bleibt bestehen. + +Tatsächliche lokale Prüfung: Der erste Build `bafde30c…` scheiterte vor Link +an einer fehlenden QOS5-Typdeklaration im neuen Wrapper. Der fehlende Block +wurde danach bytegleich aus dem bisherigen Produktwrapper übernommen, +einschließlich x64-/SDK-ABI-Assertions. Kein Compilerfehler wurde unterdrückt. +Der neue Build für Kontrolle0 bestand C-Werror, unveränderten Microsoft-MIDL- +Compile, Link, Importgrenze, PowerShell-AST und lokalen Manifestreader. +Unabhängiger Quellenreview ohne weitere Funktionsblocker;131 Produktinputs +und23 frühere Diagnoseinputs unverändert. Kontrollen1/2 wurden noch nicht gebaut +oder auf der VM ausgeführt. + +Manifest `d3a6222da8aed64e4e5ad5c07993177a11f56af229d4754ea04f248ee79385bc`, +PE117586Byte/SHA256 +`5c55327f5569723875bb4b2622dd12fda76dbb041ea80d0a64324acc940440ba`. + +## Tatsächlicher VM-Befund + +Root führte ausschließlich Kontrolle0 im eigenen neuen Fall +`bcda2ede-d3e0-41bf-94e9-9f44ea785c54` aus. Einmalige Vorbereitung/Übertragung +und ein eigener SYSTEM-Dienststart, anschließend separater lesender Readback: + +- DienstStopped/Exit0, Diagnose vollständig aufgezeichnet; +- eine erfolgreiche Discovery mit tatsächlich nicht-NULL leerem Principal; +- QOS5/Control0, Serverdescriptor vorhanden; +- `RpcBindingSetAuthInfoExW` verweigert mit87 bei Stage30; +- **null Statusqueries**, kein normaler Statusreturn und kein EEInfo-Record; +- eigenes vorhandenes Privileg nach Aktivierung vollständig nachgelesen + zurückgesetzt, beobachtete Peertoken unverändert; +- anschließend ausschließlich der eigene gestoppte Diagnosedienst entfernt. + +Endbeleg `diagnostic-result.json`, SHA256 +`ce4004b1fd833b9590f23d31a918daefccf8870e6630be6beb28869fad1f8b5c`. +Separater Erhaltungsnachweis: alle sechs bestehenden nativen RMM-Bereiche +und Servergate gleich, Windows0/0/0/0 und Linux31/31/27/0, Rootpolicycf15 geschlossen. +Before-SHA256 `ee28b23c474958b47ebeb50e03e3c2b21df4bddfc777583908921d5b4982de77`, +After-SHA256 `de130d3e6f279d84f8b56cc896fd50ef04415b09f6349eb615eda87971ca97a7`. +„Diagnose vollständig“ bedeutet hier einen vollständig erhaltenen Fehlerbefund, +keinen positiven Identitäts- oder Clocknachweis. Weil schon die erwartete +Identität keinen Statuspfad erreicht, wurden keine negativen Identitätskontrollen +als vermeintliche erfolgreiche Sicherheitsabnahme nachgeschoben. + +Der konkrete Parameterverbund ist damit auf dieser VM nicht zugelassen. +Welcher einzelne Parameter diese87-Ablehnung verursacht, ist noch nicht isoliert. +Insbesondere wird daraus weder eine generelle Nichtunterstützung jeder V5- +Named-Pipe-Konfiguration noch eine erlaubte Lockerung der Produktidentität +abgeleitet. Eine weitere dokumentierte Parameteralternative benötigt einen +separaten Quellen-/Build-/Nativefall. Produktclock/Jobs bleiben geschlossen. +NTPresync wartet weiterhin auf die konkrete Benutzerfreigabe. diff --git a/docs/windows-clock-impersonate-result.md b/docs/windows-clock-impersonate-result.md new file mode 100644 index 0000000..79909dd --- /dev/null +++ b/docs/windows-clock-impersonate-result.md @@ -0,0 +1,102 @@ +# Nativer RPC-Vergleich: Impersonate statt Identify + +2026-11-14. Der getrennte Diagnosefall +`daf8205c-a110-4fb7-9ae0-f27ca1532d8f` liefert erstmals einen normalen +erfolgreichen W32Time-Statusreturn. **Keine Produktclockfreigabe:** Dienstidentität, +LocalService-Pfad und tatsächliche Zeitqualität sind weiterhin separat nachzuweisen. + +## Konkreter Anlass und geprüfter Unterschied + +Die [vorherige Diagnose](windows-clock-process-privilege-result.md) hatte trotz +nachgewiesen aktivem vorhandenem Prozessprivileg weiterhin RPC5/Stage90 ergeben. +Der Windows-eigene `w32tm /query /status /verbose` dagegen lieferte als +bestehender Admintransport Exit0. Seine Ausgabe war selbst Leap3/Stratum0, +nicht synchronisiert; damit bestehen unabhängige Transport- und Zeitqualitätsgates. + +Root las ausschließlich die vorhandenen Microsoft-Systemdateien `w32tm.exe` +und `w32time.dll`, prüfte SignaturstatusValid und identische SHA/Länge vor und +nach der privaten Kopie. Keine Installation oder DLL-/Produktänderung: + +| Datei | Bytes | SHA256 | +| --- | ---: | --- | +| w32tm.exe | 274432 | `e81bcc55d0ed5d744b2f23417e9b2706e17a1c02a340503887679f54005570e5` | +| w32time.dll | 745472 | `38c2efef83c2becb913d820b02fb16e987eccebf06ae4072093632b4c3bcc2ab` | + +Lokale PE-Analyse dieser konkreten DLL: Der Export `W32TimeQueryStatus` +(RVA280d0) ruft Discovery mit GSS9 und anschließend +`RpcBindingSetAuthInfoW` mit Privacy6 auf. Der gefundene serverseitige +Callback ruft nach `RpcImpersonateClient(NULL)` +`OpenThreadToken` mit TOKEN_QUERY und OpenAsSelfFALSE auf. Das ist ein +versionsgebundener Binärbefund, kein allgemeiner Vertrag jeder Windowsversion. +Microsoft dokumentiert, dass das Öffnen des Tokens auf Identification-Stufe +OpenAsSelfTRUE benötigt, da diese Stufe keine Executiveobjekte öffnen darf. +[OpenThreadToken-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthreadtoken). +Die RPC-Standardstufe ist Impersonate, wenn die höhere Ebene nichts anderes +vorgibt. [MS-RPCE](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rpce/fd5d5c6e-80f4-49b5-887f-4ce844cc62c4). + +Deshalb wurde ein neuer, ausdrücklich getrennter Diagnosekandidat erstellt: +die RPC-Stufe wechselt von Identify2 auf Impersonate3. Das erlaubt dem lokalen +RPC-Server die lokale Impersonation des Diagnoseprozesses; es ist keine +Delegatestufe und keine stille Produktlockerung. Namen/Fallprofil/Elternbezüge +sind getrennt. GSS9, Privacy6, tatsächlicher zurückgegebener nicht-NULL +Principal einschließlich Emptystring, eine Discovery und höchstens eine +Opnum6 bleiben unverändert. Kein Authfallback oder Setter. Der gleiche +SYSTEM-Own-Token-Enable-/PreviousState-Restoreablauf und die vier gehaltenen +Peerprozesse mit ausschließlich TokenQUERY bleiben erhalten. + +## Tatsächliche lokale und native Ergebnisse + +Die vier neuen Quellen unter `deploy/windows/clock-spnego-impersonate-trace/` +wurden unabhängig geprüft. Manifest +`5644a50aee329144cb32c5bf0ebf4992ec068c59ca024416b66e8201366fd702`, +PE114089Byte/SHA256 +`885a6f28df76ebc06e1457628cb4387bc9c0fa822b750fd29ce29d50aaf08fa5`. +Tatsächlich bestanden: C-Compile mit Warnungen als Fehler, unveränderte +Microsoft-MIDL-Ausgaben, Link, DLL-Importgrenze, PowerShell-AST sowie lokaler +Manifestreader. Original131 Produktinputs,19 vorherige Diagnoseinputs, +Elternmanifest6c976583 und ursprünglicher Fehlerbelegc7556589 bleiben bytegleich. + +Root bereitete den separaten Fall vor, übertrug dessen feste EXE und startete +genau einmal den eigenen temporären SYSTEM-Dienst. Tatsächlich: + +- DienstStopped/Exit0; vollständiger normaler Return, RPC0, Stage80; +- native Rückgabe0, Status vorhanden, ulSize120, cEntries0, pEntriesNULL; +- genau eine erfolgreiche Principaldiscovery, tatsächlich nicht-NULL/leer, + genau eine Opnum6 mit GSS9/Privacy6/Impersonate3; +- keine RPC-Ausnahme und kein EEInfo-Record; +- genau ein erfolgreiches Aktivieren des vorher vorhandenen Privilegs und + nachgelesene vollständige Rücksetzung; alle beobachteten Peertoken unverändert. + +Ein separater rein lesender Same-case-Aufruf bestätigte das Originalergebnis; +anschließend wurde ausschließlich der eigene gestoppte Dienst entfernt. +Endbeleg `diagnostic-result.json`, SHA256 +`26a06f8f46a7b5fa173c5ee81cd97a4542571a7b97b15fd5e0e8a41315680c4e`. +Zusätzliche native Erhaltungsnachlese bestanden: sechs bestehende RMM-Bereiche +und vollständiger Servergate gleich; Windows0/0/0/0, Linux31/31/27/0, +Rootpolicycf15 geschlossen. Before-SHA256 +`d0f45d6d25936de2d4d66ef79b9bd3a1bb9bd5013cbbcd7ef3d145703e6c96cd`, +After-SHA256 `792e164fcdc567c3ac620d89a7d8907ab6d80b9485e135c6744c92191eae31fe`. + +Im kontrollierten Vergleich ändert der explizite RPC-Stufenwechsel das Ergebnis +von5/Stage90 auf0/Stage80. Das stützt die konkrete Identify-/Callbackursache; +ein interner Fehlerort des früheren fehlgeschlagenen Aufrufs wurde nicht +serverseitig instrumentiert. Eine Discovery oder der zurückgegebene SPN, +insbesondere unter NTLM, ist weiterhin kein unabhängiger Dienstidentitätsbeweis. +Der Diagnosepfad enthält keine Produktionsfreigabe oder RMM-Jobausführung. + +## Weiter offen + +Die Produktclock braucht einen nachgewiesenen Account-/W32Time-Servicebezug +mit passenden tatsächlichen negativen Identitätskontrollen; außerdem einen +nativen LocalService- und Unsicherheits-/Kontinuitätsnachweis. Die vorhandene +VM-Uhr ist laut Builtinstatus unsynchronisiert. Zwei rein lesende NTP- +Stripchartproben zum bereits konfigurierten Peer antworteten; privater Beleg +`156f5df32f54f3886b9712eecee6f73d7f08b3ddb3b216e9219137c89dc15785`. +Dies prüft den Stripchartpfad und beweist nicht die erfolgreiche +W32Time-Synchronisierung über dessen eigenen Quellport. Ein einmaliger +`w32tm /resync` wurde dem Benutzer konkret zur Freigabe vorgelegt und hier +noch nicht ausgeführt. NTPserver/Peers, Startart, ACLs, Rechtezuweisung, +Produktdateien, Clockgate und Windows-RMM-Verbrauch blieben unverändert. + +Private Belege einschließlich PE-Kopien/Disassembly bleiben gitignoriert; +Microsoft-Binärdateien oder deren vollständige Disassembly werden nicht publiziert. diff --git a/docs/windows-clock-midl-codegen.md b/docs/windows-clock-midl-codegen.md new file mode 100644 index 0000000..3387e3f --- /dev/null +++ b/docs/windows-clock-midl-codegen.md @@ -0,0 +1,107 @@ +# Nächster Clock-Diagnosekandidat: Microsoft-MIDL-Codegenerierung + +Stand 2026-11-14. **Geplant, nicht auf der Windows-VM ausgeführt.** Der +Narrow-IDL-Pointerkandidat `91889303…` liefert laut getrenntem nativen +Root-Beleg weiterhin `1783` in Trace-Stage 90, ohne normale RPC-Rückkehr und ohne +Status. Seine einzelne Pointeränderung ist damit nicht als ausreichender Fix +belegt. Das beweist nicht, dass Pointersemantik irrelevant ist. ALPC `1753` und +das geschlossene Clock-Gate werden davon nicht verändert. + +## Enger nächster Nachweis + +Microsoft beschreibt [MIDL-generierte Clientstubs](https://learn.microsoft.com/en-us/windows/win32/midl/files-generated-for-an-rpc-interface) +als vorgesehenen Weg; die [NDR-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/rpc/rpc-ndr-engine) +rät ausdrücklich von handbearbeiteten Stubdaten ab. Deshalb folgt kein weiterer +Formatbytepatch. Ein separat gehaltener Microsoft-Generator soll denselben +Quellvertrag erzeugen, bevor ein weiterer RPC-Diagnosekandidat gebaut wird. + +Das offizielle [SDK-NuGet-Paket 10.0.26100.9169](https://www.nuget.org/packages/Microsoft.Windows.SDK.CPP/10.0.26100.9169) +wurde ausschließlich auf dem Entwicklungsrechner über verifiziertes TLS geladen +und als ZIP aufgelistet, nicht installiert oder ausgeführt. Privater Fall: +`devstate/windows-clock-midl/6b7fb9b1-0bb7-4880-850b-e6812d3df1b1`. +Paket: 160512239 Bytes, SHA-256 +`475269434dcd808a67853773272f972c3229c0e10c3ddc821290e70cc0f6904d`. + +Genau die enthaltenen Tools `c/bin/10.0.26100.0/x64/midl.exe` und `midlc.exe` +reichen nach statischer Importprüfung als Kandidat: beide importieren nur +`KERNEL32.dll` und `msvcrt.dll`. Das ist noch kein Beweis, dass sie auf dem Ziel +ohne weitere Abhängigkeit laufen. Tool-SHA-256: + +- `midl.exe`, 154048 Bytes: + `7a2a717be64f755390ad8b04cb034549b2606acec646ec7cbe44c67516ccba83`. +- `midlc.exe`, 1366464 Bytes: + `34293d7bd256f2d43311d197f13bbb8a1ae26c92cc1605d9f35dd3ddfe264b65`. + +**Microsoft-Authenticode und Zertifikatskette sind noch nicht geprüft.** +Der Paketdownload und ein berechneter Hash ersetzen diese Prüfung nicht. +Vor Toolausführung müssen die exakten Dateien am Ziel einen gültigen erwarteten +Microsoft-Signer und dieselben Hashes besitzen. Keine Trust-/Zertifikatänderung. + +## Geplanter begrenzter Ablauf + +Ein eigener create-only Fall erhält Quellen, Toolhashes und vor dem Start einen +dauerhaften Startintent. Es werden nur die beiden Tools und die gehashte +IDL-Quelle in ein eigenes Administratorverzeichnis übertragen. Keine Installation, +kein Registry-/PATH-/Policy-/Servicewechsel und keine RPC-/RMM-Ausführung. +Verlorene Antwort bedeutet ausschließlich Readback desselben Falls, keinen +neuen Toolstart. Toolausgabe und erzeugte Dateien bleiben als private Originale +erhalten; Ausgangsquellen werden nicht überschrieben. + +Geplante feste Argumente: + +```text +/nologo /no_cpp /env amd64 /Oicf /robust /Zp8 /protocol dce +/client stub /server none /h w32time.h /cstub w32time_c.c w32time.idl +``` + +[`/no_cpp`](https://learn.microsoft.com/en-us/windows/win32/midl/-no-cpp-nocpp) +ist der offizielle Verzicht auf den C-Präprozessor. Die enge Quelle besitzt keine +Includes oder Präprozessordirektiven; ein fehlendes CL soll nicht durch +Installation/Policyänderung kompensiert werden. [`/env amd64`](https://learn.microsoft.com/en-us/windows/win32/midl/-env) +setzt das tatsächliche x64-Ziel und 8er-Packung; +[`/protocol dce`](https://learn.microsoft.com/en-us/windows/win32/midl/-protocol) +hält die bisherige DCE-NDR-Transfersyntax konstant. Es gibt keine stillschweigende +NDR64-Umstellung. + +Zuerst werden die originale [Microsoft-Voll-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a) +und die unveränderte enge Quelle separat generiert. Zu vergleichen sind der +Opnum-6-Vertrag, der vollständige Pointerpfad, expliziter Bindinghandle, alle +19 Statusfelder und der 120-Byte-x64-ABI. Die Voll-IDL ist ausschließlich +Vergleichseingabe; ihre anderen Operationen werden niemals aufgerufen. + +Nur nach erhaltenem nativen Codegenbeleg kann ein neuer separat gehashter +Diagnosebuild mit **unverändertem generiertem** Clientstub und bisherigem +C-Wrapper untersucht werden. Ein konkretes Compiler-/Headerproblem muss offen +benannt werden; kein manuelles Umschreiben von NDR-Daten. Authentisierung, +Endpoint, SEH-Grenze, Allocatorgrenze, Statusguard und `ADAPTER_QUALIFIED=false` +bleiben unverändert. Ein lesbarer Named-Pipe-Status allein ist keine qualifizierte +Clock oder Helper-Zeitautorität. + +## Vorbereiteter Runner (weiterhin kein Zielnachweis) + +`deploy/windows/midl_codegen.py` implementiert die getrennten Aktionen +`prepare`, `start`, `readback` und verwendet ausschließlich den streng geparsten +bestehenden SSH-Bootstrapzugang aus dem expliziten Hauptrepo-Accessroot. Der +15-KiB-Body wird als gehashte `MidlCodegen.ps1` übertragen und regulär mit +prozessbezogenem `RemoteSigned` als Datei aufgerufen; kein großer +EncodedCommand und kein ScriptBlock-Dateiausführungsersatz. + +Vor Start prüft der Runner gültiges Microsoft-Authenticode, die Onlinekette, +Hash, Länge und die tatsächliche feste Tool-Dateiversion `8.1.628.1`. Die +zugehörigen lokalen PE-Zertifikatsmetadaten wurden lediglich gelesen; das ist +noch keine Authenticodeprüfung. Ein vor `CreateProcessW` installierter +`PROC_THREAD_ATTRIBUTE_JOB_LIST` ordnet den MIDL-Prozess samt seinen eigenen +Nachkommen atomar einem unbenannten Kill-on-close-Job zu; höchstens zwei +Prozesse, ausschließlich drei Standardhandles geerbt, kein später +Assign-Fallback. Nach zehn Sekunden oder überschrittenem Outputlimit wird nur +dieser eigene Job beendet, höchstens insgesamt zwei weitere Sekunden beobachtet +und dann geschlossen. Auch die Pfade für Header und Clientstub sind fest, +jeweils höchstens 256 KiB. Kein globales Compiler-/Installer-Kill. + +Lokale Qualification: +`devstate/windows-clock-midl/6b7fb9b1-0bb7-4880-850b-e6812d3df1b1/runner-final-qualification/qualification.json`, +SHA-256 `dab36fbab3e407cbae6d97f27068abe8f57cc13243b94b4fd95fe9108dc7a508`. +Python-Syntax, drei PowerShell-ASTs ohne Fehler und reine C#-Deklarationskompilierung +bestanden; keine Win32-Funktion aufgerufen, keine Zielverbindung. +Runner-SHA-256: +`078bf2303979dbeccdb7eb84e116325e7f155146d93d0dc0fff6b3e6bdd1b2eb`. diff --git a/docs/windows-clock-midl-diagnostic-build.md b/docs/windows-clock-midl-diagnostic-build.md new file mode 100644 index 0000000..a38435b --- /dev/null +++ b/docs/windows-clock-midl-diagnostic-build.md @@ -0,0 +1,237 @@ +# Getrennter Diagnosebuild mit tatsächlichem Microsoft-MIDL-Output + +Stand 2026-11-14. Eigene Buildquelle; keine Änderung des Produktbuilders, +der bisherigen Runner oder früherer Binär-/Abnahmebelege. Kein VM-Zugriff, +kein RMM-Job und keine Clockqualifikation durch diesen lokalen Build. + +## Tatsächliche Eingangsdaten + +Root hat MIDL auf der Windows-VM im eigenen Fall +`149bafe2-3469-4580-b133-988812bcc3db` ausgeführt und anschließend denselben +Fall separat nur gelesen. Der neue lokale Builder prüft dessen vollständigen +Readback gegen SHA256 +`0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c`. +Der Beleg enthält erfolgreiche Microsoft-Authenticode-/Kettenprüfung der +festen Tools, Codegenexit0 und das Ende aller eigenen Prozesse. Es fand kein +RPC-Aufruf statt; `clock_qualified=false` bleibt ausdrücklich erhalten. + +Die zwei zurückgelesenen tatsächlichen Outputs werden unverändert als neue +Buildinputs kopiert und sowohl gegen die Originalbytes im Readback als auch +gegen feste Hashes geprüft: + +| Datei | Bytes | SHA256 | +|---|---:|---| +| `w32time.h` | 3779 | `db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde` | +| `w32time_c.c` | 18866 | `d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38` | + +`deploy/windows/clock_midl_diagnostic_build.py` erstellt pro lokalem Aufruf einen +neuen privaten Fall unter `devstate/windows-clock-midl/diagnostic-builds/`. +Er kopiert einen gehashten Quellsnapshot und verwendet ausschließlich diesen +Snapshot. Das separate Cargo-Paket unter +`deploy/windows/clock-midl-diagnostic/` bindet das vorhandene originale +`examples/clock_readiness.rs` und dessen originales `src/clock.rs` ein. C-Wrapper, +Endpointcode und Narrow-IDL sind ebenfalls unverändert und im neuen build.rs +zusätzlich fest gepinnt. `ADAPTER_QUALIFIED=false`, Authentisierung, Statusguard, +SEH- und Allocatorgrenzen werden nicht verändert. + +Es wird weder ein Compilerwrapper anstelle von WIDL ausgegeben noch ein +bestehendes OUT_DIR nachträglich verändert. Das neue build.rs kompiliert die +zuvor geprüften Originaloutputs direkt, ohne Generatorfallback oder NDR-Patch. +Der vorhandene Produktpfad `crates/agent-windows/build.rs` bleibt unverändert. +Der Lockfileabgleich erlaubt keine neue externe Paketversion gegenüber dem +ursprünglichen Root-Lockfile. Alle nachfolgenden Cargobefehle verwenden +`--locked --offline`; Docker läuft ohne Netzwerk und mit read-only Rootfilesystem. + +## Tatsächliche Compiler-/Linkerbefunde + +Die Microsoft-Quelldatei schützt ihren AMD64-Code mit `_M_AMD64`; Clang/GNU +definiert diesen Makronamen nicht selbst. Nur im getrennten tatsächlichen +x64-Build wird deshalb `_M_AMD64=100` gesetzt. Weder `_MSC_VER` noch +`__RPCNDR_H_VERSION__` werden definiert oder erhöht. Der echte MinGW-Header +meldet475; der originale Microsoft-Header verlangt475. + +Der unveränderte Microsoftstub enthält legale C-Klammerelision an einem +Unioninitializer sowie zwei unbenutzte konstante Tabellen. Der erste strikte +Versuch scheiterte an `-Wmissing-braces`; der zweite bewahrte zusätzlich die +konkreten `-Wunused-const-variable`-Befunde. Nur die exakt gepinnte generierte +Stubunit erhält `-Wno-error=missing-braces` und +`-Wno-error=unused-const-variable`: Die drei Warnungen bleiben im Log sichtbar, +alle übrigen Diagnosen bleiben Fehler. Die beiden unveränderten C-Wrapper +werden getrennt weiterhin mit `-Wall -Wextra -Werror` kompiliert. Kein +Typfehler, Strukturassert oder Sicherheitscheck wird abgeschaltet. + +Das isolierte kleine Rustpaket benötigt außerdem `mincore` zum Linken der +beiden unveränderten präzisen Interruptzeitgetter. Das vorhandene +MinGW-Kernel32-Importarchiv kennt sie nicht; `libmincore.a` enthält die +Windows-Realtime-API-Imports. Bereits die vorherige Readiness-EXE91889303… +importierte beide Getter über `api-ms-win-core-realtime-l1-1-1.dll`. +Es gibt keinen Ersatzgetter, keine Zeitberechnung aus Serverzeit und keinen +Runtimefallback. Die neuen PE-Imports werden separat erhalten. +Der tatsächlich erfolgreiche neue Link wählt für diese beiden Getter +`api-ms-win-core-realtime-l1-1-2.dll`, der frühere918…-Link dagegen +`api-ms-win-core-realtime-l1-1-1.dll`. Das ist eine zusätzliche tatsächliche +Linkdifferenz, kein reiner Einvariablenvergleich ausschließlich des Generators. +Ihre native Zulässigkeit wird hier nicht behauptet. + +Die unvollständigen Fälle `4ce00b43-4ca1-4e50-9f65-e89bd82f9364`, +`81b5503a-d78f-49be-b323-380c254cedff` und +`81d93ea1-f886-4853-8db4-f4e1c95f33ea` bleiben samt Eingängen und Logs erhalten. +Der letzte enthält bereits erfolgreiche Windows-Clippy- und fünf tatsächliche +Linux-Clocktests, aber einen fehlgeschlagenen Windows-Testlink. Diese Fälle +sind keine erfolgreichen vollständigen Diagnosebuilds. + +## Ausführung und Nachweisgrenzen + +Lokaler Buildbefehl, keine VM-Aktion: + +```text +python3 deploy/windows/clock_midl_diagnostic_build.py +``` + +Jeder Fall erhält Intent, genaue Compiler-/Lock-/Quellhashes und einzelne +Checklogs. Nur nach erfolgreichen fünf tatsächlichen Clocktests, Windows- +Clippy/-Testlink und Release-Link wird eine finale Qualifikation geschrieben. +Original-Linkdatei und separat gestrippte `WindowsClockReadiness.exe` bleiben +beide erhalten. Ein Windows-Crosslink ist kein nativer Windows-Lauf. + +Vollständiger tatsächlich erfolgreicher Fall: +`181c3a1c-8324-41fd-9b7c-aa8010262912`.131Compilerinputs vor/nach identisch; +Fmt, Windows-Alltargets-Clippy mit Rust-Warnungen als Fehler, alle fünf +Linux-Clocktests ohne Skip, Windows-Unitlink, Release-Link und PE-Importausgabe +bestanden. Die sichtbaren drei C-Stilwarnungen gelten ausschließlich für die +oben beschriebene gepinnte Microsoftstubunit. + +- Finale EXE:1217536Bytes, SHA256 + `b1d3da4f393ddf20bc8e48a9894ee314666f2ac3613ef97f5c228e3d089ca560`. +- Original-Linkdatei SHA256: + `5efcbbbdfe9c9d8b5954e4d550ba8f35fbaf1bcffefa610bd25b0c3797340d1c`. +- Finale `qualification.json` SHA256: + `2e0de3acf72ab5c3a8e0baa54e8643d086ea7c03d1b38fd89b6bfc00e45f8cbb`. + +Python-Syntaxprüfung des neuen Builders wurde ebenfalls tatsächlich ausgeführt. +Das ist lokale Crossbuild-/Vertragsqualifikation, kein Cloud-Linux- oder +Windows-VM-Nachweis und kein bestätigter Fix für die bisherige RPC1783-Ausnahme. + +Eine spätere tatsächliche Ausführung bleibt eine eigene Root-geführte +Diagnose mit konkretem Binaryhash und dem bestehenden Readinessrunner. +Selbst ein erfolgreicher Statusreturn würde weder die Named-Pipe-Serveridentität +noch Clockauthority oder den SYSTEM-/Jobpfad qualifizieren. Keine automatische +Wiederholung früherer RPC-Aufrufe und keine Genehmigungsabkürzung. + +## Ursprüngliche Vorbereitung der portablen Linux-Vorstufe + +`deploy/windows/clock_midl_linux_native.py prepare-local` wurde tatsächlich +lokal ausgeführt. Es kopiert ausschließlich die bereits im erfolgreichen +Build181c… ausgeführte Linux-Testexe; kein neuer Build und kein Strip. +Der separate Packfall lautet `f5d85873-96b2-41d5-97be-4c8f5c6baaef`, unter +`devstate/windows-clock-midl/linux-native-packs/`. Finale Manifest-SHA256: +`dcd6351898a1893253b352dce144d52dd45cd71aa1453295e648aa9d41afa67c`. + +Die tatsächlichen unveränderten26577504Bytes besitzen SHA256 +`6b3153d0d781798454f483c1c5b58089dcd2fe98b03c43aea3d928fd6107a9c8`. +ELF-Metadaten: x86-64, Interpreter `/lib64/ld-linux-x86-64.so.2`, höchste +benötigte Version `GLIBC_2.34`, direkte Abhängigkeiten `libc.so.6`, +`ld-linux-x86-64.so.2`, `libgcc_s.so.1`. Containerseitiges reines Listing +derselben Bytes bestätigt genau diese fünf bereits bestehenden Tests: + +```text +clock::tests::gate_requires_all_status_and_uncertainty_evidence +clock::tests::production_clock_stays_closed_until_native_adapter_qualification +clock::tests::suspend_closes_until_actual_post_resume_sync +clock::tests::timeout_worker_stays_closed_without_a_second_call +clock::tests::wall_step_and_overflow_fail_closed +``` + +Der neue Runner besitzt die getrennten Aktionen `native` und `readback`. +Nur Root führt `native --execute-native-tests --access-root +--manifest ` aus. Der bestehende strikte +SSH-/Credentialparser wird ausschließlich dann aufgerufen. Der Zielpfad +`/var/lib/rmm-clock-midl-portable-tests/` ist privat und create-only. +Originalintent, Startmarker vor dem ersten Prozess und finales Ergebnis werden +dauerhaft gespeichert. Verlorene Antwort erlaubt nur `readback --case `; kein zweiter Start. Ausschließlich die fünf hart codierten Tests dürfen +laufen, mit eigener Netzwerknamespace, bereinigter Umgebung, fünf Sekunden +je Test, zwanzig Sekunden Gesamtbudget und begrenzter Ausgabe. ELF-Loaderprüfung +erfolgt zusätzlich auf dem tatsächlichen Linuxziel. Keine bestehenden Dienste, +Jobs, Journale, Policies, Schlüssel oder Zeitdienstkonfiguration werden benutzt. + +Python-Syntax und lokales ELF-/Listpaket sind geprüft. **Der Autor dieses +Quellschnitts hat keine VM-Verbindung oder native Testausführung vorgenommen.** +Ein späterer Linux5/5-Beleg betrifft ausschließlich portable Clockguards, +keine Linux-NDR-Prüfung und keinerlei Windows-RPC-/Serveridentitäts- oder +Clockauthority-Nachweis. Root führt Windowsdiagnostik getrennt danach aus. + +### Readbackkorrektur vor der ersten nativen Ausführung + +Root-Review fand im zuvor vorbereiteten Linuxrunner einen konkreten Fehler: +Auch `read` hätte bei fehlender Zielwurzel ein Verzeichnis angelegt. Die +Korrektur beschränkt diese einzige Wurzelanlage auf `prepare`; `read` und +`run` verweigern eine fehlende Wurzel ausschließlich lesend. Der äußere +Readbackzweig ruft nur `action=read` auf, ohne Prepare, Upload oder Teststart. +Das ursprüngliche Pack f5d85873… bleibt erhalten, ist durch seinen alten +Runnerhash aber für den korrigierten Runner nicht mehr verwendbar. + +Der neue Packfall **68c5b69c-3391-4ff9-943d-3e5955be4e1f** enthält dieselben +unveränderten Testexebytes und dieselbe ursprüngliche Buildqualifikation. +Neues `manifest.json` SHA256: +`eceec2cc3f778cc46d58d1c10679fc38e5fcc7c7bee6eac99ef9454162f7ce48`. +Runner-SHA256: +`27a6a62e24a3908765bfe3c94d5ae75022210ebc6ab35ffc7f659bfe45844956`. +Die tatsächliche `native_case`-Teilquelle ist zusätzlich separat mit SHA256 +`ab7cd86e03684a6e7167d0c6814bc71edb39046e07b5794cfb0d6f195e2b6828` +gebunden. Manifest und spätere Originalintents binden außerdem die drei +Supportquellen `remote_client_bootstrap.py`, `vm_mvp_acceptance.py` und +`vm_access_check.py`. Jeder Native-/Readbackaufruf prüft diese Bindungen vor +dem ersten SSH-Aufruf; Sourceänderung verweigert den Zugriff. + +Tatsächlich lokal mit gemockten Ziel-/Transportobjekten geprüft: `read` bei +fehlender Wurzel ohne mkdir/open/Prozessstart; gleiches für `run`; äußerer +Readback genau ein Read-RPC ohne mkdir/SFTP/Testlauf; geänderte Supporthashes +vor RPC verweigert. Vier Guards bestanden, kein realer Zielzugriff. Beleg: +`readback-guards.json` im neuen Pack, SHA256 +`4db073802235d86b5233255a5fbf42be87808307abe32f47c4f6bb059ae8de31`. +Python-Syntax und erneutes reines ELF-/Testlisting bestanden. Alle ursprünglichen +131 Windowsbuildinputs wurden erneut gegen181c… verglichen und sind exakt +unverändert. Kein neuer Build, kein Strip und keine native Ausführung. + +## Danach tatsächlich: Cloud-Linux5 und Windowsdiagnose + +Root führte den korrigierten Pack68c5b69c nativ auf der Cloud-Linux-Test-VM +aus. Fall `222a0d60-4ddb-41c3-961c-2fa04138db28`: alle fünf festen portablen +Clocktests bestanden, jeder als exakter eigener Fall, keine ignorierten Fälle. +Originalbytes/Loader, Netzwerknamespace, begrenzte Ausgabe und feste Budgets +geprüft. `passed.json`-SHA256: +`b045ddccba9fff80ecba3b81649e14330b58f79b04990b5b257b1d6a3df39d3e`. +Keine Linux-NDR- oder Windows-RPC-Prüfung aus diesem Erfolg ableiten. + +Erst danach wurde Windows-EXEb1d3da4f im neuen eigenen LocalService- +Diagnosefall `94562d81-f75f-45c8-ab6b-28b70d12bd81` einmal ausgeführt. +Der bestehende Readinessrunner blieb unverändert; anschließend wurde derselbe +Originalbericht separat nur lesend identisch bestätigt. Der eigene temporäre +Dienst wurde entfernt. ResultatSHA256: +`91176b2c6832573786de9a8a15f9f239a0f93d7b0d5fef5eb36ac39f992b9232`. + +Tatsächliches Token: SID19/LocalService, kein Administrator und kein SYSTEM. +Beide ALPC-Versuche sowie deren falsche Account-/Servicekontrollen liefern +weiter1753 ohne Status; damit ist keine Identitätsverweigerung bewiesen. +Die getrennte Named-Pipe-Diagnose liefert jetzt **RPC5/AccessDenied** statt +des früheren1783. Trace: Stage90, `rpc_exception=5`, kein normaler nativer +Return und kein Status. Dies ist eine neue konkrete Fehlerbeobachtung, +**keine erfolgreiche W32Time-Abfrage** und kein isolierter Ursachennachweis; +die dokumentierte APIset-Linkdifferenz bleibt Bestandteil dieses Kandidaten. + +Ein separater Vorher-/Nachherabgleich des tatsächlich laufenden Agent-/ +Helperpaars prüfte PIDs/Geburt, Dateien/PKI/DB-/Lock-Datei-IDs, Helperwitness und +geschlossene Serverzähler/Flags unverändert. NachherbelegSHA256: +`09493104ca46b53b235df677f70289ef48bbfd718c8f5c82790921986db27bc8`. +Keine W32Time-ACL-/Konto-/NTP-Änderung, kein Agentwechsel oder RMM-Job. + +Microsoft dokumentiert für LocalService anonyme Netzwerkanmeldedaten und für +MS-W32T den authentisierten Named-Pipe-Endpunkt W32TIME_ALT. +[LocalService](https://learn.microsoft.com/en-us/windows/win32/services/localservice-account), +[MS-W32T-Transport](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655). +Ein Token-/Authentisierungseinfluss ist damit eine begründete **Hypothese**, +keine bewiesene Ursache des konkreten5. Als nächster enger Diagnoseschritt wird +ein eigener lesender SYSTEM-Vergleich mit unveränderten C-/Auth-/MIDLinputs +vorbereitet; kein Lockern der bestehenden LocalService-Prüfung oder +Zeitdienstrechte. Produktgate/Clock/Jobs bleiben geschlossen. diff --git a/docs/windows-clock-next-diagnostics.md b/docs/windows-clock-next-diagnostics.md new file mode 100644 index 0000000..bff782c --- /dev/null +++ b/docs/windows-clock-next-diagnostics.md @@ -0,0 +1,92 @@ +# Clock: nächste Diagnosegrenzen, noch keine Implementierungsfreigabe + +Historische Planungsnotiz vor der nativen MIDL-/EEInfo-Probe; deren tatsächliche +Ergebnisse stehen in [EEInfo-Diagnose](windows-clock-eeinfo-trace.md). Die hier +beschriebenen weiteren V5-Vergleiche wurden nicht ausgeführt. + +Stand 2026-11-14. Diese Notiz ändert weder den eingefrorenen MIDL-Runner +`078bf230…` noch Clock-/RPC-Produktquellen. Keine Zielverbindung ausgeführt. + +## MIDL-Signatur: tatsächlich statisch gelesene öffentliche Metadaten + +Die gehashten NuGet-PE-Dateien `midl.exe` und `midlc.exe` enthalten denselben +Microsoft-Corporation-Code-Signing-Leaf, SHA-256 +`0ba22e4765f7a160178ec90535c37f024916fbce0d9da63118d69662b5fed7eb`. +Sein Gültigkeitsintervall ist **2026-03-05 19:58:26 UTC bis +2027-03-03 19:58:26 UTC**, einschließlich Code-Signing-EKU. Das enthaltene +Zwischenzertifikat Microsoft Windows Code Signing PCA 2024 ist von +2024-08-08 bis 2035-06-23 datiert. Damit widerspricht eine Prüfung zum +14.11.2026 diesen eingebetteten Zeitintervallen nicht. + +Der private Beleg `public-certificate-time-metadata.json` im MIDL-Downloadfall +`6b7fb9b1-0bb7-4880-850b-e6812d3df1b1` enthält die exakten Toolhashes und beide +öffentlichen Zertifikatsbags. Dies ist **kein** Nachweis von PE-Signatur, +Signerauswahl, Zertifikatskette, Widerruf oder vertrauenswürdigem Zeitstempel. +Die Ziel-Vertrauensspeicher und Online-Widerrufsprüfung bleiben ungeprüft. + +Die zusätzliche `X509Chain.Build(SignerCertificate)`-Prüfung benutzt ohne +explizite VerificationTime das aktuelle Datum; die +[Microsoft-.NET-Framework-Quelle](https://github.com/microsoft/referencesource/blob/main/System/security/system/security/cryptography/x509/x509chainpolicy.cs) +setzt beim Reset `DateTime.Now`. Eine Dateisignatur mit gültigem vertrauenswürdigem +Timestamp kann dagegen auch nach Ablauf des Signierzertifikats zulässig bleiben, +wie Microsoft für [Authenticode-Zeitstempel](https://learn.microsoft.com/en-us/windows/win32/seccrypto/time-stamping-authenticode-signatures) +beschreibt. Eine separate heutige Blattkettenprüfung ist deshalb kein allgemeiner +Ersatz für die vollständige Dateisignatur-/Timestamp-Policy. + +Für die **jetzt fest gepinnten** Tools besteht nach den gelesenen Metadaten kein +solcher Ablaufkonflikt. Der Runner bleibt unverändert streng. Scheitert die +native Prüfung, muss der genaue Grund erhalten werden; kein IgnoreNotTimeValid, +kein abgeschalteter Widerruf und kein neu importierter Trustanker als Abkürzung. +Soll später ein anderer, abgelaufener, aber timestamp-signierter Input nötig +werden, verlangt das einen eigenen geprüften Verifiervertrag: vollständige +[Authenticode-Dateipolicy](https://learn.microsoft.com/en-us/windows/win32/api/wintrust/nf-wintrust-winverifytrust), +Dateidigest, erlaubter Signer und belegte Timestamp-/Kettenprüfung statt eines +frei gesetzten historischen Prüfdatenwerts. + +## Geplanter enger Named-Pipe-V5-Diagnosevergleich + +Voraussetzung ist zuerst ein **tatsächlich zurückgelesener** MIDL-Header/-Stub +und ein nativer Opnum-6-Statusbeleg. Ein weiterer gleicher NDR-Fehler 1783 ist +kein Identitätsnachweis und darf nicht als negatives Sicherheitskontrollergebnis +gezählt werden. Produktive Clockbereitschaft bleibt unabhängig davon false. + +Die [RPC-V5-Dokumentation](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w) +beschreibt `ServerSecurityDescriptor` zur Serveridentifikation und warnt, dass +NTLM trotz fehlender gegenseitiger Authentifizierung erfolgreiche +MUTUAL_AUTH-Verhandlung melden kann. `Sid` ist insbesondere für `ncalrpc` +beschrieben; die Wirkung der gewählten Kombination auf `ncacn_np` ist noch +nativ nachzuweisen. Ein gesetztes Flag oder erfolgreiche SetAuthInfo-Rückgabe +qualifiziert diese Kombination nicht. + +Kleinster **noch nicht implementierter** Vergleich, getrennt vom bisherigen +Named-Pipe-/ALPC-Pfad: + +1. Exakter lokaler authentifizierter Endpunkt `\\pipe\\W32TIME_ALT`, Interface + 4.1/Opnum 6, bestehender C-SEH-/Allocator-/Statusvertrag und PacketPrivacy. + Kein Remotehost, alternativer Endpunkt oder automatischer Fallback. +2. V5 mit festem erwarteten LocalService-SID und lokal konstruiertem Descriptor, + dessen einzige Allow-ACE den echten `NT SERVICE\W32Time`-SID bezeichnet. + Account und Service-SID kommen niemals aus der Endpointantwort. Descriptor, + ACL und beide SIDs leben bis nach dem vollständigen RPC-Aufruf. +3. Derselbe Statusaufruf mit ausschließlich falschem erwartetem Account + (LocalSystem statt LocalService), korrektem W32Time-Descriptor. +4. Derselbe Statusaufruf mit korrektem Account, aber ausschließlich falschem + Service-SID (`RmmDiscoveryWindows` statt W32Time). Damit wird die Trennung + gegenüber dem ebenfalls als LocalService laufenden Network-Agent getestet. + +Erforderlich wären echter positiver Return mit validem Status **und** zwei +nachvollziehbare Identitätsverweigerungen ohne gelieferten Status, unter +identischem frischem Dienst-/Boot-/Binarykontext. Timeout, fehlender Endpunkt, +ungültiger Stub oder derselbe 1783-Fehler auf allen Varianten sind unzureichend. +Eine akzeptierte falsche Identität falsifiziert den Kandidaten; keine Abschwächung +auf Account-only. Der tatsächlich aktivierte W32Time-Service-SID und die feste +Dienstkonfiguration müssen zuvor rein lesend belegt sein. Fehlende SID-Isolation +darf nicht durch eine Service-/Token-/ACL-Änderung für die Diagnose repariert +werden. + +Die spätere Probe benötigt einen einzelnen begrenzten Diagnoseworker, feste +Varianten und numerische Stage-/Return-/Status-Presencefelder. Kein freier +SID-/Endpunktparameter, kein Ersatzthread nach hängendem Call und kein Retry +mit schwächerer Authentisierung. Erst diese technischen Diagnosen wären eine +Grundlage für eine separate Clockvertrauensentscheidung; sie öffnen weder +`ADAPTER_QUALIFIED` noch Jobcapabilities oder den SYSTEM-Helperpfad. diff --git a/docs/windows-clock-pointer-native.md b/docs/windows-clock-pointer-native.md new file mode 100644 index 0000000..3ec6ddd --- /dev/null +++ b/docs/windows-clock-pointer-native.md @@ -0,0 +1,34 @@ +# W32Time-Pointerkandidat — tatsächlicher Nachtest + +Der lokal qualifizierte Diagnosebuild91889303… wurde nach dem vom Benutzer +bestätigten manuellen Konsolenneustart und dem bereits autorisierten gezielten +W32Time-Start tatsächlich als eigener LocalService-Dienst ausgeführt. + +Fall `79896ca7-1337-4118-bda9-f7506f7649f6`, BinarySHA256 +`91889303e1650d8612b946512f069a3421eb686c7bed315426c48bd62b18a1fd`. +Eigener temporärer Dienst nach seinem Ende entfernt, Bericht getrennt identisch +lesend bestätigt. SID19, kein Administrator und kein SYSTEM. AgentPID3172 und +gestoppter manueller Helper sowie ursprüngliche Datei-/PKI-Metadaten und +Zeitdienstdefinition/-Konfiguration im frischen Nachbeleg exakt erhalten. +Zentrale Zähler und geschlossene Testflags unverändert, keine RMM-Jobs. + +Beide produktiv ausgelegten ALPC-Proben liefern weiterhin1753; Endpointmapper +keine Einträge; beide falschen Identitätskontrollen ebenfalls1753. Das ist kein +Verweigerungsnachweis. Die unabhängige Named-Pipe-Diagnose liefert weiterhin1783, +Status fehlt. Die zusätzliche Traceabfrage meldet Stage90/RPC-Ausnahme1783, +native_rpc_return_present0 und status_present0. Ohne Presenceflag ist das +numerische Returnfeld0 ausdrücklich kein erfolgreicher nativer Return. + +Die mit WIDL7 erzeugte ref→unique-Korrektur allein hat den Fehler somit im +realen Gast nicht behoben. Die genaue weitere Ursache bleibt offen; kein +nachträglicher Erfolg und keine Aussage, dass der Pointerunterschied irrelevant +sei. Die [Microsoft-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a) +ist die Referenz, keine manuellen Stubbytepatches. Microsofts nativer +MIDL-/MSVC-Nachweis fehlt weiterhin; die Buildtoolsinstallation bleibt wegen +nativ nach dem Boot beobachtetem CBS-Neustartmarker gesperrt. + +Geschützte BewertungSHA256 +`fceb92c2ca059f23f3b930e80b59ec4f16b72741e4822aadc6c11c1933c01383`. +`ADAPTER_QUALIFIED=false`, keine Job-, SYSTEM- oder Paketcapability aktiviert. +Eine erfolgreiche rohe RPC-Statusabfrage allein würde noch keine gesicherte +Bindung an den tatsächlichen Zeitdienst oder vertrauenswürdige Uhr beweisen. diff --git a/docs/windows-clock-process-privilege-plan.md b/docs/windows-clock-process-privilege-plan.md new file mode 100644 index 0000000..0669c8d --- /dev/null +++ b/docs/windows-clock-process-privilege-plan.md @@ -0,0 +1,240 @@ +# Plan: einmaliger Clockvergleich mit vorhandenem Prozessprivileg + +Ursprünglicher Plan 2026-11-14, vor Implementierung verfasst; die inzwischen erfolgte lokale Umsetzung steht im letzten Abschnitt. +**Keine Implementierung, kein Build und keine Zielaktion für diesen Nachfolger.** +Die Freigabe der konkreten Tokenabgrenzung und des Diagnoseumfangs liegt beim +Hauptagenten. Alle bisherigen Empty-, F6-, SYSTEM-, EEInfo- und Produktquellen +sowie deren Casebelege bleiben unverändert. + +## Ausgangspunkt und begrenzte Fragestellung + +Der Hauptagent meldet aus dem tatsächlichen Empty-Case +`5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94`: eine Statusquery, RPC5/Stage90, +ein numerischer EEInfo-Record; vorhandenes SeSystemtimePrivilege mit +Attributen0/Enabled0. Dieser Plan ergänzt keinen abgeschlossenen +Readback-/Cleanup-/Preservationnachweis und leitet daraus keine Fehlerursache ab. + +Der nächste Vergleich soll ausschließlich prüfen, ob sich das Ergebnis eines +einzelnen lesenden Opnum6 ändert, wenn genau das bereits vorhandene +SeSystemtimePrivilege des getrennten Diagnoseprozesses vorübergehend aktiviert +ist. Es werden keine Kontorechte zugewiesen. Auch ein erfolgreicher Vergleich +wäre weder Produktionsfreigabe noch ausreichende Clock-/Serveridentitätsprüfung. + +## Geprüfte Microsoft-Verträge + +AdjustTokenPrivileges wirkt auf das übergebene Tokenobjekt. Es benötigt +TOKEN_ADJUST_PRIVILEGES, mit PreviousState zusätzlich TOKEN_QUERY. TRUE allein +bedeutet nicht, dass alle angeforderten Rechte angepasst wurden: +GetLastError ist unmittelbar auszuwerten; ERROR_NOT_ALL_ASSIGNED verweigert den +Diagnoseaufruf. Vorhandene Rechte können aktiviert werden, neue werden nicht +hinzugefügt. PreviousState enthält die tatsächlich geänderten ursprünglichen +Zustände und dient als NewState einer Wiederherstellung. Ein zu kleiner +PreviousState-Puffer führt ohne Anpassung zum Fehler. +[AdjustTokenPrivileges](https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges) + +OpenProcessToken öffnet das einem Prozess zugeordnete Token. Dieser Aufruf ist +kein eigenständiger Vertrag über die Exklusivität aller Referenzen auf dieses +Tokenobjekt. +[OpenProcessToken](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken) + +TokenStatistics.TokenId identifiziert die konkrete Tokenobjektinstanz. +AuthenticationId identifiziert eine Anmeldesitzung, zu der viele Tokens gehören +können. ModifiedId ändert sich bei Tokenänderung. Deshalb weder gleiche +AuthenticationId als Tokenidentität noch gleiche ModifiedId nach Wiederherstellung +fordern; die ursprüngliche ModifiedId lässt sich nicht durch Zurücksetzen der +Privilegattribute wiederherstellen. +[TOKEN_STATISTICS](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_statistics) + +Jeder Prozess hat ein Primärtoken; ein impersonierender Thread kann zusätzlich +ein Threadtoken besitzen. Der Vergleich soll weiterhin ohne Impersonation und +ohne Tokenwechsel laufen. +[Access Tokens](https://learn.microsoft.com/en-us/windows/win32/secauthz/access-tokens) + +LocalSystem-Dienste erben den Sicherheitskontext des SCM. Diese Aussage und +derselbe SYSTEM-SID belegen für sich allein keine verschiedenen TokenIds. +SeSystemtimePrivilege ist in Microsofts LocalSystem-Beschreibung standardmäßig +deaktiviert; das erklärt nicht allein den konkreten RPC5. +[LocalSystem Account](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account) + +SERVICE_WIN32_OWN_PROCESS belegt einen eigenen Prozess, nicht durch seine bloße +Bezeichnung eine geprüfte Trennung sämtlicher Tokenreferenzen. +[CreateServiceW](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-createservicew) + +## Noch vom Hauptagenten zu entscheidende Beweisgrenze + +Vorgeschlagener enger Gate: Vor jeder Anpassung rein lesend TokenId und +TokenStatistics des Diagnoseprozesses, des SCM-Prozesses und der aktuell an +W32Time, RMM-Agent und RMM-Helper gebundenen Prozesse erfassen. Prozesshandles +und Startzeiten binden die Ablesung gegen PID-Wiederverwendung; Dienst-PID und +Prozessbindung direkt danach erneut prüfen. Nur TOKEN_QUERY gegenüber fremden +Tokens; kein SE_DEBUG_ENABLE, kein fremdes TOKEN_ADJUST_PRIVILEGES. +Bei fehlender erforderlicher Probe, Prozesswechsel, gemeinsamem TokenId, +falschem SYSTEM-Primärtoken oder vorhandenem Threadtoken: Abbruch vor Anpassung +und vor RPC. Gleiche AuthenticationId allein ist kein Fehler. + +Dies belegt lediglich Trennung von den tatsächlich abgefragten Peer-Tokenobjekten. +Es beweist nicht, dass kein weiterer Prozess/Thread irgendeine Referenz auf das +Diagnosetoken hält. Die ausgewerteten primären Verträge liefern hierfür keine +ausreichende universelle Exklusivitätsgarantie. **Ohne ausdrückliche Akzeptanz +dieser Grenze wird kein Anpassungscode erstellt.** Alternativ ist zuerst ein +rein lesender TokenId-Vergleich vorzubereiten. Ein dupliziertes Token plus +Impersonation oder neuer Childprozess ist ein anderer Vergleich und wird nicht +stillschweigend als Ersatz eingebaut. + +## Vorgeschlagene neue Quellen, erst nach dieser Entscheidung + +Vier neue Dateien unter `deploy/windows/clock-spnego-privilege-trace/`: + +- `clock_rpc_spnego_privilege.c`: bytegleicher Empty-RPCpfad bis auf das neue + öffentliche Symbolsuffix. Tatsächlich zurückgegebenen nicht-NULL Emptystring + unverändert weitergeben; GSS9/Privacy6/Identify2, kein Authfallback. Maximal + eine Managementdiscovery und bei erfüllten Vorbedingungen eine Opnum6-Query; + Setupfehler bedeuten null Queries. EEInfo weiter maximal vier numerische + Records. Kein Setter und keine neue Serveridentitätsbehauptung. +- `system_trace_spnego_privilege.c`: eigener, einmalig gestarteter + SYSTEM-OWN_PROCESS-Dienst mit dem nachstehend beschriebenen Tokenablauf. +- `build.py`: alter Compiler/MIDL/Header/SDK/DLL-Vertrag unverändert, neue + vier Inputs sowie Empty-Manifest und tatsächlichen Ausgangscase hashen; + alte Inputs nur vergleichen und unverändert erhalten. +- `native.py`: eigene Case-/Service-/Profilbindung, create-once prepare/start, + rein lesender same-case Readback und getrenntes Cleanup nur des eigenen + gestoppten Dienstes. Antwortverlust erlaubt keine Wiederholung des Starts. + +Vorgeschlagene Namen: `RmmClockSpnegoPrivilegeDiagnostic`, +`clock-system-spnego-privilege-v1`, `ClockSpnegoPrivilegeTrace.exe`, +`C:\ProgramData\RustDiscoveryBootstrap\clock-spnego-privilege-trace-`. + +## Geplanter Tokenablauf und Fehlerverhalten + +1. Vor Anpassung eigenes gehaltenes Primärtoken mit exakt TOKEN_QUERY und + TOKEN_ADJUST_PRIVILEGES öffnen; keine Vererbung oder Weitergabe des Handles. + SYSTEM, Primärtoken und fehlendes Threadtoken prüfen. Vollständige begrenzte + Privilegliste auslesen, LUIDs numerisch sortieren und auf Duplikate prüfen. + SeSystemtimePrivilege muss genau einmal vorhanden sein, Attribut0 haben und + weder enabled noch removed sein. Abweichung verweigert den Vergleich. +2. Eigenes PID/Startzeit/TokenStatistics und Peer-Proben samt ursprünglicher + numerischer Privilegliste create-once vor Anpassung dauerhaft ablegen. + Geplantes Limit: höchstens256 Privilegien und derselbe4096Byte-Tokenpuffer. + Keine Namen, Anmeldeinformationen oder Tokenhandles als Ausgabedaten. +3. Ein einziges AdjustTokenPrivileges mit DisableAllPrivileges=FALSE, + PrivilegeCount=1, exakter vorhandener LUID und SE_PRIVILEGE_ENABLED. + Ausreichender fester PreviousState-Puffer für genau eine Änderung; + BOOL und sofortiges GetLastError getrennt speichern. Nur TRUE+ERROR_SUCCESS + und genau ein gültiger PreviousState-Eintrag derselben LUID/Attribut0 + erlauben den weiteren Ablauf. Kein SE_PRIVILEGE_REMOVED/DisableAllPrivileges. +4. Direkt am gehaltenen eigenen Token nachlesen: gleiche TokenId, + AuthenticationId und TokenType, unveränderte Privilegmenge sowie lediglich + der erwartete Enablebit-Wechsel. Direkt vor RPC fehlendes Threadtoken erneut + prüfen. Fehler springen zuerst in Restore, nicht in RPC. Der Enablezeitraum + umfasst den unveränderten Discovery-/Authsetup-/Querypfad; es wird keine + Behauptung aufgestellt, dass das Bit nur während des einzelnen Opnum6 aktiv ist. +5. Bestehende RPCfunktion höchstens einmal aufrufen; RPCexception/Fehler bleibt + ihr numerischer Befund. Unmittelbar danach Restore auf demselben gehaltenen + eigenen Token mit PreviousState als NewState. Jeder normale Fehlerpfad nach + Anpassungsbeginn erreicht denselben Cleanupblock, bevor Berichtschreiben + oder Dienstende. Auch fehlgeschlagene Nachprüfung löst Restore aus. + Bei unerwartetem PreviousState ist kein RPC erlaubt; der bereits separat + gesicherte eine ursprüngliche LUID/Attribut0 ist die begrenzte Restoreeingabe. + Keine Wiederholung eines RPCs oder Aktivierungsversuchs. +6. Restore-BOOL und unmittelbaren Fehlercode separat erfassen. Vollständige + Privilegliste erneut lesen; exakt ursprüngliche Attribute/Menge fordern. + TokenId/AuthenticationId/TokenType müssen gleich sein. ModifiedId darf und + wird gegebenenfalls anders sein; dies ist keine fehlgeschlagene Rücksetzung. + Peer-TokenIds/Attribute erneut rein lesend prüfen; Wechsel/Fehler ehrlich + als nicht nachgewiesene Erhaltung melden, nicht durch fremden Schreibzugriff + reparieren. Danach Ergebnis plus before/enabled/restored-Snapshots speichern. + +Ein Restorefehler kann nicht durch eine Erfolgsmeldung verdeckt werden und +beweist keine erfolgreiche Erhaltung; Dienstexit wird Fehler, kein weiterer +RPC. Unvorhersehbarer Prozessabbruch, TerminateProcess oder Stromverlust kann +keinen benutzerseitigen finally-Block garantieren. Ohne gespeicherte und +nachgelesene Wiederherstellung lautet der Nachweis daher `unknown`, auch wenn +der Prozess bereits beendet ist. Es wird keine universelle Rücksetzgarantie +für solche Abbrüche behauptet. + +Die Statusquery bleibt fachlich lesend; der neue Diagnoseprozess insgesamt ist +wegen AdjustTokenPrivileges **nicht rein lesend**. Maschinen-/Kontorechte, +ACL/GPO, W32Time-Konfiguration, Dienstkonten und Uhrzeit werden nicht geändert. +Die Erzeugung des eigenen Diagnosedienstes bleibt eine gesonderte ausdrückliche +Bootstrapwirkung. Kein Produktgate und keine Job-/Freigabe-/Policyänderung. + +## Geplante lokale und native Nachweise, sämtlich noch nicht ausgeführt + +Nach akzeptiertem Scope zunächst Quellenreview: genau ein Enable, ein gebundener +Restorepfad, kein Tokenwechsel, keine fremden Tokenwrites, bestehender RPCpfad +bis auf Symbol bytegleich. Lokale gezielte Guardfälle: TRUE mit1300 verweigern, +fehlendes/removed/dupliziertes Recht, bereits enabled, falscher PreviousState, +fremder gleicher TokenId, Peerwechsel, nichtlesbarer Peer, aktiver Threadtoken, +Nachprüfungsfehler, RPCexception sowie Restorefehler. Nicht jeder synthetisch +abgedeckte Fehler ist damit ein nativer Windowsnachweis. + +Erst nach getrenntem Source-/Buildreview kann der Hauptagent einen neuen nativen +Case ausdrücklich starten. Benötigte Belege: originale Snapshots vor Anpassung, +sichtbare einzelne Enableänderung, exakter RPC-/EEInfo-Befund, nachgelesener +Restore, unveränderte Peer-Zustände, gestoppter eigener Dienst, same-case +Readback sowie getrenntes Cleanup/Preservation bestehender RMM-Dienste. Keine +Clockqualifikation allein aus einem erfolgreichen Statusqueryreturn ableiten. + + +## Lokale Umsetzung nach ausdrücklicher Rootfreigabe + +Der Hauptagent hat die begrenzte TokenId-Trennung zu gehaltenen SCM-/W32Time-/ +Agent-/Helper-Prozessen ausdrücklich akzeptiert. Universelle Exklusivität aller +Referenzen wird weiterhin nicht behauptet. Der ursprüngliche176Zeilen-Plan +mit SHA25627b1035c… ist zusätzlich create-once unter +`devstate/windows-clock-spnego-privilege-trace/local-review/accepted-plan.md` +erhalten. Dieser Abschnitt ersetzt keine Freigabe einer Zielaktion. + +Die vier oben benannten neuen Dateien sind jetzt lokal implementiert. +Vorher werden eigene TokenUser/SYSTEM, Primärtoken, fehlender Threadtoken und +vollständige numerische Privilegliste geprüft. SCM wird eindeutig über +services.exe samt Systempfad ermittelt; die anderen drei Prozesse sind über +gehaltene Service-/Prozesshandles, Running/PID, Erstellzeit und feste Images +gebunden. Fremde Tokenhandles verlangen ausschließlich TOKEN_QUERY. Der eigene +Tokenhandle verlangt QUERY|ADJUST_PRIVILEGES. Vor Enable wird der vollständige +Beforebeleg create-once geschrieben. Der unmittelbare Enable-Rückgabecode und +GetLastError, PreviousState und volle Nachlese begrenzen den einzigen RPCpfad. + +Alle kontrollierten Fehlerpfade nach Enable erreichen dieselbe einzelne +Restorestelle; danach werden volle ursprüngliche Attribute und die +unveränderten numerischen Peer-Privilegzustände/TokenIds/ModifiedIds geprüft. +ModifiedId des eigenen Tokens darf nach korrektem Restore geändert sein. +Berichte kennzeichnen die gesamte Diagnose ausdrücklich als read_only=false; +SYSTEM wird nur bei erfolgreicher tatsächlicher Probe ausgewiesen. Ein eigener +Cleanupreceipt erhält den vorherigen Dienstexitcode, damit Serviceentfernung +keinen fehlgeschlagenen Ablauf nachträglich als vollständig erscheinen lässt. + +Finaler lokaler Build: +`devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json`, SHA256 +`6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3`. +PE114087Bytes, SHA256 +`68a217914c15f28b19c52a2f5adfd595854f88210fbb0b69c20e73a59952b65e`. +Originales Microsoft-MIDL/Header und gepinnter Compiler unverändert; eigene +C-Units Wall/Wextra/Werror, gleiche vier DLL-Imports ADVAPI32/KERNEL32/RPCRT4/ +msvcrt. PowerShell-AST bestanden, EncodedCommand18858Zeichen unter32767. +Alle131Produktinputs,15bisherige Diagnosequellen sowie F6-/Empty-Manifeste und +Ergebnisbelege unverändert geprüft. Der RPCwrapper unterscheidet sich vom +Empty-Elternteil ausschließlich durch das öffentliche Symbolsuffix. + +Gezielte lokale Nachweise, keine Windows-API- oder RPC-Ausführung: der tatsächliche +C-run_service-Block wurde bytegleich extrahiert und mit kontrollierten lokalen +API-Stubs übersetzt/ausgeführt.13Fälle bestanden, unter anderem TRUE/1300, +FALSE, ungültiger PreviousState, aktive Attributabweichung, Own-/Peerprobe-Fehler, +Restorefehler, fehlgeschlagene Nachlese sowie Writefehler vor/nach Enable. +Jeder Fall prüft höchstens1Enable, genau1Restore je Enable und höchstens1RPC. +Der echte Python-Reader akzeptierte zwei synthetische gültige Berichte und +verweigerte17Fälschungen/Fehler einschließlich fremdem TokenId, nicht erhaltenen +Attributen, Peerdrift, schwächerer Privacy und verstecktem Fehlerexit nach Cleanup. +Guardreceipt `local-review/guards.json`, SHA256 +`c12c5d06ecad63101874f7c66af1f49eb9f6d9b51dbba9c75e367462660fa831`. +Dies sind lokale Fehlerpfadbelege, keine nativen Token-/Erhaltungsnachweise. + +**Bis zum Abschluss dieser lokalen Vorbereitung war kein Privilegvergleich auf +Windows ausgeführt. Der Subagent hat keinen VM-/SSH-/SCM-Start vorgenommen und +keinen Produktcode/Clockgate geändert.** Das erforderliche unabhängige +Source-/Manifestreview und die spätere native Ausführung durch den Hauptagenten +sind inzwischen im [tatsächlichen Ergebnis](windows-clock-process-privilege-result.md) +mit Startfehler, separatem Readback, Restore, Cleanup und Preservation dokumentiert. +Auch eine künftig erfolgreiche Query ließe produktive LocalService-Privilegien, +gebundene Serveridentität und Transport-Positiv-/Negativnachweise weiter offen; +Discovery/NTLM/Mutualauth-Flags allein ersetzen diese nicht. diff --git a/docs/windows-clock-process-privilege-result.md b/docs/windows-clock-process-privilege-result.md new file mode 100644 index 0000000..685de46 --- /dev/null +++ b/docs/windows-clock-process-privilege-result.md @@ -0,0 +1,185 @@ +# Tatsächlicher Prozessprivilegvergleich auf der Windows-VM + +Stand 2026-11-14: eigener Diagnoseablauf, separater Readback, Cleanup und +After-Preservation durch den Hauptagenten abgeschlossen. Die W32Time-Statusquery +scheitert weiterhin mit RPC5. Kein Produktgate geöffnet, kein RMM-Job ausgeführt. + +## Verwendeter Quellen- und Buildstand + +Reviewter Nachfolger unter `deploy/windows/clock-spnego-privilege-trace/`, vier +Dateien; ursprünglicher Scope und lokale Nachweise: +[Prozessprivilegplan](windows-clock-process-privilege-plan.md). + +Buildmanifest: +`devstate/windows-clock-spnego-privilege-trace/build-b56e3f3d-8904-4fd8-9c34-0e55e57c8f07/manifest.json`, SHA256 +`6c97658307ec66e6605574dca27cdbc79efefa9cd7f386e6e2cb3f73d9b5c6d3`. +Windows-PE114087Bytes, SHA256 +`68a217914c15f28b19c52a2f5adfd595854f88210fbb0b69c20e73a59952b65e`. +Der Hauptagent und sein unabhängiger Reviewer haben Quelle, Manifest und PE +geprüft. Die vier Quellen wurden für den nativen Vergleich nicht verändert. + +## Fehlgeschlagener Startaufruf und getrennte Nachlese + +Neuer einmaliger Case: `6de04277-6bec-477d-b1c9-bfca88a9cd78`. +Der ursprüngliche Startaufruf meldet tatsächlich +`StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand` an Zeile26. +Transportbeleg `transport-6e33c04b-f149-426b-8da1-309129ff3469.json`, SHA256 +`83ccfd7db60ad27dd901ddbef223cde8f69ecc9e635373038f20ca864b954ba6`. +Dieser Aufruf bleibt als fehlgeschlagen dokumentiert. **Kein Startretry.** + +Anschließend gewinnt der Hauptagent ausschließlich durch einen separaten, +rein lesenden same-case Readback den vollständigen Diagnosebericht. Der eigene +Dienst ist gestoppt, Dienstexit0. Readback +`readback-9039311f-1b98-4d0c-b516-02a543fb2d7b.json`, SHA256 +`c5dcf129d329b879be00c801eead32d2047d9b73ffed0e0e692615e9a7459c07`. +Der gebundene vollständige Ergebnisbeleg `diagnostic-result.json` hat SHA256 +`c7556589a015fc5ab53feffe3caf74a3904b7f5a65b70066f256cc0693ff8152`. +Exit0 und complete=true belegen den abgeschlossenen Diagnose-/Restoreablauf, +keinen gelungenen W32Time-Aufruf. Die Ursache der anfänglichen Startfehlermeldung +ist nicht nachgewiesen; eine SCM-Race wird nicht als Erklärung behauptet. + +## Tatsächliche Token- und RPC-Ergebnisse + +Eigenes gehaltenes SYSTEM-Primärtoken; kein Threadtoken. Der vorhandene +SeSystemtimePrivilege-LUID ist12,0, ursprüngliches Attribut0. Genau ein +Enableversuch: BOOLtrue/GetLastError0, PreviousStateCount1,16Bytes, derselbe +LUID12,0 und ursprüngliches Attribut0. Die anschließende vollständige Nachlese +zeigt ausschließlich den vorgesehenen Enablebit-Wechsel auf2. + +Genau eine Wiederherstellung auf dem gehaltenen eigenen Token mit dem geprüften +PreviousState: BOOLtrue/GetLastError0. Danach sind die vollständige ursprüngliche +Privilegmenge und Attribute0 wiederhergestellt, restoration_verified1, +restored_status0, flow_status0. Vorher-/Nachher-TokenId und Authentifizierungs-ID +bleiben gebunden; eine geänderte eigene ModifiedId ist keine unerwartete +Attributabweichung. Die beobachteten gehaltenen Peer-Tokens für SCM, W32Time, +Agent und Helper behalten ihre TokenIds, ModifiedIds und Privilegattribute. +Dies ist der vereinbarte begrenzte Peer-Nachweis, keine universelle Behauptung +über sämtliche Tokenreferenzen des Betriebssystems. Fremdtokens werden nur gelesen. + +Eine SPNEGO-Managementdiscovery gelingt mit Status0 und normalem Return. Der +tatsächlich gelieferte Principalpointer ist nicht-NULL, UTF16-Länge0. GSS9, +PacketPrivacy6 und Identify2 bleiben unverändert. Danach genau ein Opnum6: +RPCexception5/Stage90, kein normaler Return, kein Statusobjekt. Unmittelbar +erfasst wird ein numerischer EEInfo-Record: Komponente2, Status5, +DetectionLocation1750, Flags0, Parameteranzahl1. Keine Parameterinhalte gelesen. +Principal-/Bindingfreigabe werden jeweils einmal erfolgreich ausgeführt. + +Der Unterschied zum vorherigen Emptyvergleich ist damit tatsächlich geprüft: +Aktivieren dieses vorhandenen Prozessprivilegs beseitigt den beobachteten RPC5 +nicht. Daraus folgt weder, dass jede Privilegprüfung erfolgreich war, noch eine +eindeutige Aussage über den vom Server geprüften Credential-/Impersonationkontext. +Keine Uhr-, Kontorechte-, ACL-, GPO-, Policy- oder W32Time-Konfigurationsänderung. +Die gesamte Privilegdiagnose kennzeichnet sich korrekt als read_only=false; +die einzige W32Time-Methodenquery selbst ist lesend. + +## Cleanup und Erhaltung + +Der Hauptagent bereinigt ausschließlich den eigenen gestoppten Diagnosedienst. +Cleanupreceipt `readback-d02e8c7a-5154-488b-a29f-4d4d8155ec7a.json`, SHA256 +`e163d7d4790ea4900f1cc1caedf11ff2619f30cf7b25388eabffa9afd75d8d50`, +bestätigt cleanup_verified=true; der eigene Dienst ist anschließend nicht mehr +registriert. Kein Retry, Reset oder zusätzlicher RMM-Job. + +Vorherbeleg SHA256 +`a4b321f965f4ccc968724fae9abd856cca5f799b5fc96a54d04f5316b95ab05b`; +Afterbeleg im Pipeworktree: +`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/spnego-privilege-trace-after.json`, SHA256 +`f37a2e866ebc5dfd1ae13bfd18b7c5355da42dfd01b7e7e69f478555c60eb830`. +Alle sechs nativen Bereiche service/helper_service/agent_kernel/helper_kernel/ +files/helper_witness sind exakt gleich. Serverzustand ebenfalls gleich: +Windows0/0/0/0, Linux31/31/27/0, geschlossene Rootpolicycf15. Der separate +Nachweis meldet verified=true, read_only=true, no_jobs=true, clock_qualified=false. + +## Tatsächlicher Builtinvergleich und Primärquellen + +Der Hauptagent hat separat den vorhandenen Microsoft-Builtin +`w32tm /query /status /verbose` über den bestehenden Administratortransport +abgefragt. Beim ersten lesenden Aufruf scheitert der Texttransport an einer +UTF8-Dekodierung mit Byte0x84; Resultbytes wurden nicht erhalten. Dies ist kein +brauchbarer Status- oder Exitcodenachweis dieses ersten Prozesses. Ein zweiter, +separater lesender Query verwendet danach eine ASCII-JSON-Hülle und Base64 +für den ausdrücklich UTF8-kodierten Ausgabetext. Keine wiederholte Wirkung eines +RMM-Jobs; beide Bootstrapbefehle sind Statusabfragen, kein resync/config/register. + +Der zweite Aufruf liefert Exit0. Receipt im Pipeworktree unter demselben14fb-Pfad: +`builtin-w32tm-status-base64-result.json`, SHA256 +`4e5ea093ee8f9508b5327e664bbe9c824895c08feecdd8f425fe18f9d2ece262`. +Der erhaltene native Status meldet Leap3/nicht synchronisiert, Stratum0, +Rootdispersion8.8814534Sekunden, Phase-1.1113519Sekunden, letzte Synchronisation +14.11.2026 15:26:24, Alter15703Sekunden und letzte Synchronisationsfehlermeldung1/ +keine Zeitdaten. Konfigurierte Quelle: time.windows.com,0x9. Dies sind die Werte +im erhaltenen Statuszeitpunkt, keine aktuelle fortlaufende Messung und kein +vertrauenswürdiger Synchronisationsnachweis. + +Damit sind zwei getrennte Hindernisse belegt: der eigene SYSTEM-/SPNEGO-RPCpfad +scheitert weiterhin mit5, während der Builtin unter dem Administratortransport +Status lesen kann; zusätzlich zeigt der tatsächlich gelesene W32Time-Status +keine vertrauenswürdige Synchronisation. Exit0 des Tools behebt keines dieser +Produktgates und beweist kein bestimmtes internes Authentifizierungsverfahren. +Eine Netzprobe oder spätere Zeitsynchronisierung ist kein Bestandteil dieses +Schritts; daraus folgt keine Freigabe für Uhr-/NTP-/Serviceänderungen. + +Microsoft beschreibt /query /status als Statusanzeige, ohne /computer +standardmäßig lokal, und verlangt für lokale Toolnutzung Administratorberechtigung. +Die Quelle legt weder das konkrete interne Binding noch Authn-/Impersonation- +parameter dieses konkreten Builtinlaufs offen. +[Windows Time Service Tools and Settings](https://learn.microsoft.com/en-us/windows-server/networking/windows-time-service/windows-time-service-tools-and-settings) + +MS-W32T AppendixB33 beschreibt eine zusätzliche Prüfung des Rechts zur +Systemzeitänderung; auch eine nicht durchführbare Prüfung kann den Aufruf +verweigern. Der dokumentierte Clientpfad verwendet SPNEGO/Privacy mit dem +Discoveryergebnis. Daraus lässt sich ohne weitere Beobachtung nicht schließen, +welche Prüfung den konkreten RPC5 verursacht hat. +[MS-W32T Appendix B](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497) + +Ein serverseitiger RPC-Securitycallback kann Zugriffe prüfen; eine Ablehnung +wird zum Client als RPC_S_ACCESS_DENIED abgebildet. Der Zahlenwert5 identifiziert +deshalb keine einzelne fehlgeschlagene Prüfung und keinen bestimmten Callback. +[RPC_IF_CALLBACK_FN](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nc-rpcdce-rpc_if_callback_fn) + +Authentifizierung, Clientcredential-Snapshot, SSP-Verhalten und zulässige +serverseitige Impersonation sind getrennte Eigenschaften. Ein NULL-AuthIdentity +verwendet den aktuellen Login-Kontext, nicht explizit anonyme Credentials. +Der Authsetup-Aufruf nimmt einen Credentialsnapshot; die QoS-Unterscheidung +Static/Dynamic und Identify/Impersonate enthält SSP-/Transportsonderfälle. +Diese Unterschiede bleiben Hypothesen bis zu einem passenden Nachweis. +[RpcBindingSetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw), +[RPC_SECURITY_QOS](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos) + +Produktiver Transport, LocalService-Rechte und gebundene W32Time-Serveridentität +einschließlich Positiv-/Negativnachweisen bleiben offen. Discovery, Negotiate, +NTLM oder ein Mutualauth-Flag allein ersetzen keinen sicheren Identitätsbeweis. +Keine weitere Diagnosequelle und keine Produktfunktion als Teil dieses Schritts. + + +## Enger Quellenvergleich nach dem Builtinergebnis + +Die Microsoft-Methode W32TimeQueryStatus ist ausdrücklich Opnum6. Sie hat genau +zwei Parameter: das primitive handle_t hBinding und den äußeren out/ref-Zeiger +auf PW32TIME_STATUS_INFO. Kein ulInfoLevel, Providername oder weiterer +Eingabeparameter ist für diese Methode beschrieben. Das ursprüngliche gepinnte +IDL bewahrt sechs unaufgerufene Slots davor; unser tatsächlicher Aufruf ist +RmmW32TimeQueryStatus(binding,&status). Der erhaltene Microsoft-MIDL-Header149b +hat denselben Zweiparameterprototyp. Dieser Vergleich liefert deshalb keinen +Hinweis auf einen fehlenden Infolevel-/Providerparameter bei unserer Opnum6. +[W32TimeQueryStatus, Opnum6](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/7e80a465-f5f4-4c3c-87ef-12f76e45f8d1) + +Der eigene Code aktiviert das vorhandene Recht vor dem Aufruf der gesamten +RPCfunktion. Erst danach entstehen in diesem neuen Prozess Binding, Discovery +und Authsetup. Die einfache Erklärung, unser eigener statischer +Credentialsnapshot sei bereits vor Enable erstellt worden, passt daher nicht +zu dieser nachgewiesenen Codefolge. Welche Identität und Privilegabbildung die +Gegenseite tatsächlich geprüft hat, bleibt ohne passenden Nachweis offen. + +Als Unterschiede zum Builtin bleiben Authn-/SSP-Auswahl, der tatsächlich beim +Server ausgewertete Clientcredential-Kontext und dessen zulässige Impersonation +zu untersuchen. Identify2 hat provider-/transportabhängige Sonderfälle; ein +Wechsel auf Impersonate3 würde zusätzliche Autorität erlauben und wird aus diesem +Befund weder still vorgenommen noch als Produktionsfix empfohlen. Die reine +Builtin-Ausgabe offenbart diese internen Einstellungen nicht. Es werden keine +Servercallbackursache oder DetectionLocation1750-Zuordnung erfunden. + +Die originalen IDL-Kommentare nennen teilweise ältere Kapitelnummern. Der hier +verifizierte Vertrag stammt aus der aktuellen Methodenbeschreibung3.2.5.7 und +der dort gebundenen Statusstruktur2.2.17; ein Kommentarfix kann nach dem MVP +folgen. Gepinnte IDL-/MIDL-/Produktquellen bleiben in diesem Abnahmeschritt bytegleich. diff --git a/docs/windows-clock-readiness.md b/docs/windows-clock-readiness.md index b345ae3..66a6095 100644 --- a/docs/windows-clock-readiness.md +++ b/docs/windows-clock-readiness.md @@ -1,5 +1,13 @@ # Windows-Zeitstatus: Adapter und native Readinessprobe +**Neue Userentscheidung1.22:** Ein unabhängiger signierter Onlinezeitvergleich +mit dem festgelegten Server ist ausdrücklich zur Umsetzung erlaubt. +Der frühere Ausschluss eines Serverzeitankers gilt für diese Alternative nicht +mehr. [Angenommener Vertrag und offene Nachweise](windows-clock-attestation-proposal.md). +Die folgenden RPC-Belege bleiben historische Befunde; kein Clockgate dadurch +eröffnet und kein W32Time-Sync behauptet. + + Stand 2026-11-14. Ergänzung zu [Windows-Jobgrenze](windows-job-boundary.md). Diese Strecke ändert weder die Windows-Geräteidentität noch die WebUI-Grenze. Ein Zeitstatusbericht ist keine Jobgenehmigung. `NativeClock::now()` verweigert @@ -262,3 +270,47 @@ SDK-Struktur bleibt aufx64 begrenzt und wird beim MSVC-Build zusätzlich direkt gegen die native SDK-Deklaration geprüft. Dies ersetzt weder einen nativen MSVC- noch einen tatsächlichen W32Time-Nachweis. W32Time ist weiterhin gestoppt; Produktgate unverändert `ADAPTER_QUALIFIED=false`. + +## Autorisierter Dienststart — noch keine Clockabnahme + +Nach ausdrücklicher Userentscheidung1.18 wurde das vorhandene W32Time im Fall +`c3552c3f…` genau einmal gestartet und separat lesend als Running bestätigt. +RMM-Agent/Helper samt ursprünglichen PIDs, Definitionen und PKI-Metadaten, +ausgewählte NTP-/Policywerte und zentrale Jobzählungen/Flags sind erhalten. +Keine Startart-/NTP-/ACLänderung oder Resynchronisierung angefordert; normale +Synchronisierung durch den Dienst ist erlaubt. [Genauer Beleg](windows-time-service-start.md). + +Ein neuer GNU-Diagnosebuild `a817cf61…`, EXE `f5003f96…`, wurde lokal mit +identischen Quellbindungen vor/nach gebaut. Sein tatsächlicher ALPC-/Status-/ +Identitätskontrolllauf ist inzwischen ausgeführt; Ergebnis folgt unten. Der +Dienststart allein öffnet weder Clock- noch Jobgate. + +## Tatsächlicher Kandidatenlauf nach Dienststart: nicht qualifiziert + +Fall `e1f3edbb-5a2f-4d82-a449-0432913c6bd7`, EXE `f5003f96…`, nativ als +separater LocalService-Dienst: TokenSID19, kein Administratormitglied/SYSTEM, +zwei Statusproben und beide Identitätskontrollen ausgeführt. ALPC meldet jeweils +`1753`/`CLOCK_UNSUPPORTED`; die Endpunktenumeration meldet Erfolg mit0Einträgen. +Beide Negativkontrollen ebenfalls1753, **kein Ablehnungs-/Identitätsbeweis**. +Die zusätzliche Named-Pipe-Diagnose meldet1783 ohne Status. Noch unbewiesen, +ob dessen Quelle RPC/NDR oder der eigene strikte Strukturguard ist. Keine +stillschweigende Status-/Authentisierungs-/Transportlockerung. + +Der eigene temporäre Dienst wurde nach Stopped entfernt; der normale Agent und +SYSTEM-Helper wurden nicht gestoppt oder verändert. Separater Readback bestätigt +identischen Originalbericht. Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene +Flags/Rootpolicyhash vor/nach unverändert. Privater Fallabschluss +`assessment.json`, SHA256 +`d80e5f39cbd6d332deb12bf4f21e1372c88025b551db4ef33a190e3f82b3300a`. +Native Ausführung belegt, **Clockabnahme fehlgeschlagen**; Produktionsgatefalse, +keine Windowsjobs oder Capabilities aktiviert. + +Nach dem Lauf erneut gegen Microsoft geprüft: MS-W32T2.1 verlangt Named-Pipe- +Transport und nennt den authentisierten Endpunkt `W32TIME_ALT`; ein ALPC- +Endpunkt ist damit kein zugesicherter Plattformvertrag. Der bisherige ALPC- +Kandidat war ein zu qualifizierender Zusatz, keine native Windowsgarantie. +[Transportvertrag](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655), +[vollständiges IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a). +Die konkrete1783-Ursache wird separat rein diagnostisch eingegrenzt; eine +erfolgreiche unqualifizierte Pipeabfrage würde die Clockgrenze weiterhin nicht +öffnen. Bereits vorhandene Originalfehler bleiben unverändert erhalten. diff --git a/docs/windows-clock-rpc-qos5-analysis.md b/docs/windows-clock-rpc-qos5-analysis.md new file mode 100644 index 0000000..f10ca5b --- /dev/null +++ b/docs/windows-clock-rpc-qos5-analysis.md @@ -0,0 +1,108 @@ +# QOS5-Fehler87: statischer Befund der tatsächlichen RPC-Runtime + +2026-11-14. Die beiden nativen QOS5-Diagnosen erreichen keine Statusquery. +Die folgende ausschließlich lokale Analyse grenzt ihre Parameterverweigerung +an der bereits nur lesend gesicherten Windows-System-DLL ein. Sie führt keine +PE-Datei, keinen neuen Dienst und keinen RMM-Job aus. Die bestehenden131 +Produktinputs und31 Diagnoseinputs bleiben bytegleich. Produktclock und +Windowsjobgate bleiben geschlossen. + +## Primärvertrag und gesicherte Artefakte + +Microsoft beschreibt `ServerSecurityDescriptor` in QOS5 als clientseitigen +Serveridentifikationsdescriptor. Die öffentliche Dokumentation präzisiert +weder seine Auswertung für Named Pipes noch eine Pflicht zum selbstrelativen +Format. Die SID ist eine Alternative zum erwarteten Serverprincipal; ein +erfolgreich gesetztes Mutual-Auth-Flag alleine belegt bei NTLM keine +gegenseitige Authentifizierung. +[QOS5-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w), +[SetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw). + +Die tatsächlich auf der Windows-VM nur lesend kopierte `RPCRT4.dll` hat +1182928Byte und SHA256 +`35fa5f92f985cba9b33bc5f17968211d84ebb910d639ba2db8f35596befca6a6`. +Die getrennten nativen Before-/Aftermetadaten melden denselben Hash, dieselbe +Länge und Windows-Authenticode-Status `Valid`. Die lokale Kopie stimmt damit +überein. Das ist der untersuchte konkrete OS-Stand, keine Zusage für jede +Windowsversion oder jeden Transport. + +Die über den offiziellen Microsoft-Symbolserver zum CodeView-Schlüssel +`E9DD14015C33891F220822884DBE17FA1` geladene öffentliche `rpcrt4.pdb` hat +905216Byte und SHA256 +`1e31c17cb9f42e6bd503d149793104a50683dfc4421b3139a09836549aa3dd6c`. +GUID `e9dd1401-5c33-891f-2208-22884dbe17fa` stimmt überein. +DLL-CodeView-Age und PDB-DBI-Age sind jeweils1; der PDB-Informationsstream +meldet dagegen3. Diese Werte werden getrennt erhalten, kein vollständiger +Age-Gleichstand behauptet. Die unten genannten Codeadressen und der +Vtableslot sind zusätzlich unmittelbar gegen die DLL-Bytes geprüft. + +Alle OS-Binärdateien, PDB, vollständigen Disassemblies und Rohbelege bleiben +privat unter `devstate/windows-builtin-clock/f2de6c29-38f3-4e4d-813e-e9e498a870a6/` +im Hauptcheckout. Sie werden nicht ins Repository übernommen. + +## Frühere Verweigerung bei tatsächlich leerem Principal + +Der Export `RpcBindingSetAuthInfoExW` beginnt bei RVA`0x405f0`. Sein +Mutual-Auth-Parametercheck behandelt sowohl NULL als auch einen vorhandenen +Principal mit erstem UTF-16-Codeunit0 als fehlenden erwarteten Namen: +RVA`0x40962` prüft genau diese leere Zeichenfolge. Dieser Pfad verlangt +anschließend QOS-Version mindestens3 und eine vorhandene SID bei QOS-Offset +`0x20` (RVA`0x40771` bis`0x4077e`). Andernfalls liefert RVA`0x409b2` direkt87. +Der V5-Descriptor bei Offset`0x30` wird erst später betrachtet. + +Das erklärt den ersten erreichbaren Verweigerungszweig der nativen +Descriptorprobe `4b1ae5cf…`: ihr tatsächlich vorhandener Discoveryprincipal +ist leer, `Sid=NULL` und Mutual Auth ist gesetzt. Ein Wechsel nur vom absoluten +zum selbstrelativen Descriptor würde diesen früheren Check nicht verändern. +Dies ist eine aus den unveränderten konkreten Eingabewerten und DLL-Bytes +abgeleitete statische Erklärung; keine nachträglich erfundene dynamische +Debuggeraufzeichnung des ursprünglichen Falls. + +## Zusätzliche Descriptorverweigerung im OSF-Pfad + +Auch ein nichtleerer erwarteter Principal löst den nächsten Blocker nicht: + +- QOS5-Descriptor wird bei RVA`0x4099d` aus Offset`0x30` geladen und als letztes + Stackargument bei Caller-Offset`0x88` weitergereicht (RVA`0x40862`). +- Der virtuelle Aufruf benutzt Slot`0xd8`. Die tatsächliche + `OSF_BINDING_HANDLE`-Vtable bei RVA`0xdd408` verweist dort auf + `BINDING_HANDLE::SetAuthInformation`, RVA`0x7b110`. +- Dessen Prolog legt den Framepointer64Byte unter den vorherigen Callerstapel. + Somit bezeichnet `[rbp+0xc8]` genau das weitergereichte letzte Argument. + RVA`0x7b169` prüft dieses auf NULL; bei non-NULL führt RVA`0x7b170` unmittelbar + zu RVA`0x7b6a2`, Rückgabe87. Der Zweig liegt vor der Securityproviderarbeit. + +Der hier verwendete verbindungsorientierte Named-Pipe-/OSF-Pfad nimmt folglich +keinen non-NULL-Serverdescriptor an, unabhängig von dessen Format. Die native +SID-/Descriptorprobe `bcda2ede…` mit fester SID und NULL-Principal ist mit diesem +weiteren Blocker konsistent. Nicht behauptet wird, ein Debugger habe genau +diesen Branch beim damaligen Prozess beobachtet. Ein isolierter +`MakeSelfRelativeSD`-Nachfolger oder ein weiterer Descriptorvergleich mit +anderem SPN würde diese Runtimeverweigerung nicht beseitigen. + +## Tatsächliche Prüfung und verbleibende Grenze + +GNU `objdump` wurde lokal auf der gesicherten DLL ausgeführt. Ein eigener +lokaler Analysereader prüft DLL-/PDB-Hashes, GUID sowie alle getrennten +Agewerte, öffentliche Symbolpositionen, den echten Vtableslot und neun enge +Instruktionsbytesfolgen. Er prüft zusätzlich die unveränderten131 ursprünglichen +Produktinputs,27 älteren Diagnosedateien und die vier eingefrorenen +Descriptorquellen. Der erste lokale Readerlauf verweigerte ausdrücklich am +unterschiedlichen PDB-Info-Age; die anschließende Fassung erhält diese +Abweichung und bindet DBI-Age/Adressen/Bytes getrennt. Linker-Absolute-Symbole +werden nicht als PE-Sektionsadressen behandelt. + +Der abschließende statische Bericht `rpcrt4-qos5-static-analysis.json` hat +SHA256 `86328105c109e49f08b06bac9e33e1fc74c7debba88ac3951e565c63d0497a19`. +Kein neuer Native-, Build-, Identitäts-, Synchronisierungs- oder Clocknachweis +wird dadurch behauptet. Insbesondere bleiben der erfolgreiche reine +GSS9/Privacy6/Impersonate3-Statusabruf und die fehlende unabhängige Dienstbindung +getrennte Ergebnisse. + +Ein vorher separat per Pipehandle beobachteter SCM-PID-/Tokenbeleg bindet +nicht automatisch die andere, vom RPC-Runtimehandle eröffnete Verbindung. +Er darf daher keinen Ersatz für die fehlende Dienstidentitätsbindung bilden. +Ein gleichwertiger, auf der tatsächlichen Verbindung wirksamer OS-Vertrag +ist noch offen; keine Lockerung auf bloße Discovery-, Mutual-Auth-Flags oder +CLI-Textinterpretation. Auch eine positive OS-Zeitsynchronisierung würde diese +unabhängige Identitätslücke alleine nicht schließen. diff --git a/docs/windows-clock-spnego-empty-trace.md b/docs/windows-clock-spnego-empty-trace.md new file mode 100644 index 0000000..8fcc374 --- /dev/null +++ b/docs/windows-clock-spnego-empty-trace.md @@ -0,0 +1,197 @@ +# Isolierter Vergleich mit tatsächlich zurückgegebenem leerem Principal + +Stand2026-11-14: neuer getrennter Diagnosenachfolger lokal gebaut/geprüft. +**Native Ausführung, separater Readback und Cleanup durch den Hauptagenten inzwischen erfolgt; der Subagent hat keine VM-/SSH-Aktion ausgeführt.** +Produktcode, Clockgate, ursprüngliche131Quellen sowie WINNT-/SYSTEM-/EEInfo- und +F6-SPNEGO-Proben bleiben unverändert und mit ihren ursprünglichen Treibern lesbar. + +## Tatsächlicher Ausgangsbefund + +Der ursprüngliche SPNEGO-Case +`0f512772-3599-4c83-b877-41c74fe50fb0` verwendet Manifest +`f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001`. +Sein unveränderter `diagnostic-result.json` hat SHA256 +`4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9`. +Der tatsächliche Bericht meldet Discovery1/Status0/normaler Return1, +Principalpointer vorhanden1 und UTF16-Länge0. Die eigene Nichtleerprüfung +verweigert dies mit123/Stage26, vor dem Authsetup und vor Opnum6; Statusaufrufe0. +Das ist kein Nachweis eines W32Time-Statusqueryfehlers. + +Die eigene SYSTEM-Primärtokenprobe wurde vorher erhalten: kein Threadtoken, +SeSystemtimePrivilege vorhanden1, Attribute0, Enabled0. Das bleibt eine reine +Beobachtung; weder daraus noch aus dem Leerstring werden Workgroup-, Domain-, +Provider-, ACL- oder Privilegursachen abgeleitet. Readback und Cleanup des alten +Cases erfolgen ausschließlich durch den Hauptagenten mit dessen originalem +Treiber; dieser Nachfolger ersetzt keinen historischen Beleg. + +## Primärquellen und Schlussgrenze + +Die Microsoft-API beschreibt den zurückgegebenen Principal als vom RPC-Runtime +allokierte Zeichenfolge, die anschließend mit RpcStringFree freizugeben ist. +Eine zusätzliche Mindestlänge wird dort nicht festgelegt. +[RpcMgmtInqServerPrincNameW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcmgmtinqserverprincnamew) + +Die Syntax und Bedeutung des Authentifizierungs-Zielnamens bestimmt der +verwendete SSP. Das ist keine allgemeine Garantie, dass jeder SSP einen leeren +Namen akzeptiert. +[RpcBindingSetAuthInfoExW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetauthinfoexw) + +Microsoft nennt Systemdienste, für die manche Provider keinen Principalnamen +führen, und warnt ausdrücklich vor Principaldiscovery als sicherem +Serveridentitätsnachweis. Ein erfolgreicher Discoveryaufruf oder ein weiter +gelungener Statusaufruf beweist hier deshalb keine unabhängig gepinnte +Serveridentität. +[Principal Names](https://learn.microsoft.com/en-us/windows/win32/rpc/principal-names) + +MS-W32T AppendixB Fußnote16 beschreibt erfolgreiche Managementdiscovery und +danach den tatsächlich gelieferten Namen mit SPNEGO/PacketPrivacy. Sie fügt +keine Nichtleerbedingung hinzu. Die dort ebenfalls beschriebene unauthentisierte +Fallbackvariante wird hier ausdrücklich nicht implementiert. Fußnote33 beschreibt +eine zusätzliche Privilegprüfung aller authentisierten Methoden; sie erklärt +weder den jetzigen eigenen Stage26-Abbruch noch allein die Bedeutung von +Present/Enabled in unserem Tokenbefund. +[MS-W32T Appendix B, Fußnoten16/33](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497) + +Der engere Schluss ist daher lediglich eine begründete **Diagnosehypothese**: +die eigene Nichtleer-Zusatzprüfung einmal isoliert entfernen und die exakte +Runtimeantwort an den unveränderten SSP übergeben. Es wurde keine konkrete +Primärquellenpflicht gefunden, die genau diesen Diagnosevergleich verbietet. +Es wird weder universelle Leerstring-Zulässigkeit noch Produktionsfähigkeit +behauptet. + +## Exakter neuer Scope + +Vier neue Dateien unter `deploy/windows/clock-spnego-empty-trace/`: + +- `clock_rpc_spnego_empty.c`: im vorhandenen UTF16-Prüfer entfällt allein das + `!i`-Verbot am terminierenden Nullzeichen. NULL-Pointer bleiben Fehler, + Hoch-/Niedrigsurrogate, Steuerzeichen und die512-Unit-Grenze bleiben geprüft. + Der tatsächlich von RpcMgmt gelieferte Pointer wird unverändert und nicht-NULL + an RpcBindingSetAuthInfoExW weitergereicht, auch wenn er auf eine leere + terminierte Zeichenfolge zeigt. Kein erfundener SPN und keine NULL-Ersetzung. +- `system_trace_spnego_empty.c`: gleiches Token-/RPC-/EEInfo-Verhalten; + ausschließlich getrennte Symbol-, Service-, Profil- und Casepfadnamen. + `own_system_token` ist byteidentisch zum Original. +- `native.py`: eigene Case-/Manifest-/Servicebindung; Ergebnisprüfung erlaubt + nun0..512Units nur bei weiterhin vorhandenem und geprüftem Principal. + Ohne erfolgreiche einzelne Discovery kein Statusaufruf. +- `build.py`: gleicher lokaler Compiler-/MIDL-/SDKpfad; bindet zusätzlich + unverändertes F6, dessen beobachteten Ausgangscase und alle vier alten + SPNEGO-Quellen. Der kleine direkte Eltern-Wrapperdiff wird separat erhalten. + +Eigenes SCM-Serviceobjekt: `RmmClockSpnegoEmptyDiagnostic`; eigenes Profil: +`clock-system-spnego-empty-v1`; eigener Pfad: +`C:\ProgramData\RustDiscoveryBootstrap\clock-spnego-empty-trace-`. +Originale Services/Cases werden weder adressiert noch ersetzt. + +Unverändert bleiben GSS_NEGOTIATE9, PacketPrivacy6, Identify2, genau eine +Managementdiscovery und höchstens ein Opnum6 auf dem bereits bekannten +authentisierten W32TIME_ALT-Pfad. Fehler führen weder zu anderem SSP noch zu +anonymer oder unauthentisierter Wiederholung. Das unveränderte AuthIdentity-NULL +bedeutet die bestehende eigene Prozessidentität, keine neu gewählte anonyme +Identität. Die Principal-Pointer-Unterscheidung wird davon getrennt behandelt. +Maximal vier ausschließlich numerische EEInfo-Records, unmittelbare Aufnahme +vor weiterem RPC/Cleanup, keine Namen oder Parameterinhalte. + +Vor RPC werden ausschließlich das eigene SYSTEM-Token und dessen vorhandene +Privileginformationen gelesen und als numerischer Beleg create-once geschrieben. +Kein AdjustTokenPrivileges, kein Impersonate, keine Uhr-, ACL-, Policy-, NTP-, +W32Time- oder RMM-Änderung. Ein temporärer Diagnoseservice ist ausschließlich +separate explizite Bootstrapwirkung des späteren Hauptagenten, kein RMM-Job. +Readback bleibt rein lesend; Cleanup ist ein separater expliziter Vorgang nur +für den gebundenen eigenen gestoppten Service. Nach Antwortverlust kein Startretry. + +## Tatsächlicher lokaler Build + +Buildcase: +`devstate/windows-clock-spnego-empty-trace/build-9daffc05-64d1-45c2-954a-4ec642c5ef70`. +Manifest-SHA256: +`768293c37702e40876a83bbab4a24186a3b4e284cf9a193c40550dd72ef32548`. +Windows-x64-PE `ClockSpnegoEmptyTrace.exe`:99727Bytes, SHA256 +`7ca7cd51cc84678068f00d9ae5344a76485db6a600557757f925f6fcb3228fe5`. + +Verwendet wurde dasselbe gepinnte Image1b2fd985… und die ursprüngliche +Microsoft-MIDL-Ausgabe aus149bafe2 mit Headerhashdb5dbe5b… und Stubhashd806adb4…. +Keine Codegenerierung mit WIDL, kein Header- oder OUT_DIR-Patch. Beide eigenen +C-Units wurden mit Wall/Wextra/Werror übersetzt. Für die unveränderte tatsächliche +MIDL-Unit bleiben genau die bereits überprüften zwei sichtbaren Warnklassen +ohne Werror-Eskalation erhalten. Link, Strip, Importprüfung und echter +PowerShell-AST-Parse erfolgreich. EncodedCommand17146Zeichen, unter32767. + +Die DLL-Importliste stimmt **exakt** mit F6 überein: +ADVAPI32.dll, KERNEL32.dll, RPCRT4.dll und msvcrt.dll. Alle131Originaldateien und +die elf bisherigen Diagnosequellen blieben beim Build byteidentisch; das +ursprüngliche F6-Manifest und sein Ergebnisbeleg sind zusätzlich gehasht gebunden. +Vorhandene Primärunterlagen-Snapshots wurden nicht verändert. + +Der tatsächliche neue C-Prüfer wurde außerdem lokal mit einem temporären +uint16-Fixturetreiber ausgeführt: zehn Fälle einschließlich NULL, nicht-NULL +Leerstring, gültiger Surrogatfolge, ungültiger Unicode-/Steuerzeichen und +512/513Grenze bestanden. Die echte Python-Ergebnisprüfung wurde mit synthetischem +Empty-Query-Bericht geprüft und verweigerte neun Änderungen an Pointer-/Valid- +Status, Länge, Discovery-/Queryzahl, Authparametern und Tokenbefund. Das erzeugt +keinen Windows-RPC-Nachweis. Beleg `empty-local-guards.json`, SHA256 +`9d276e59c3376be3e47cc2580238904ac76bfeda08e4665b2edd5ff39011362a`. + +## Geplante native Fortsetzung, nicht ausgeführt + +Erst nach unabhängigem Rootreview dieses Source-/Manifeststands: + +```text +python3 deploy/windows/clock-spnego-empty-trace/native.py prepare --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --execute-native +python3 deploy/windows/clock-spnego-empty-trace/native.py start --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE --execute-native +python3 deploy/windows/clock-spnego-empty-trace/native.py readback --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE +python3 deploy/windows/clock-spnego-empty-trace/native.py cleanup --manifest ABSOLUTE_NEW_MANIFEST --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --id NEW_CASE --execute-native +``` + +Der ursprüngliche0f512772-Case bleibt beim alten F6-Treiber. Der neue Vergleich +beansprucht weder Clock-/Adapterqualifikation noch Serveridentitätsnachweis, +Produktgate, Signier-/Jobrecht oder eine tatsächliche native Messung. Auch ein +eventueller RPC-Return0 wäre erst ein Diagnoseergebnis; die vollständige +Zeitvertrags- und Sicherheitsabnahme bliebe gesondert erforderlich. + + +## Tatsächlicher nativer Emptyvergleich 2026-11-14 + +Der Hauptagent hat ausschließlich den neuen Case +`5e0e8ce9-b9a3-4c4a-b739-3f84d714dc94` mit obigem unverändertem +Manifest768293c3… nativ ausgeführt. Der erhaltene Ergebnisbeleg +`diagnostic-result.json` hat SHA256 +`c53378d5b6e1099a781bb007e2480609e4105b94498ce443df937a0a591ff307`. +Discovery1/Status0/Return1 liefert tatsächlich weiterhin einen nicht-NULL +Principal mit0UTF16-Units. Dieser wird unverändert akzeptiert und weitergegeben. +Danach wird genau eine Opnum6-Statusquery versucht. Ergebnis: RPCexception5, +Stage90, kein normaler RPCreturn und kein Statusobjekt. Der unmittelbar erfasste +numerische EEInfo-Befund enthält genau einen Record: Komponente2, Status5, +DetectionLocation1750, Flags0, Parameteranzahl1; Parameterinhalte werden nicht +gelesen. Eigenes SYSTEM-Primärtoken: Recht vorhanden1, Attribute0/Enabled0, +kein Threadtoken. Daraus folgt keine nachgewiesene Privileg-/ACL-/Providerursache. + +Separater rein lesender Readback +`readback-03d099ce-a024-49c7-8a80-6c30f0228756.json`, SHA256 +`7751477d29844f6f8b1e90f8c7322473014c631323aa5d88c54773445eb5f7ea`, +bestätigt den gleichen Bericht, den eigenen gestoppten Dienst und Exit0. +Exit0 bezeichnet den abgeschlossenen Diagnosebericht, keinen erfolgreichen +W32Time-Statusquery. Anschließend hat der Hauptagent den eigenen gestoppten +Diagnosedienst getrennt bereinigt. Cleanupreceipt +`readback-8786048c-06a9-43f1-bede-b62a1ef21e22.json`, SHA256 +`1eb2fdef2aef832973897bd4bb6c01f459ab30e544c603e6feb81e1a318b3bb1`, +meldet cleanup_verified=true und already_absent=false. + +Readback und eigenes Cleanup sind damit nachgewiesen. Nach dem separaten +ScopeClose hat der Hauptagent auch den After-Preservationvergleich gewonnen: +`rust-discovery-windows-pipe-drain/devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/spnego-empty-trace-after.json`, SHA256 +`a8ab4396c1c8ed4fa2f0f3b06434efb0ecb058865c69aeba278744a850dd910f`. +Alle sechs nativen Bereiche `service`, `helper_service`, `agent_kernel`, +`helper_kernel`, `files` und `helper_witness` sind exakt zum Before unverändert. +Serverflags bleiben gleich, Rootpolicycf15 geschlossen, Hooksfalse; die +Windows-spezifischen Job-/Outbox-/Permit-/Unresolved-Zähler bleiben0/0/0/0. + +Die global beobachteten Linux-Serverzähler sind ausdrücklich nicht unverändert: +30/30/26 wurden31/31/27, weiterhin unresolved0. Der Hauptagent belegt dies durch +den parallel tatsächlich über MCP beantragten und in der WebUI genehmigten +Linux-Fullscript-Caseced97b4d mit bestandenem Ergebnisbeleg89dcb583…. +Diese autorisierte parallele Wirkung wird nicht als Wirkung der Emptyprobe oder +als globale Preservationgleichheit dargestellt. Der Empty-Abnahmeschritt ist als +Diagnose abgeschlossen; sein Ergebnis bleibt RPC5. Clock-/Adapterqualifikation, +Serveridentität und Produktgate bleiben nicht nachgewiesen/geschlossen. diff --git a/docs/windows-clock-spnego-trace.md b/docs/windows-clock-spnego-trace.md new file mode 100644 index 0000000..0ca6eed --- /dev/null +++ b/docs/windows-clock-spnego-trace.md @@ -0,0 +1,169 @@ +# Isolierter SPNEGO-/Privilegdiagnosevergleich + +Stand2026-11-14: separat implementiert, lokal gebaut/geprüft; **keine VM-Aktion +durch diesen Subagenten**. Kein Produktclockgate, kein neuer Agentadapter und +keine Änderung der ursprünglichen WINNT-/LocalService-/SYSTEM-/EEInfo-Proben. +Die tatsächlichen früheren Vergleiche bleiben RPC5/Stage90 ohne normalen Return +oder Status. Ihr einzelner Runtime-EEInfo-Record mit Detection1750 beweist keine +bestimmte ACL-, Privileg- oder Anonymitätsursache. + +## Primärbefund und begrenzte Hypothese + +[MS-W32T AppendixB, Fußnoten16/32/33](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/bb576d39-587b-484a-86a4-e1d378cf9497) +beschreibt den Windowsclient mit Principalabfrage für SPNEGO und anschließend +GSS_NEGOTIATE/PacketPrivacy. W32Time prüft bei allen authentisierten Methoden +zusätzlich das Systemzeitänderungsrecht. Der bisherige feste WINNT-/NULL- +Principalpfad unterscheidet sich davon. Dies begründet einen Diagnosevergleich, +keine erwiesene Fehlerursache und keine Erlaubnis, Produktprüfungen zu lockern. + +[LocalSystem](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account) +besitzt `SeSystemtimePrivilege` standardmäßig deaktiviert. Zusätzlich kann SCM +bei ausdrücklich eingeschränkten +[RequiredPrivileges](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_required_privileges_infow) +nicht benötigte Privilegien vollständig entfernen. SID18 bedeutet daher weder +„vorhanden“ noch „aktiviert“. Die eigene neue Diagnose verwendet einen separaten +SCM-Dienst; sie beweist keinen identischen Token des Produkthelpers. Kein +RequiredPrivileges-, Konto-, SID-, ACL-, NTP- oder Maschinenrichtlinienwechsel. + +## Exakte neue Sourcegrenze + +Vier eigene sibling-Inputs unter `deploy/windows/clock-spnego-trace/`: +`clock_rpc_spnego.c`, `system_trace_spnego.c`, `build.py`, `native.py`. +Eigener temporärer Dienst `RmmClockSystemSpnegoDiagnostic`, eigener Casepfad und +eigene create-only History. Die131 ursprünglichen Quellen und sieben bestehenden +SYSTEM-/WINNT-/EEInfo-Diagnoseinputs werden vor/nach dem Build gehasht und müssen +unverändert bleiben. Neuer Wrapperdiff gegen Original74aceb6e wird erhalten; +das tatsächliche Microsoft-MIDL-Header-/Stubpaar bleibt byteidentisch. + +Vor dem ersten RPC-Aufruf liest die Hülle ausschließlich den eigenen Token mit +TOKEN_QUERY. Primärer SID18-Token ist Pflicht; ein vorhandener Threadtoken oder +ein anderer Tokenfehler beendet den Versuch, ohne Impersonation/Revert. Fester +Lookup von `SeSystemtimePrivilege`, höchstens256 SDK-`LUID_AND_ATTRIBUTES` in +4096Bytes; SDK-Buffermengen werden geprüft. Vorhandensein, rohe Attribute, +Enabled/EnabledByDefault/Removed und numerische APIfehler werden getrennt +erhalten. `token.json` wird create-only und fsync-gesichert **vor** dem fremden +RPC-Code geschrieben. Fehlendes/deaktiviertes Privileg wird beobachtet; die +Diagnose aktiviert oder vergibt es nicht. Keine Passwort-/Credentialabfrage, +kein AdjustTokenPrivileges oder sonstiger Tokenänderungsaufruf. + +Der feste lokale `ncacn_np`-Endpunkt bleibt `\\pipe\\W32TIME_ALT`. Calltimeout1500ms +wird vor der Principalabfrage gesetzt. Genau eine +[RpcMgmtInqServerPrincNameW](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcmgmtinqserverprincnamew)-Abfrage +für GSS_NEGOTIATE darf stattfinden. Diese Managementabfrage ist gesondert gezählt; +sie ist keine W32Time-Statusabfrage. Nur APIstatus0, Nonnull und ein binnen512 +UTF16-Einheiten NUL-terminierter, nicht leerer und strukturell gültiger String +ohne C0/C1-Steuerzeichen darf an SetAuthInfoEx weitergegeben werden. Strings, +Principalname, Parameterwerte oder Pointer werden niemals ausgegeben. Die API +allokiert den String intern; die512-Grenze beschränkt Prüfung/Weiterverwendung, +**keine behauptete Vorabgrenze der internen RPC-Allokation**. + +Danach ausschließlich GSS_NEGOTIATE, PacketPrivacy, IDENTIFY, statische implizite +eigene Credentials und genau dieser Principal. Kein NULL-, WINNT-, anonymer oder +anderer Auth-/Transportfallback. Die erwartete Identität des Servers wird dadurch +nicht unabhängig bewiesen; der vom Endpunkt gelieferte Principal ist ausschließlich +Diagnoseeingabe. Kein Produkt-Trust, Konto-/Service-SID-Beweis oder persistierter +Identitypin entsteht daraus. + +Höchstens eine tatsächliche Opnum6-Invocation; bei fehlender Discovery, +Stringprüfung oder Auth-/Arenafehler auch null. Der Zähler steht unmittelbar vor +dem echten generierten Methodenaufruf. Unveränderte Größen-/Statusprüfung und +64KiB-Arena, begrenztes numerisches EEInfo mit höchstens vier Records. Ursprung +der EEInfo wird numerisch zwischen Discovery, SetAuth und Status unterschieden. +Originale Fehlercodes werden vor jedem Cleanup erhalten. Principal wird auf +jedem vorhandenen Pfad mit RpcStringFreeW freigegeben, danach BindingFree; beide +Cleanupstatuses sind eigene Zahlen. Kein Probe-Retry. + +Neue Phasen25/26 kennzeichnen Discovery/Stringprüfung,91 eine enthaltene +Discoveryexception;90 bleibt eine Status-RPCexception. Ein Diagnose-Serviceexit0 +heißt ausschließlich Bericht geschrieben. `clock_qualified`, `adapter_qualified` +und `product_gate_open` bleiben stets false, auch wenn künftig ein Status käme. + +## Build und geplanter Zielablauf + +Der bekannte Offlinebuilder wird mit read-only Quellmount verwendet. Hülle und +Wrapper mit `-Wall -Wextra -Werror`; nur die drei unveränderten bekannten +MIDL-Stilwarnungen bleiben sichtbar. Keine Typ-/Securitywarnungsunterdrückung. +Nur bisherige ADVAPI32/KERNEL32/RPCRT4/msvcrt-Imports; kein neues SDK, Broker, +WMI- oder Produktfeature. Benötigte RpcMgmt-/GSS-/Tokenbindings wurden im +vorhandenen Builderheader tatsächlich gelesen, keine eigenen ABIdeklarationen. + +Der frühere lokale Pack153a1030 enthält den ersten vollständig gebauten Stand, +noch vor zusätzlichen strikten Reportkonsistenzchecks. Er bleibt historisch +erhalten und wird nicht für eine VM-Probe verwendet. Der finale separate Pack +ist nach diesen Checks erneut quellgebunden bereitgestellt. Keine native +Ausführung oder Produktqualifikation ist ein Ergebnis des Builders. + +Geplant, nicht ausgeführt: Rootreview, unveränderte vorherige Preservationzeugen, +einmaliges Prepare/Upload und genau ein Start über den vorhandenen geprüften +Bootstrapweg. Der Reader liest nur den ursprünglichen Case einschließlich des +vor RPC gespeicherten Tokenzeugen. Antwortverlust erlaubt nur Readback, keinen +erneuten Start. Cleanup ist eine getrennte explizite Phase ausschließlich für +den eigenen nachgewiesen gestoppten, exakt gebundenen Diagnosedienst; Dateien +und Originalbelege bleiben erhalten. Anschließend eigene Preservationprüfung +von RMM-/W32Time-Prozessen, Kontrollen, FileIDs/PKI/DB/Serverzustand. Keine +W32Timeänderung, kein RMM-Job und keine WebUI-Genehmigungsabkürzung. + +## Tatsächliche lokale Guards + +Die tatsächliche Reportprüffunktion akzeptierte ausdrücklich synthetische +SYSTEM-RPCfehler- und Discoveryfehler-ohne-Query-Belege und verweigerte15 +unabhängige Manipulationen von Aufrufzahl, Authstärke, Impersonation, Privileg- +Attributen, Tokenzeugen, Principal-/Parameterstrings, EEInfo-Ursprung und Gates. +Die tatsächliche extrahierte C-Principalprüffunktion wurde lokal mit leerem/ +fehlendem Namen, gepaarten/ungepaarten Surrogaten, C1-Steuerzeichen sowie exakt512 +und513Einheiten kompiliert und ausgeführt. Dies sind reine lokale Guards, +keine echten Token-/RPC-/Clock- oder VM-Ergebnisse. + +Der finale Pack liegt unter +`devstate/windows-clock-spnego-trace/build-2ebcfe9c-1e2b-4a50-99c5-3370640aeb77/`. +Manifest-SHA256 +`f6b5cd23b1599c2db4fc803fd7232dfd3522dead840e492f659e4efd7a6be001`; +PE99721Bytes, SHA256 +`ce11b0f0c400160b1580e8f68666530eaa324626a557a267ad684dc069cf2fba`. +Alle ursprünglichen131 und sieben früheren Diagnoseinputs bleiben unverändert. +Aktueller PowerShell-AST-Parser bestanden; EncodedCommand17122Zeichen. +Hülle/Wrapper ohne Warnungen unter `-Werror`; unveränderter Microsoftstub mit +genau den drei bekannten sichtbaren Stilwarnungen. Imports ausschließlich +ADVAPI32/KERNEL32/RPCRT4/msvcrt. Der tatsächliche PE-Importdump enthält keine +Token-/Privileg-/Uhränderungsimporte. + +Die aktuelle strengere Reportprüffunktion wurde anschließend erneut mit zwei +synthetischen gültigen Fehlerbelegen und **16** unabhängigen Manipulationen +ausgeführt, einschließlich einer Boolzahl statt numerischem Aufrufzähler. +Die tatsächliche extrahierte C-JSONformatierfunktion wurde lokal mit kleinem +Fehlerbericht und maximalen32Bit-Zahlen/vier EEInfo-Records kompiliert und +ausgeführt; beide Berichte waren gültiges JSON, höchstens2074Bytes. Sie ersetzt +keine native Windowsausführung. `local-guards.json` im finalen Pack kennzeichnet +`native_executed=false` und `target_called=false`. Kein Zielaufruf oder Gitaktion +durch diesen Subagenten; der Pack ist ausschließlich für Rootreview vorbereitet. + + +## Tatsächliche isolierte Windows-Probe + +Root hat den finalen Pack im separaten Fall +`0f512772-3599-4c83-b877-41c74fe50fb0` einmal gestartet. Das ursprüngliche +Resultat (SHA256 `4c99b34b8c64f877dbbf0fe860d59499f1c054de7d036016e80b84581448cfc9`) +wurde zusätzlich getrennt identisch zurückgelesen. Eigener gestoppter +Diagnosedienst anschließend explizit entfernt; kein Start/Stop an W32Time oder +RMM-Diensten und keine Privilegaktivierung. + +Tatsächlich: eigenes SYSTEM-Primarytoken ohne Threadtoken, Systemzeitprivileg +vorhanden, Attribute0, enabled0/default0/removed0. Genau eine Principaldiscovery +mit Status0 und nichtleerem Zeiger, aber **Stringlänge0**. Deshalb verweigerte +der eigene Nonempty-Guard mit123/Stage26; es gab **keine** Opnum6-Abfrage, +keinen Status, keine RPCexception und keinen EEInfo-Record.123 ist in diesem +Fall das eigene Guardergebnis, kein W32Time-Status und keine neue Bestätigung +der Ursache des vorherigen RPC5. + +Vorher-/Nachher-Erhaltung der tatsächlichen RMM-Prozessgeburten/Codehashes, +Dienste, FileIDs, PKI-/DBzeugen und des Serverzustands bestanden; Vorher-SHA256 +`c4704d1b1ce0bbb7f7e3c062274167fa2031e7a78652acfd535d31af725f720d`, +Nachher-SHA256 `e69960b20dd96e3c5c1b667ad1cc0a41fb0d0bb623e8d3f03fcf99398fc43f61`. +Windows0Jobs/Outbox/Grants/ungeklärt, Linux30/30/26/0; Clockgate bleibtfalse. + +Microsoft beschreibt die Principal-Syntax als SSP-abhängig und nennt +[Systemdienste ohne Principalnamen](https://learn.microsoft.com/en-us/windows/win32/rpc/principal-names). +Das beweist weder eine konkrete Workgroupkonfiguration noch eine RPC5-Ursache. +Die Discovery ist laut derselben Quelle kein sicherer Serveridentitätsnachweis. +Ein begrenzter separater Diagnosevergleich für den tatsächlich zurückgegebenen +leeren String wird vorbereitet; Originalfall und Quelle bleiben unverändert. diff --git a/docs/windows-clock-system-trace.md b/docs/windows-clock-system-trace.md new file mode 100644 index 0000000..a2df8a8 --- /dev/null +++ b/docs/windows-clock-system-trace.md @@ -0,0 +1,142 @@ +# Getrennter SYSTEM-Vergleich für die W32Time-RPC-Diagnose + +Stand 2026-11-14: **implementiert und lokal gebaut, nicht auf der VM ausgeführt**. +Der User-/Orchestratorauftrag erlaubt hier ausschließlich einen neuen separaten +SID18-Diagnosedienst mit genau einem lesenden Traceaufruf. Bestehende Readiness, +RPC-/Clock-Produktquellen und sämtliche131 bisherigen Buildinputs bleiben +unverändert. Keine Produktgate-/Policy-/Konto-/NTP-/W32Time-ACLänderung. + +Ausgangsbefund ist der tatsächlich ausgeführte LocalService-MIDL-Diagnosefall +`94562d81-f75f-45c8-ab6b-28b70d12bd81`: Named Pipe meldete RPC5/Stage90 ohne +Status, ALPC weiterhin1753. Der Unterschied zu früher1783 ist kein positiver +Status-/Clocknachweis. Microsoft beschreibt unterschiedliche Netzwerkidentitäten +für [LocalService](https://learn.microsoft.com/en-us/windows/win32/services/localservice-account) +und [LocalSystem](https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account). +Dies begründet den Vergleich, beweist aber keine konkrete Ursache. Auch ein +abweichendes SYSTEM-Ergebnis unterscheidet für sich weder SSPI-Credentials von +serverseitiger Token-/ACLautorisierung noch schließt es alle Harnessunterschiede +aus. Der ALPC-Endpunktbefund bleibt eine eigene offene Frage. + +## Enger neuer Quellschnitt + +Nur neue Dateien unter `deploy/windows/clock-system-trace/`: + +- `system_trace.c`: eigenständige einmalige SCM-Servicehülle + `RmmClockSystemDiagnostic`; prüft den tatsächlichen eigenen Prozesstoken mit + `OpenProcessToken`/`GetTokenInformation`/`IsWellKnownSid` auf SYSTEM und ruft + danach exakt einmal `rmm_clock_query_trace` auf. Kein Tokenwechsel und keine + Impersonation. Numerische RPC-/Tracefelder, feste Booleans und Fall-ID; + Ausgabedatei create-only, begrenzt und dauerhaft geflusht. +- `build.py`: eigenständiger Offline-C-Build mit originalem `clock_rpc.c` und + exakt denselben tatsächlich von Microsoft-MIDL erzeugten Header-/Stubbytes + aus Fall `149bafe2-3469-4580-b133-988812bcc3db`. Keine NDR-/Headerbearbeitung, + kein WIDL-Fallback und kein Patch im alten Build-/OUT_DIR. +- `native.py`: Root-Orchestrator mit getrennten expliziten Phasen `prepare`, + `start`, `readback`, `cleanup`. Vor Start dauerhaftes einmaliges Intent; + verlorener Reply erlaubt nur ursprüngliches Readback. Remote-Readback liest + ausschließlich, ändert weder ACLs noch Servicezustand und bereinigt nichts. + Cleanup darf ausschließlich den eindeutig gebundenen **gestoppten eigenen** + Diagnosedienst löschen. Alle Dateien/Originalbelege bleiben erhalten. + +Die vorhandene ReadinessEXE verweigert SYSTEM weiterhin absichtlich; sie wird +weder verändert noch als Launcher eingesetzt. C-Wrapper, Named-Pipe-Endpunkt, +WINNT/PacketPrivacy und QoS bleiben identisch zur bisherigen Diagnose. Das +Programm bewertet keinen Clockstatus und setzt `clock_qualified=false`, +`adapter_qualified=false`, `product_gate_open=false` auch bei RPC0. + +## Tatsächlich lokale Prüfungen + +```text +python3 deploy/windows/clock-system-trace/build.py +``` + +Gepinntes Image `sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9`, +Netzwerk deaktiviert, Quellsnapshot nur lesbar, eigenes Ausgabe-/Belegverzeichnis. +Neue C-Hülle und unveränderter Wrapper bestanden Clang `-Wall -Wextra -Werror`. +Für den unveränderten generierten MIDL-Stub bleiben nur dieselben drei bekannten +Stilwarnungen sichtbar: fehlende Initialisierungsbrace und zwei unbenutzte +Konstanten; keine Typ-/Securitywarnung wurde abgeschaltet. MinGW-GCC-Link, +PE-x64-/Größen-/Importprüfung und tatsächlicher PowerShell-AST-Lauf bestanden. +Der fertige EncodedCommand umfasst16666Zeichen und liegt unter32767. + +Aktueller Manifest: +`devstate/windows-clock-system-trace/build-8b5fc22c-3dbe-4924-a431-9e889d6a4b7c/manifest.json`, +SHA256 `3b2c397eec9f3aa4a1e82ba10f2812f986c9b7e69e235c8f105ebaec221eaf5e`. +Standalone-PE98028Bytes, SHA256 +`0035fee43333b7cb8d34e70b9c53b31dae49e4793abb0f1e00271572c75b7922`. +Beobachtete Imports ausschließlich `ADVAPI32.dll`, `KERNEL32.dll`, `RPCRT4.dll`, +`msvcrt.dll`. `kernel32` wird vor `mincore` aufgelöst; dieser C-Trace benötigt +keine zusätzlichen präzisen Zeit-APIimporte der Rust-Readinesshülle. +Das sind Builddaten, noch kein nativer Loader-/RPCbeleg. + +Erhaltene frühere lokale Fälle werden nicht umgeschrieben: `58611089…` +scheiterte am Clang-Linkerpfad zu GCC-Runtimearchiven; `b900df4d…` wurde wegen +zusätzlicher aus `mincore` aufgelöster API-Set-Imports verweigert; der zunächst +fertig gebaute Pack `4d49b432…` scheiterte im nachfolgenden privaten +Manifestguard am Docker-root-eigenen Linkartefakt. Der neue Pack erhält nun +zusätzlich eine bytegleiche, vom Aufrufer besessene private Originalkopie. +Keine dieser Korrekturen verändert C/Auth/MIDL oder bestehende Produktdateien. + +Sechs manipulierte Berichtsfälle, nur numerische Ausgabe, historischer Bericht +nach gebundenem Cleanup und Readback ohne Upload/Start/Cleanup wurden lokal +mit ausdrücklich **simulierten** Transport-/Reportdaten geprüft. +`local-guards.json` beim aktuellen Manifest kennzeichnet `simulated_reports_only`, +`ssh_executed=false`, `native_executed=false`. Das ist keine simuliert als echt +ausgegebene SYSTEM-/RPC-/VM-Abnahme. Original131 und sämtliche neuen Inputs +wurden vor/nach dem Build unverändert gehasht. + +## Ursprünglich geplante Root-Ausführung + +Nur der Orchestrator benutzt den vorhandenen bestätigten Zugang zur festgelegten +Windows-Test-VM. Zugang bleibt in den privaten `credentials/` des Maincheckouts; +keine VM-Adresse oder Transportpräfixe in diesem Beleg. Der Notebook-Host +führt keinen Agenten und keinen Diagnosedienst aus. + +Zuerst `native.py prepare --manifest --access-root +--execute-native`: neuer privater Remote-Scratchfall und create-once Upload; +der Dienst startet dabei noch nicht. Anschließend `start` mit genau dieser +`--id` und `--execute-native`: eigener LocalSystem-Dienst wird einmal angelegt +und gestartet. Ein Create-once-Marker steht vor jeder möglichen Wirkung. + +`readback --id ` braucht **kein** `--execute-native` und +liest ausschließlich denselben Fall. Bei fehlendem/unklarem Ergebnis kein +neuer Start und kein erneuter Upload. Der tatsächliche numerische RPCcode +kann auch bei vollständig ausgeführter Diagnose ein Fehler sein; das ist +kein bestandener Status-/Clockbeleg. + +Erst danach gesondertes `cleanup --id --execute-native`. +Es verweigert fremde Binär-/Intent-/Servicekonfiguration, laufenden Dienst +oder wiederholte unklare Löschung. Bei Antwortverlust nur Readback. +Keine automatische Bereinigung im Leseweg, kein Stop fremder Dienste, +kein impliziter Reboot, kein Gatewechsel und kein RMM-Auftrag. + +## Tatsächlicher SYSTEM-Vergleich und getrennter Abschluss + +Root führte nach Source-/Manifest-/PowerShell-Parserprüfung den aktuellen +Pack8b5fc22c auf der Windows-Test-VM aus. Eigener Fall +`562ff9de-67ff-48a1-96f0-c2474b3b0777`: erst create-only Vorbereitung/Upload, +danach einmaliger eigener Dienststart. Das C-Programm bestätigte seinen +tatsächlichen SYSTEM-Token und führte genau einen Status-Traceaufruf aus. + +Tatsächliches Ergebnis: **RPC5, Stage90**, `rpc_exception=5`, kein normaler +nativer Return, kein Status. Der Dienst stoppte mit Exitcode0; dieser bestätigt +ausschließlich den abgeschlossenen Diagnosebericht, keinen erfolgreichen RPC. +Originalbericht danach im selben Fall separat rein lesend identisch bestätigt. +`diagnostic-result.json`-SHA256: +`5d8475f70a9cd6ef8713edb0264fa0d560499fa6abb6f5483e47b2332a4e6ca5`. + +Der Vergleich löst die Verweigerung durch den Callerwechsel nicht auf. Die +Erklärung allein durch LocalService ist damit nicht belegt. Ob SSPI, NPFS, +Serverautorisierung oder eine andere RPCschicht5 erzeugt, bleibt offen. Keine +beobachtete tatsächliche serverseitige Caller-/Service-SID und kein +Serveridentitäts- oder TrustedClock-Nachweis. + +Anschließend wurde ausschließlich der eigene exakt gebundene gestoppte Dienst +mit dem separaten Cleanupaufruf entfernt. Kein Stop eines bestehenden Diensts, +keine W32Time-ACL-/NTP-/Kontoänderung. Vorher/Nachher-RMM-/Serverabgleich +bestätigt dieselben PIDs/Prozessgeburten, Code-/Policydateien, PKI-/DB-/Lock- +Datei-IDs, Helperwitness und geschlossene Zähler/Flags. NachherbelegSHA256: +`65a9e98b6933a5c5f45acd8e6edcca837eaf28a7aeab0e8637ade8b09bf6c18c`. +Produktclock, Capabilities und Jobs bleiben gesperrt. Der nächste getrennte +Diagnosevorschlag erfasst ausschließlich begrenzte numerische RPC-EEInfo direkt +am Fehler; keine schwächere Authentisierung, Impersonation oder ACLänderung. diff --git a/docs/windows-console-boot.md b/docs/windows-console-boot.md new file mode 100644 index 0000000..e3bcbc2 --- /dev/null +++ b/docs/windows-console-boot.md @@ -0,0 +1,47 @@ +# Manueller Windows-Konsolenneustart — tatsächlicher Nachbeleg + +Der Benutzer stimmte das konkrete ruhige Zeitfenster ab, startete die VM über +die Konsole selbst und meldete anschließend „Neustart ist durch“. Kein +Remote-Reboot, kein RMM-Rebootjob und kein Produktionsfreigabenachweis. + +Nur lesender SSH-Nachbeleg unter unverändert geprüftem Hostschlüssel, +Fall `d888645b-b403-47b5-b45e-89a2ef03bd02`, beobachtet +2026-11-14T12:27:45.5207910Z: + +- Tatsächlicher Boot2026-11-14T12:26:50.5000000Z. +- Agent89004ad3… Running/Auto/LocalService, PID3172; Image unverändert. +- Helpere6aacbdd… Stopped/Manual/LocalSystem; Image unverändert. +- W32Time Stopped/Manual/LocalService. Kein erneuter Start in diesem Schritt. +- Windows-Update-Neustartmarkerfalse; CBS-Neustartmarker weiterhintrue. + +Privater BerichtSHA256 +`ab4a99b7cfc1d2f48de9ede45357b7c43d9df7b5f398fb5906009921bd327af9`. +Das beweist den erfolgten Boot und die beobachteten Dienst-/Markerzustände, +keine vollständige PKI-/Datenbankerhaltung oder neue Runtimeabnahme. Die +MSVC-Installation bleibt bei vorhandenem CBS-Marker gesperrt; keine Marker +entfernen oder Installation erzwingen. Die genaue Ursache bleibt offen. + + +## Bereits autorisierter Zeitdienst nach diesem Boot + +Eigener neuer Fall `203ce31a-e81e-4a38-af34-a9f1f08e5dc0`: W32Time einmal +gezielt gestartet und getrennt nur lesend Running nachgewiesen. Der erste +historische Startfall und dessen globaler Einmalmarker bleiben unverändert. +Die neue Admission ist fest an den tatsächlich bestätigten Boot gebunden; +kein allgemeiner Autostart oder Retry. AgentPID3172 Running und HelperStopped +bleiben erhalten; ursprüngliche Image-/Konfigurations-/PKI-Metadaten und +Dienstdefinitionen einschließlich Startarten/ACLs/SIDtyp sowie ausgewählte +stabile NTP-/GPO-Werte unverändert. Schlüsselinhalt wurde nicht gelesen. +Zentralzähler und geschlossene Testflags vor/nach Start und Readback identisch. +Normale Zeitsynchronisierung war durch die bestehende Userfreigabe erlaubt. + +Neue Quelle `deploy/windows/time_service_after_boot.py`, SHA256 +`7e533bc8624ac7c779812a3f0dde0a25d619bc7553681c1639c48b34cb2c842c`, +abgeleitet aus unveränderter ursprünglicher Quelleef5d4ce8…; enge vier +Substitutionen, Python-/PowerShell-AST und unabhängiger Quellreview bestanden. +Neuer Einmalmarker statt Reset des alten. Verlust einer Startantwort erlaubt +ausschließlich Readback desselben Falls. ErgebnisSHA256 +`badcc32035686f63b1aacf4183b53a802ee93a0a613f7ac89e40dee2de13d3ae`; +separater Readback bestätigt exakt den Originalbericht und denselben Nachzustand. +Dies qualifiziert keine vertrauenswürdige Uhr: Clockgate unverändertfalse, +keine RMM-Jobs, kein Helper-/Fixturestart, keine Änderung an NTP oder Startarten. diff --git a/docs/windows-dev-access-recovery.md b/docs/windows-dev-access-recovery.md new file mode 100644 index 0000000..373d4cc --- /dev/null +++ b/docs/windows-dev-access-recovery.md @@ -0,0 +1,262 @@ +# Windows-Entwicklungszugang: Ablauf und vorbereitete Konsolenwiederherstellung + +Stand: 2026-11-14. Der bisherige SSH-Entwicklungszugang lief am +**2026-11-14T12:55:31.254999+00:00** ab. Die vorher vorbereitete automatische +Verlängerung wurde **nicht betreten**: kein Server- oder Windows-Enter, keine +Ablaufzeitänderung und kein angelegter Renewalworker. Die drei fehlgeschlagenen +Vorbereitungen und ihre Quellen bleiben historische Belege. + +**Aktueller Stand:** Die spätere User-Konsolenwiederherstellung wurde +erfolgreich ausgeführt; Root bestätigte anschließend die tatsächliche Rückkehr +des gepinnten SSH-Zugangs. Auch der getrennte vollständige Key-/Task- +Erhaltungsabgleich und der lokale Accessmetadaten-CAS sind inzwischen bestanden. +Einzelheiten stehen im neuen Abschlussabschnitt dieser Verlaufserfassung. + +Diese Entwicklungshilfe ist SSH-Bootstrap, keine RMM-Aktion und kein Ersatz für +Geräte-mTLS, Tenantgrenzen, TrustedClock, signierte Grants oder die +WebUI-Genehmigung. Das Notebook bleibt ausschließlich Entwicklungsrechner. + +## Tatsächliche abgebrochene Vorbereitungen + +| Fall unter `devstate/windows-client/dev-access-renewal/` | Tatsächliches Ergebnis | +| --- | --- | +| `45626a0c-edc4-4f35-9f36-921692bccbc1` | Rein lesende Windows-Vorbereitung verweigerte `Transport owner` vor dem Serveraufruf. Die zwei öffentlichen `.pub`-Dateien gehörten dem tatsächlichen lokalen Builtin-Administrator mit SID-Endung `-500`; deren bestehende öffentlichen Leserechte waren für die ursprüngliche private Dateiprüfung zu weit. Nur die separate öffentliche Metadatenprüfung wurde später präzisiert; keine ACL-Reparatur. | +| `d40c06a4-d6d3-4dc0-9ef6-b1ef1197bcc9` | Rein lesende Windows-Vorbereitung verweigerte `VariableNotWritable`: die Hilfsvariable `$host` kollidierte mit PowerShells schreibgeschütztem `$Host`. Die Quelle wurde anschließend auf `$hostPublic` korrigiert. Keine Server- oder Windowsmutation. | +| `6988fd11-0e0a-4fd7-878d-96b130d83aee` | Der lokale Datums-/Fristguard verweigerte nach Ablauf der alten Frist, noch vor `prepare-intent.json`. Dies war kein weiterer ausgeführter Windows-Readonly-Test. Der leere lokale Fall bleibt erhalten. | + +Die ersten beiden Fälle enthalten nur Vorbereitungsintent und Controllerkopie; +keiner enthält einen Server-/Windows-Enterintent. Root bestätigte zusätzlich, +dass kein Renewal-Enter und kein Worker ausgeführt wurden. Ablauf und Fehler +werden nicht nachträglich als erfolgreiche Verlängerung ausgegeben. + +## Getrennte Wiederherstellung des bereits abgelaufenen Zugangs + +Die neue Quelle +[`console_access_recovery.py`](../deploy/windows/console_access_recovery.py) +hat SHA-256 +`703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053`. +Sie trennt den Server-CAS von der erst anschließend durch den User in der +Windows-Administratorkonsole auszuführenden Phase. Die frühere +[`dev_access_renewal.py`](../deploy/windows/dev_access_renewal.py) wird für den +abgelaufenen Lease nicht umgedeutet oder erneut gestartet. + +Root führte ausschließlich den Serverteil im neuen Fall +`4b6506a7-6c3e-4cca-a497-618fa8666300` aus. Dessen `server-entered.json` +meldet `completed=true`; ein getrennt gespeicherter lesender Readback bestätigt +dieselbe neue Autorisierungsdatei und Frist: + +| Bindung | Tatsächlicher Beleg | +| --- | --- | +| Neue feste UTC-Frist | `2026-11-15T13:05:58+00:00` | +| `authorized_keys` nach CAS | `fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2` | +| Unverändertes SSH-Profil | `932adc2ad3e88c3a47054c3d09e44024f21918cf144f0bb349bd8763e844e482` | +| Unveränderte effektive SSH-Konfiguration | `3a345912fdd4bb9bb29628d670a8bdbdfbbc22b3e308ab56fb3bafb7bc15533a` | +| Server-Enterbeleg | SHA `2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317` | +| Getrennter Readback | SHA `f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787` | + +Der Serverteil ersetzte ausschließlich den Ablaufwert des gleichen bestehenden +restriktiven Tunnelkeys. Keybytes und Optionen, Loopbacklistener +`127.0.0.1:22240`, SSH-Profil, Serverhostpin und der Account +`rmm-win-tunnel` mit Shell `/usr/sbin/nologin` blieben gebunden. Historische +`prepared.json`/`registered.json` wurden nicht überschrieben. Dieser CAS +veränderte weder einen Downloadlease noch die RMM-Konfiguration. + +## Öffentliches Paket und noch offene Userphase + +Unter dem privaten Consolefall liegt das **inzwischen zurückgezogene, +historisch erhaltene** öffentliche Paket mit genau +`Recover-ExistingDevAccess.ps1`, `public-recovery.json` und `README.txt`. +Es enthält öffentliche Pins und feste Parameter, keine privaten Schlüssel oder +Tokens. Die Paketdateien sind zusätzlich im unveränderlichen Intent gebunden. + +| Datei | SHA-256 | +| --- | --- | +| `windows-dev-access-recovery.zip` | `7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7` | +| `Recover-ExistingDevAccess.ps1` | `564da57d70ef06df7bd9adc37565b7e28ef446a6c69b984711c5b77b28441e8a` | +| Consoleintent | `cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a` | + +Vor der Userausführung fand Root im Konsolenguard eine unbelegte +Ganzsekundenannahme für den alten `AccountExpires`-Wert. Der feste Wert +`134391345310000000` ließ den Bruchteil `.254999` der ursprünglichen +Konfigurationszeit weg. Ein lokaler .NET-Roundtrip derselben vollständigen +UTC-Zeit ergibt `134391345312549990`. Dieser lokale Roundtrip allein war ein +**abgeleiteter Sollwert**, noch kein gemessener Windows-VM-Accountwert. Der +spätere tatsächliche Userreadback ist unten getrennt dokumentiert. Das alte Paket wird deshalb nicht zur +Ausführung weitergegeben; sein gültiger getrennter Server-CAS bleibt erhalten. + +Die kleine neue Quelle +[`console_access_precision.py`](../deploy/windows/console_access_precision.py) +mit SHA +`8b4d14edf0794c4ef662d7587b4538f8e7aebc06c11db76c3cafc2c24c11a37b` +erzeugte den neuen lokalen Consolefall +`5c96d3d8-1657-40c8-a6ec-c00b63a98210`. Sie bindet den ursprünglichen +Serverintent, Enterbeleg und getrennten Readback des Falls `4b6506…` sowie +sämtliche alten Paketdateihashes. Es gibt weder einen Serveraufruf noch eine +erneute Fristverlängerung: `2026-11-15T13:05:58+00:00` bleibt unverändert. + +Der neue Guard berechnet genau einen erwarteten 64-Bit-Wert über +`[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc()` aus der +zuvor anhand der Originalbytes und der exakten alten Zeit geprüften Config. +Keine Rundung, Toleranz oder alternative Zeit wird akzeptiert. UUID und +Provenienzbeleg sind neu; die drei Mutationsschritte ab `File.Replace` bis +zum Ende sind gegenüber dem alten Paket bytegleich. Falls ein früheres Paket +entgegen dem bisherigen Kontrollstand bereits erfolgreich ausgeführt wurde, +muss der alte Config-Hashguard verweigern. Dann nur lesen und durch Root +abgleichen, kein neuer Versuch. + +| Neues Korrekturartefakt | SHA-256 | +| --- | --- | +| ZIP im Fall `5c96d3d8…` | `dbcd5ca863c0b09f89b67eb10eeaeaf89b941bbc5840079f1bb0c36dc6ff3b3e` | +| Neues `Recover-ExistingDevAccess.ps1` | `4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69` | +| Neuer unveränderlicher Intent | `eae7995b5735bf1e8f0fafc0ae6ccf6bdd4576566663c1256a511f6c3408e32e` | + +Die Userphase mit dem Konsolenskript des Falls `5c96…` wurde inzwischen begonnen, +scheiterte aber vor jeder Wirkung an `Get-History / IdCannotConvert`: PowerShells +standardmäßiger Alias `h` wird auch unter `-NoProfile` vor der Funktion `H` +aufgelöst. Der Fehler trat im ersten Case-/Configguard vor `New-Item` auf. +Es wurde damit keine Konfigurations-/Accountablaufzeit geändert und kein +Tunneltask gestartet. Die unveränderte Case-Abwesenheitsprüfung bleibt für die +erste tatsächlich noch unerreichte Wirkung verbindlich. + +Die separate lokale Quelle +[`console_access_hash_command.py`](../deploy/windows/console_access_hash_command.py) +hat SHA `b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad`. +Sie erzeugt `Recover-ExistingDevAccess-HashFix.ps1` mit SHA +`d366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c`. +Ausschließlich die eine Funktionsdefinition und alle fünf Aufrufe heißen nun +`Get-RmmRecoveryFileSha256`; eine inverse Ersetzung ergibt exakt die alten +PS1-Bytes. Alle übrigen Guards, Pins, Fristen, die gleiche Console-UUID und +Mutationsschritte bleiben erhalten. Kein Alias wird entfernt oder geändert. + +Der kleine Userpatch `Create-VerifiedHashFix.ps1` mit SHA +`385a388476cef0c85f02bca236ade48f28a041476330d3e309ab1ca2f22bb9f5` +prüft zuerst den ursprünglichen PS1-Hash `4977665f…`, erzeugt ausschließlich +eine zuvor fehlende neue Datei mit UTF-8 ohne BOM, verlangt deren vollständigen +Hash `d366ae17…` und startet erst dann den separaten Bootstrapprozess mit +`-NoProfile -ExecutionPolicy RemoteSigned`. Kein neuer Download ist für diese +lokale Korrektur erforderlich. Bereits vorhandene Korrekturdateien werden +nicht überschrieben und eine unklare frühere Wirkung wird nicht wiederholt. + +ASTs, vollständige Command-AST-Ersetzung sowie ein tatsächlicher lokaler +Hashfunktionsaufruf bei unverändert vorhandenem Alias `h=Get-History` bestanden; +der unabhängige Review bestätigte die reine Namensänderung. Das sind lokale +PowerShellprüfungen, kein weiterer Windows-VM-Erfolgsnachweis. Alte Quellen, +ZIPs und Fehlerbelege bleiben unverändert. + +Die anschließende tatsächliche Userausführung des HashFix-Skripts `d366ae17…` +verweigerte im kombinierten anfänglichen Case-/Config-/Bootstrapguard weiterhin +vor Wirkung. Root ließ zunächst ausschließlich fünf Werte lesend ausgeben. +Der Userreadback ergab: + +| Tatsächlicher Konsolenwert | Ergebnis | +| --- | --- | +| Recoverycase vorhanden | `false` | +| Config-SHA | `4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823` | +| Bootstrap-SHA | `332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f` | +| Configablaufzeit | `2026-11-14T12:55:31.254999+00:00` | +| Tatsächliches Account-FILETIME | `134391345312549990` | + +Damit ist dieser Guardfehler konkret erklärt: die Recoveryquelle erwartete +den späteren Repositoryhash `9e992602…`, obwohl die VM exakt das ursprünglich +veröffentlichte Bootstrap mit Hash `332ceeed…` behielt. Das erhaltene Original-ZIP +`cba15946…` enthält genau diese Datei und die Config `4ad28ec5…`; das ebenfalls +veröffentlichte Reparaturpaket `2558448b…` bindet denselben Bootstraphash als +Voraussetzung und ersetzt Bootstrap/Config nicht. Der Maintainerteil beider +Bootstrapquellen ist bytegleich. Es wird somit keine unbekannte Datei anhand +eines beliebigen neuen Readbacks übernommen. + +Die getrennte lokale Quelle +[`console_access_original_bootstrap.py`](../deploy/windows/console_access_original_bootstrap.py) +mit SHA `c0816055407c17af4c0bf4b5bd5ce3055e5a9d44fe7f2334f5aa7913520478c6` +bindet den tatsächlichen Userreadback und beide publizierten Originalpakete. +Sie erzeugt `Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit SHA +`aba0a5a4152347e639266e95a05eae4343a99be9070a94fa4fc6501bfc3283d2`. +Ausschließlich die eine Bootstrap-Sollhashkonstante wird von `9e992602…` auf +das bestätigte Original `332ceeed…` berichtigt. Alle anderen Bytes des +`d366ae17…`-Skripts, einschließlich gleicher Case-Abwesenheit, voller UTC- +Präzision, Aliasfix, Fristen und Wirkungsschritte, bleiben identisch. + +Der Userpatch `Create-VerifiedOriginalBootstrapFix.ps1` hat SHA +`64f1d62ea3a87d4db7103ca01f7d735689caf54a7cc4b2458908956624062549`. +Er verlangt den vollständigen Eingabehash `d366ae17…`, schreibt nur eine +zuvor fehlende neue Datei, prüft deren vollständigen Hash `aba0a5a4…` und +startet erst danach den separaten Bootstrapprozess. Lokaler Python-/AST-Test, +ein tatsächlicher lokaler PowerShelllauf des Patchpräfixes ohne Kindstart und +der unabhängige byteweise Review bestanden. Dadurch wird die Userausführung +der korrigierten Wirkung noch nicht vorweggenommen. Kein Serveraufruf und keine +weitere Serverfriständerung wurden durch diese lokale Korrektur ausgeführt. + +Eine erfolgreiche Windows-Konsolenphase und Tunnelwiederkehr sind **noch nicht +nachgewiesen**. Die korrigierte Strecke prüft die alten +Config-/Bootstrapbytes und öffentlichen Pins, den bestehenden Account sowie den +unveränderten SYSTEM-Tunneltask. Erst bei `Ready` und ohne verbliebenen +Maintainer/SSH-Kindprozess darf sie die vorhandene Konfigurations- und +Accountablaufzeit erneuern und den Originaltask mit dauerhaftem Startintent +**einmal** starten. Private Keydateien werden nur über Metadaten beobachtet, +nicht inhaltlich gelesen. Keine Installation, ACL-Reparatur, neue Schlüssel, +zusätzlichen SSH-Rechte, Prozesskills, Reboots oder RMM-Wirkungen. + +Die README verlangt den unabhängig mitgeteilten Downloadhash und den festen +PS1-Hash. Ein etwaiges `Unblock-File` betrifft nur diese exakt geprüfte +Download-Datei; `RemoteSigned` nur den separaten Bootstrapprozess. Eine +verweigernde GPO oder ein fehlgeschlagener Guard wird nicht umgangen. Ein +bereits vorhandener Recoveryfall bleibt zur lesenden Inspektion erhalten. + +Eine gesonderte, auf 45 Minuten begrenzte Veröffentlichung über den vorhandenen +öffentlichen TLS-Bootstrapdienst wird durch Root separat behandelt. Dieser +Server-CAS und diese Dokumentation belegen noch keine Downloadveröffentlichung. +Nach der Userausführung bleiben tatsächliche Tunnelwiederkehr, ursprüngliche +SSH-Hostidentität, erhaltene Schlüssel/Taskdefinition und die lokale +Accessmetadatenfortschreibung durch Root zu prüfen. **Neuer Windowszugriff ist +bis dahin nicht nachgewiesen.** + +Lokale Python-/AST- und Paketprüfungen sowie unabhängige Source-Reviews bestanden. +Der lokale Paketfixture verwendete einen gemockten Serveraufruf und ist kein +zusätzlicher nativer Recoverybeleg. Kein RMM-Job, keine Capability oder +Clockbereitschaft folgt aus der Zugangswiederherstellung. + +## Update: User-Konsolenerfolg und tatsächlicher gepinnter SSH-Kontakt + +Der User meldete die erfolgreiche Ausführung der korrigierten Konsolenstrecke +`Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit Hash `aba0a5a4…`. +Root erhielt danach über den bereits gepinnten SSH-Zugang tatsächlich eine +getrennte rein lesende Antwort. Der lokale Verifikationsfall ist +`fc7a6ad5-5ec5-4280-b629-851aad2529b2`; sein `readback.json` hat SHA +`bb0e2b4747068433bcb7c950743ef56007f22206ca5d4b458f6b8221a4a031e2`. +Der Beleg nennt weiterhin den ursprünglichen Consolefall +`5c96d3d8-1657-40c8-a6ec-c00b63a98210`, `read_only=true`, +`completed=true` und `no_jobs=true`. + +| Tatsächlich beobachteter Wert | Ergebnis | +| --- | --- | +| Configablaufzeit | `2026-11-15T13:05:58+00:00` | +| Accountablaufzeit als FILETIME | `134392215580000000` | +| Originaler Reverse-Tunneltask | `Running` | +| `RmmDiscoveryWindows` | `Running`, PID `3172`, `NT AUTHORITY\LocalService`, Startart `Auto` | +| `RmmDiscoverySystemHelper` | `Stopped`, PID `0`, `LocalSystem`, Startart `Manual` | +| `W32Time` | `Running`, PID `3488`, `NT AUTHORITY\LocalService`, Startart `Manual` | + +Damit ist die Rückkehr des Entwicklungszugangs belegt. Die früheren Aussagen +zur noch offenen Userphase bleiben historische Zwischenstände. Der zusätzliche +rein lesende Erhaltungsbeleg desselben Falls (`preservation.json`, SHA256 +`490e01809ca1e4225f1dbb6a0a4414cf77f7822be31233366480b3a0d4810592`) +bestätigt alle sechs festen öffentlichen Dateien samt SHA/SDDL, Metadaten und +SDDL der vier privaten SSH-Schlüssel ohne Lesen ihrer Inhalte, den exakten +Originaltask-XML-Hash und Runningzustand, Account-SID sowie alle öffentlichen +Pins. Danach wurde lokal ausschließlich die Frist im Accessmetadaten-JSON per +CAS auf `2026-11-15T13:05:58+00:00` fortgeschrieben. Der SSH-Präfix blieb exakt +erhalten; Original und neuer Metadatenbeleg sind privat archiviert. Die alten +Fehlerfälle, Pakete und Korrekturquellen bleiben erhalten. + +Der Readback ist kein Paarupgrade-, TrustedClock-, Boot- oder RMM-Jobnachweis. +Insbesondere eröffnet `W32Time=Running` keine Clockbereitschaft. Der Helper +war tatsächlich noch gestoppt; daraus wird kein authentisierter neuer +Agent-/Helper-Pipeaustausch abgeleitet. Root führt die getrennten Pipe-/MIDL- +Prüfungen erst anschließend fort. + +Der User hat den nächsten Arbeitsfokus ausdrücklich auf die Skriptkonsole mit +vollständigem Shell-/PowerShellinhalt, tatsächlicher WebUI-Plangenehmigung, +Ausgabe und expliziten Root-/SYSTEM-Ausführungsrechten gelegt. Paketabnahmen +sind nachgeordnet. Der erneuerte SSH-Bootstrapzugang verleiht selbst keine +RMM-Ausführungsrechte und ersetzt keine dieser noch separat nachzuweisenden +Genehmigungs- und Ausführungsgrenzen. diff --git a/docs/windows-eventlog-contract-acceptance.md b/docs/windows-eventlog-contract-acceptance.md index 7403819..aec9aca 100644 --- a/docs/windows-eventlog-contract-acceptance.md +++ b/docs/windows-eventlog-contract-acceptance.md @@ -44,7 +44,7 @@ python3 deploy/windows_eventlog_acceptance.py windows --manifest devstate/window Artefakte und lokale Belege bleiben im isolierten Eventlogworktree. Ausschließlich `--access-root` liest bei ausdrücklicher nativer Ausführung streng geparste -bestehende SSH-Konfigurationen für Cloud-Linux116.203.20.85 beziehungsweise den +bestehende SSH-Konfigurationen für Cloud-Linux beziehungsweise den bekannten gepinnten Windows-Reversezugang. Keine Credentialkopie oder neue Hostkeyannahme. Windows bindet den SHA256 des zuvor tatsächlich verifizierten Linuxbelegs desselben Manifests. diff --git a/docs/windows-gates.md b/docs/windows-gates.md index 66069f9..9cfbd1b 100644 --- a/docs/windows-gates.md +++ b/docs/windows-gates.md @@ -1,6 +1,6 @@ # Windows-Client: Abnahmegates -Stand 2026-11-14, Spezifikation 1.17. Der Windows-11-x64-Gast ist ein eigenes +Stand 2026-11-14, Spezifikation 1.18. Der Windows-11-x64-Gast ist ein eigenes Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner; Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht. @@ -12,9 +12,10 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht | HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. | | TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. | | Signierter Jobkern | Gemeinsamer Kern zuletzt nativ Linux80→Windows58 qualifiziert. Neuer enger SYSTEM-Delegationsadapter mit dauerhaftem Intent, deny-only Abandon und unabhängigem RawMirror implementiert; native23+7Units bestanden. Bestehender laufender passiver Client bleibt unverändert; neue Artefakte noch nicht installiert. Jobs bleiben deaktiviert. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Units ersetzen keinen LocalService-/SYSTEM- oder Jobnachweis; [Quellenstand](windows-system-delegation-source.md). | -| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. | +| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Separates optionales festes RemoteSigned-Prozessprofil ausdrücklich erlaubt, sichtbar an Plan/Grant gebunden; native Vertragsunits zuerst Linux23, danach Windows22 bestanden, Quellenbranch gepusht. Keine tatsächliche Jobausführung oder Profilcapability. | Profilquelle in die laufende Strecke übernehmen, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. Maschinen-/Gruppenrichtlinien unverändert. | | Privilegierte Aktionen | Eigener SYSTEM-Helper nativ installiert und einmal gestartet, Manual/LocalSystem, leere Aktionsliste und Wirkungen/Reboot gesperrt. Die echte LocalService-Agentprobe scheitert derzeit; kein positiver Peer-/Sync-/Wirkungsnachweis. | Fehler ohne Erweiterung der Sicherheitsgrenze diagnostizieren; gegenseitige SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen. | | Pakete/Dienste/Logs | Kleines MSI1.0.0 auf der VM erstellt, nur lesend geprüft und nach Download gehasht; keine Installation. Dienst-/Eventlog-/Paketquellen teilweise vorbereitet, keine native Aktionsabnahme. | Unveränderliche Tenantrezepte integrieren; UI-genehmigte MSI-/EXE-Installation/Upgrade/Noop, Dienste und Logs mit unabhängigen Nachbedingungen prüfen. | +| Eventlog-Vertrag | Im separaten Branch `codex/windows-eventlog` fester Application-/Fixtureprovider, authentisierter begrenzter Worker und hashgebundene UI implementiert/geprüft. Lokal238Rust/PG1/Web38 bestanden; nativ Linux24→Windows23 Vertragsunits ohne Skips. Keine Live-API-Abfrage, Runtimeinstallation oder Capabilityaktivierung. | Tatsächlichen LocalService-Provider und ausschließlich WebUI-genehmigten Job samt Grenzen/Fehlern auf dem Windowsgast qualifizieren. | | Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. | | Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. | | Reboot/Installer | Entwicklungsbuild unsigniert, GNU-Crossbuild; kein MSVC-/signierter Installer-/Windows-Rebootnachweis. | Eigene Abnahmen; kein Windows-Reboot ist durch den bereits ausgeführten Linux-Testreboot autorisiert. | diff --git a/docs/windows-midl-native-codegen.md b/docs/windows-midl-native-codegen.md new file mode 100644 index 0000000..456eb37 --- /dev/null +++ b/docs/windows-midl-native-codegen.md @@ -0,0 +1,40 @@ +# Microsoft-MIDL-Codegen tatsächlich auf der Windows-VM bestanden + +Der separate Bootstrapfall `149bafe2-3469-4580-b133-988812bcc3db` führte +ausschließlich die zwei festen Microsoft-SDK-Codegentools auf der Windows-VM +aus. Keine Installation, kein RPC-Aufruf, keine Produktdienst-/Registry-/PATH- +Änderung und kein RMM-Job. Die originale Quelle +`deploy/windows/midl_codegen.py` bleibt mit SHA256 +`078bf2303979dbeccdb7eb84e116325e7f155146d93d0dc0fff6b3e6bdd1b2eb` +unverändert. + +Vor dem Toolstart wurden beide Dateien tatsächlich nativ zugelassen: +AuthenticodeValid und OnlineChainValid, Microsoftsigner mit Thumbprint +`B835FC295FFB94EA2FCA23B0E9C1EDA3FBA4E07D`, Dateiversion8.1.628.1. +Der Zulassungsbeleg hat SHA256 +`4b10a0639cf8f77f9cf0a9c5031b708fe4d2d73344673fba2eecd92cd0a78cc2`. +Diese vorherige Prüfung führte die Tools noch nicht aus. + +Der anschließende eigene Codegenprozess wurde einmal unter den vorbereiteten +JobObject-/Handle-/Zeit-/Dateigrenzen ausgeführt und meldete `complete=true`. +Danach wurden die vier festen Ausgabedateien separat im selben Fall nur lesend +zurückgelesen, Base64/Länge/SHA geprüft und bytegleich privat gespeichert. +ReadbackSHA256: +`0dc2373825f7f8f224cda04ecd5c521dd3c37a6e712bc3ed83bc4fa6d0d89c8c`. + +| Tatsächliche Datei | Bytes | SHA256 | +|---|---:|---| +| `w32time.h` |3779|`db5dbe5b335eaa58a6512d4abfda44e7273f3aa8a43077dcb0719e4b97ee2bde`| +| `w32time_c.c` |18866|`d806adb431f16724c8afdea0c0751588a4bc6f82b6f0b8391d4d189d6a6f4a38`| +| `stdout.txt` |125|Im privaten vollständigen Readback gebunden; Meldung64Bit-Verarbeitung der festen IDL| +| `stderr.txt` |0|Leere tatsächliche Fehlerausgabe| + +Die erzeugten Dateien bleiben unverändert. Der nächste getrennte Build darf +diese tatsächlichen Microsoftoutputs als explizite hashgebundene Inputs +verwenden. Kein Patch bereits erzeugter OUT_DIR-Dateien, keine erfundenen +RPCNDR-Header-Versionen und keine manuell korrigierten NDR-Bytes. Frühere WIDL- +Kandidaten/1783-Berichte bleiben erhalten. + +Dieser Nachweis qualifiziert ausschließlich den Codegeneratorlauf. Noch keine +erfolgreiche Statusabfrage, TrustedClock-Qualifikation, Systemscriptausführung +oder Windows-MVP-Abnahme. Das Produktgate bleibt `ADAPTER_QUALIFIED=false`. diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index fcc4d64..daab764 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -44,7 +44,7 @@ python3 deploy/windows_profile_acceptance.py windows --manifest devstate/windows ``` `--access-root` dient ausschließlich dem streng geparsten bestehenden -SSH-Zugang: Cloud-Linux `116.203.20.85` bzw. der unveränderten gepinnten +SSH-Zugang: Cloud-Linux `` bzw. der unveränderten gepinnten Windows-Reverse-SSH-Kette über Cloud-Loopback22240. Keine Credentialkopien, Symlinks oder Hostkeyänderung. Alle Artefakte und lokalen Belege bleiben im isolierten Profilworktree. Linux läuft mit geleerter Umgebung und eigener diff --git a/docs/windows-recovery-download.md b/docs/windows-recovery-download.md new file mode 100644 index 0000000..38c9e4b --- /dev/null +++ b/docs/windows-recovery-download.md @@ -0,0 +1,68 @@ +# Öffentlicher Recoverydownload — ursprüngliches Paket zurückgezogen + +Historischer erster Veröffentlichungsbeleg. Das Paket wurde wegen eines +unbelegten gerundeten Accountzeit-Guards zurückgezogen; maßgeblich ist der +[Korrekturbeleg](windows-recovery-precision-download.md). Die ursprünglichen +Belege und Archive bleiben erhalten. + +Am2026-11-14 im separaten Fall `7f549bc4-cf12-4292-aae6-377ac9ecb2d4` +über den vorhandenen Bootstrap-TLS-Dienst tatsächlich veröffentlicht und von +außen mit normaler CA-/Namensprüfung vollständig heruntergeladen. Exakte +ZIP-SHA256 `7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7`. +Nur drei öffentliche Dateien: Konsole-PS1, öffentliche Parameter und README; +keine privaten Schlüssel, Tokens oder Zugangspasswörter. + +Feste Downloadfrist **2026-11-14T13:53:24+00:00**. Die neue URL wird nur im +privaten Veröffentlichungsbeleg und der konkreten Benutzeranweisung geführt. +Die alten abgelaufenen Bootstrap-/Repair-URLs bleiben404. Aktuelles Mapping +enthält ausschließlich den neuen zufälligen Pfad zum festen Recoveryzip. +Der vorhandene Dienst auf8443 wurde für diese begrenzte Wiederherstellung +gezielt wieder gestartet; kein Port80/ACME, kein neues Zertifikat und keine +Änderung an RMM-Server, Gateway, Datenbank oder SSH durch diesen Publisher. + +`deploy/windows/publish_recovery_download.py` ist vor der Veröffentlichung +unabhängig geprüft und per Python-AST geprüft, SourceSHA256 +`cf49bc0e78ecf35aae9d56885e6e395d1155398de46cee4f309f58549b436c90`. +Read-onlyPrepare verlangte abgelaufene Konfiguration, inaktiven Dienst, +bekannten ursprünglichen Code sowie gültige Host-/CA-Kette und mindestens eine +weitere Stunde Zertifikatsgültigkeit. Der konkrete Publishintent wurde vor +Mutation per SHA gebunden. Originalcode und Konfiguration sind separat privat +archiviert; nur ein festes Dateinamenliteral wurde ergänzt. Kein freies +Dateiserving und keine Veröffentlichung historischer Pakete. + +Eigener systemd-Close-Timer wurde **vor** Firewallöffnung und Dienststart +aktiviert. Er stoppt zur festen Frist den Downloaddienst und schließt8443. +Der HTTP-Handler verweigert darüber hinaus selbst nach derselben Frist jeden +Download. Die tatsächliche spätere Timerwirkung ist erst dann zu beobachten; +Timeraktivierung und App-Ablaufprüfung sind kein schon ausgeführter Portschluss. +TLS-Schlüssel wurden ausschließlich über den vorhandenen systemd- +Credentialmechanismus genutzt, weder gelesen noch übertragen. + +Getrennter Readback bestätigt den aktiven Downloaddienst, vorhandenen +Abschlussbeleg, KonfigurationsSHA +`1aa119f0355754e2ba054e6e1c4276f484c1287750cb853dd73bffe552ef8f93` +und ServercodeSHA +`b4f85778dd356377b95e04d6736b3fb6f4e272a276a9466f28efeaccd6ef1b7d`. +Danach gespeicherte Zentralzähler gelesen: Windows0/0/0/0, +Linux30/30/26/0, Transporttestflags geschlossen. Keine RMM-Jobs gestartet. + +Der gesonderte Serverteil der Konsolenrecovery ist bereits ausgeführt: +[genauer Quellen-/Abnahmestand](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-pipe-drain/docs/windows-dev-access-recovery.md). +Die Windows-Konsolenphase und der danach notwendige gepinnte SSH-Nachbeleg +stehen weiterhin aus; keine Wiederherstellung allein aus dem Download ableiten. +Content-Disposition des historischen Downloadservers nennt weiterhin +windows-dev-access.zip; die konkrete Benutzeranweisung speichert explizit unter +einem neuen Recoverynamen und prüft vor Ausführung den ZIP-Hash. + + +## Tatsächlicher Rückzug + +Eigener enger Nur-Bootstrap-Controller im Fall +`19f19da3-2b97-451a-a32c-4b968b37e9c5` prüfte vor dem Stopp exakte +Code-/Config-/ZIP-Hashes der ersten Publikation und stoppte ausschließlich den +Downloaddienst. `inactive` bestätigt; ursprüngliche ZIPdatei zunächst erhalten, +keine RMM-Änderung. ControllerSHA256 +`d0c08d92f7f4d748108891eacae7fa1b7dc115877e4c43cdd55cbf1b9612a43a`. +Die spätere korrigierte Publikation archiviert zusätzlich die ursprüngliche ZIP +privat und ersetzt die URLzuordnung. Die alte Benutzerrückfrage wurde ausdrücklich +ersetzt; keine bestätigte Windowsausführung oder Gerätewirkung daraus ableiten. diff --git a/docs/windows-recovery-precision-download.md b/docs/windows-recovery-precision-download.md new file mode 100644 index 0000000..3a70d98 --- /dev/null +++ b/docs/windows-recovery-precision-download.md @@ -0,0 +1,73 @@ +# Recovery: exakte Accountzeit und tatsächlich korrigierter Download + +**Abgeschlossen:** Die ursprünglichen Fehler und Korrekturen unten sind Verlauf. +Nach Alias- und Originalbootstrap-Hashkorrektur meldete der Benutzer +Konsolenerfolg; gepinnter SSH-Readbackbb0e2b47 und vollständige separate +Erhaltungsprüfung490e0180 bestätigten den Zugang. Lokale Accessmetadaten erst +danach per CAS erneuert, keine Schlüsselersetzung. Zweites Downloadpaket nach +Aliasfehler gezielt zurückgezogen. Nach tatsächlicher Ablaufzeit zusätzlich +rein lesend bestätigt (b046e30d): Downloaddienstinactive, Closeaktionsuccess, +kein8443Listener und keine8443Allowregel. Kein weiterer Download erforderlich. +Details: [aktueller Stand](parallel-mvp-status.md). + +Der gerundete alte Account-FILETIME-Wert der ursprünglichen Recoveryquelle war +eine unbelegte Annahme. Ein zusätzlicher Quellencheck fand: Microsofts +[LocalAccounts-SAM-Code](https://github.com/PowerShell/PowerShell/blob/v6.0.0/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs#L2196) +übergibt `DateTime.ToFileTime()` unmittelbar als64Bit. Eine Sekundenrundung ist +in diesem Codepfad nicht enthalten. Der lokale .NET-Roundtrip des ursprünglichen +öffentlichen ISO-Strings ergibt134391345312549990. Dies ist ausdrücklich ein +berechneter Sollwert, **keine gemessene Windows-SAM-Beobachtung**. + +Die neue separat geprüfte Quelle `console_access_precision.py` (Pipebranch, +SHA8b4d14ed…) verändert ausschließlich den Guard und die neue Fallprovenienz: +exakter Sollwert aus der bereits per Hash und ISO-String geprüften alten +Config, `DateTimeOffset.UtcDateTime.ToFileTimeUtc()`, ohne Rundung, Alternative +oder Toleranz. Die frühere Quelle/ZIP und der tatsächliche Server-CAS bleiben +unverändert. Keine weitere Serverexpiryänderung. Windowsausführung durch den +Benutzer noch nicht bestätigt oder nativ nachgewiesen. + +Korrekturfall `5c96d3d8-1657-40c8-a6ec-c00b63a98210`, gleicher vorhandener +Serverlease bis2026-11-15T13:05:58UTC. ZIP-SHA256 +`dbcd5ca863c0b09f89b67eb10eeaeaf89b941bbc5840079f1bb0c36dc6ff3b3e`, +PS1-SHA256 +`4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69`. +Der VM-SAM-Wert bleibt unbekannt; Abweichung verweigert vor irgendeiner Wirkung. +Wenn das vorherige Paket bereits wirkte, verweigert der ursprüngliche Config- +Hash den neuen Lauf ebenfalls. Kein Replay oder Reset alter Fälle. + +## Tatsächliche korrigierte Publikation + +Root veröffentlichte ausschließlich den korrigierten öffentlichen ZIP im Fall +`fb433a8e-a11a-4e3a-a9e7-e066fef66af9`. Neuer Publisher +`deploy/windows/publish_precision_recovery.py`, SHA256 +`efb2b0c2ea2d88dabd16138ce871ab7569bf9a69d84b5d9f70540a200f20f889`: +Python-AST und unabhängiger Quellreview bestanden; echte lesende Vorbereitung +mit exakter zurückgezogener Code-/Config-/ZIP-/inaktiver Dienstgeneration. +Original-ZIP/Config zusätzlich privat archiviert; aktuelle Servercodebytesb4f85778… +bleiben gleich. Nur korrigierter ZIP und Mapping auf genau einen neuen +zufälligen URLpfad; alte URL nicht mehr freigegeben. + +Feste Downloadfrist **2026-11-14T14:17:54UTC**. Eigener neuer Close-Timer vor +Neustart aktiviert, danach ausschließlich der alte zu dieser Publikation +gehörende13:53-Close-Timer deaktiviert. Vorher dessen Service-/Timerbytes exakt +geprüft. Getrennt tatsächlich gelesen: neuer Timer active/enabled, nächsteAuslösung +14:17:54UTC; alter Timer inactive/disabled. Die spätere tatsächliche +Timerwirkung bleibt separat zu beobachten. +Derselbe vorhandene TLS-Bootstrapdienst und8443, keine Änderung an80/ACME, +Zertifikaten/Schlüsseln, SSH-Frist, RMM-Server/Gateway oder Geräten durch diesen +Publisher. Der normale Handler prüft unabhängig zusätzlich die feste Ablaufzeit. + +Extern tatsächlich mit normaler CA-/Namensprüfung heruntergeladen; alle +ZIPbytes stimmen mitdbcd5ca8… überein. Getrennter Readback bestätigt aktiven +Dienst, Abschlussmarker und KonfigurationsSHA256 +`5cea6f899f75a6e21b1f2cdffedb0832650ea0a013d0f08ec08a24efaaa5db3b`. +Die neue Rückfrage enthält genau diesen Download, einen neuen lokalen Dateinamen +und ZIP-SHA-Prüfung vor dem Entpacken/gezielten Entsperren der eigenen PS1-Datei. +Sie ersetzt ausdrücklich die alte Rückfrage; bei bereits erfolgter alter +Ausführung wird zunächst deren tatsächliche Ausgabe benötigt. + +Die Veröffentlichung belegt keine Windows-Konsolenwirkung oder erneuten +SSH-Zugriff. Nach der Userphase bleiben gleicher Hostpin, eigene Recoveryreceipt, +Konfig-/Accountfristen, erhaltene Keys/Taskdefinition und getrennte lokale +Accessmetadatenfortschreibung per CAS zu prüfen. RMM-Job-/Clock-/SYSTEM-Gates +bleiben geschlossen; keine direkte API-/DB-Genehmigung. diff --git a/docs/windows-signed-clock-source.md b/docs/windows-signed-clock-source.md new file mode 100644 index 0000000..eba06c2 --- /dev/null +++ b/docs/windows-signed-clock-source.md @@ -0,0 +1,214 @@ +# Windows: unabhängiger signierter Zeitvergleich, erster Quellenschnitt + +Stand2026-11-14, Spezifikation1.22. Der User hat diese alternative Trustsource +ausdrücklich angenommen; [Vertrag](windows-clock-attestation-proposal.md). +Dieser Schnitt implementiert den unabhängigen Windows-Verifier. Er ersetzt +noch keinen laufenden Agent/Helper und öffnet keine Windows-Jobfähigkeit. + +`crates/agent-windows/src/signed_clock.rs` ist additiv registriert. Sein +installierter Adapter wird ausschließlich unter Windows mit dem vorhandenen +`system-helper`-Feature gebaut; die zwei plattformneutralen Guardtests laufen +auch unter Linux. Die bestehende RPC-Clock und `ADAPTER_QUALIFIED=false` bleiben +unverändert. Kein neuer `SyncClock`, Cache, Netzwerkclient oder Jobpfad. + +## Tatsächliche Bindung und enge API + +Agent und SYSTEM-Helper öffnen jeweils selbst die geschützte bestehende +Helperkonfiguration, prüfen ihre tatsächliche eigene SCM-Prozessgeneration, +Token-/Dienstrolle und gehaltene Imageidentität mit dem vorhandenen PeerProof. +Ein Agent kann die Helperrolle dadurch nicht nur im Request behaupten. +Die vorhandene feste lesende CIM-Bootabfrage läuft unabhängig in jedem Prozess +vor Beginn der Challenge. Ihre potenziell längere Laufzeit wird nicht aus einem +bereits laufenden Einsekundenbudget versteckt. + +Der zusätzliche feste öffentliche Pinpfad ist +`C:\ProgramData\RustDiscoverySystem\time-attestation.json`, maximal16KiB. +Seine Datei und das geschützte Elternverzeichnis werden mit bestehenden +PinnedFiles und restriktiven ACL-/File-ID-/Reparseprüfungen gehalten. +Alle ursprünglichen Helperkonfigurationshandles bleiben ebenfalls erhalten. +Der Pin bindet die exakte bestehende Gerätebindung, Serverinstanz, Zeitkey- +Generation, bis zu acht Publickeys und genau eine Kalibrierungsreferenz je +Agent-/Helperimage. Nur SYSTEM/Administrators schreiben; die beiden +Dienst-SIDs dürfen lesen. Keine Keys aus einer Serverantwort oder Workerdatei. + +Ein anschließender enger Sourcefix verweigert zusätzlich jeden Zeitpublickey, +der nach tatsächlicher Hexdekodierung dem vorhandenen Jobpublickey entspricht. +Abweichende Groß-/Kleinschreibung umgeht die Rollentrennung nicht. Eine neue +gezielte Negativprobe prüft diesen Fall. Dieser Fix ist noch nicht Teil des +unten erhaltenen180-Input-Belegs; seine neue kohärente Qualifikation folgt nach +dem neuen gemeinsamen Agentpfad-/Linuxnachweis im184-Input-Nachtrag unten. + +Die Kalibrierung muss die tatsächliche Binary per SHA256 und einen separat +gewonnenen Qualifikationsbeleg binden. Das positive Grundfehlerbudget liegt +höchstens10ms je Capture. Dies ist **keine gemessene Genauigkeit**: Aktuell +existiert aus diesem Schritt kein bereitgestellter Pin oder Kalibrierungsbeleg. +Ein solches JSON darf nicht mit geratenen Werten als qualifiziert installiert +werden. Der dauerhafte monotone Konfigurationsweg über Prozessneustarts bleibt +vor Runtimeaktivierung gesondert zu provisionieren. Der Loader selbst sperrt +innerhalb desselben Prozesses niedrigere Generationen und unterschiedliche +Rawbytes bei gleicher Generation; er erzeugt kein neues Floorjournal. + +Eine zufällige Prozessinkarnation sowie ein prozessweit gehaltener Continuity- +Head bleiben unabhängig von Objektkonstruktoren erhalten. Höchstens eine +Challenge ist pro Prozess offen. Bootwechsel, rückwärts laufende Zähler, +Wallstep oder Schlafdifferenz über1s verwerfen sie. Überlauf erschöpft den Head +dauerhaft; ein weiterer Aufruf öffnet ihn nicht wieder. Erst eine neu erzeugte +Challenge nach einer beobachteten Diskontinuität ist verwendbar. + +Im anschließenden Reviewfix hält derselbe globale Head auch die höchste +Verbindungsgeneration: Ein neues Adapterobjekt mit höherer Generation +invalidiert alte offene Challenges, alte Objekte können keine neue Anfrage +unter ihrer niedrigeren Generation eröffnen. Ein Generationwechsel am +vorhandenen `begin` schließt dessen eigene alte Anfrage. Die gezielte +Continuityprobe ergänzt diese Negativfälle; auch dieser Fix gehört zum +folgenden neuen Quellenbeleg, nicht zum ursprünglichen180-Input-Snapshot. + +Der native Capture umfasst präzise Interruptzeit, Unbiasedzeit, Wallclock, +nochmals Unbiasedzeit und Interruptzeit. Beide präzisen Interruptgetter sind +gemäß Microsoft **VOID**-APIs; kein fingierter BOOL-Erfolg und keine optionale +Fallbackquelle. Zeitwerte sind100ns-Einheiten. Der gesamte gemessene Bracket +wird zusätzlich zum ausdrücklich qualifizierten Grundfehler konservativ +berechnet. Auflösung wird nicht mit Genauigkeit gleichgesetzt. +[Präzise Unbiasedzeit](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttimeprecise), +[präzise Interruptzeit](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise). + +`begin` liefert ausschließlich den gebundenen Transportrequest und hält die +opaque Challenge selbst. `complete(bytes, callback)` nimmt nur begrenzte +Antwortbytes entgegen, keine fremden Zeiten. Der Adapter erfasst Empfang +selbst vor dem JSON-Decode und die Schlussmessung nach der vollständigen +Signaturprüfung. Der gemeinsame Codec prüft Signatur, Originalrequest und +Kontext, vollen RTT,100ms-Empfangsalter und die ganze UTCspanne. Am Ende müssen +auch prozessweiter Owner und Epoch noch identisch sein. + +Nur der unmittelbar aufgerufene Callback erhält eine geliehene Comparison mit +der geprüften Spanne und der tatsächlich selbst beobachteten Windows-Wallclock. +Keine gespeicherte Comparison, kein Midpoint als angebliche lokale Uhr, keine +automatische neue Challenge nach einem Fehler. Abschluss/Abbruch konsumiert die +ursprüngliche Anfrage. Runtimeintegration muss diese API an ihre tatsächlichen +Start-/Syncgrenzen binden; sie wird hier nicht durch einen scalar `now()`-Stub +vorgetäuscht. Die bestehenden zusätzlichen Job-/WebUI-/Ledgergates bleiben nötig. + +## Tatsächlich lokal geprüft + +Eingefrorener Sourcefall30bb330a-d285-4d15-ab8d-8ce36a760524,180 Inputs; +Inputmanifest SHA256 +`7f56d21680a1345f514ac98fd187a3bea376414215ba1d5773f682690a8ae214`. +Windowsmodul SHA256 +`f1fed304ebda3f48f38aba38f8ad5e1811c566abd740dffce318f4b07beac3ca`. +Receipt SHA256 +`ad5e35ac1c63f0cbc8e3559c338b183ca5793e7219543a9f43794cc75542402b`. +Der vollständige private Snapshot und Logs bleiben unter gitignoriertem +`devstate/windows-signed-clock/qualification-30bb330a-d285-4d15-ab8d-8ce36a760524/`. + +Tatsächlich bestanden, ausschließlich Offline-Docker auf dem Entwicklungsrechner: + +- Zwei gezielte Linux-Guardtests: Bracketbudget/Counterfehler sowie erhaltener + Prozessfence, Bootsubstitution, Generation/Fork und erschöpfter Epochcounter. + 2bestanden,0failed/ignored;10 übrige Cratetests ausdrücklich herausgefiltert. +- Windows-GNU-Alltargetscheck sowie Clippy mit `-D warnings` für den + `system-helper`-Build. Erster Clippylauf verweigerte drei verschachtelte + if-Blöcke; diese wurden ohne Unterdrückung korrigiert und erneut geprüft. +- Windows-Lib-Testbinary tatsächlich gelinkt,75326709Byte, SHA256 + `29c037f6ca13fc91806312a16dde0923fcaa1d5a0d16d057362bf112f3875da6`. + **Nicht auf Windows ausgeführt**, kein nativer Testcount daraus abgeleitet. +- Formatcheck ausschließlich der neuen Moduldatei bestanden. + +Die relevanten Cargoaufrufe benutzen `--locked --offline`; Linux-Testfilter +`signed_clock::tests`, Windows `--target x86_64-pc-windows-gnu --features +system-helper --all-targets`. Das Linken verwendet `test --lib --no-run`. +Der eingefrorene gemeinsame Codec enthält zu diesem Zeitpunkt noch die alte +`/api/agent/v1/time-attestation`-Audience. Der geplante korrekte Agentpfad +`/agent/v1/time-attestation` benötigt einen neuen gemeinsamen Quellenbeleg; +dieser ursprüngliche Snapshot wird dafür nicht verändert. + +## Offene reale Nachweise + +Keine Cloud-Linux-Ausführung dieser beiden neuen Guardtests und keine native +Windowsausführung in diesem Schritt. Keine tatsächliche Timerkalibrierung, +Pinprovisionierung, Serverantwort im echten Geräte-mTLS-Kontext oder parallele +Agent-/SYSTEM-Roundtrips. Keine Runtime-/IPC-/HTTP-Anbindung und keine Wirkung. +Der Servercodec besitzt eigene getrennte Nachweise; diese qualifizieren nicht +automatisch den Windowsadapter. Zuerst Linux-first, dann unabhängig auf dem +Windowsgast prüfen. Erst danach kann eine gesonderte WebUI-genehmigte +Windows-Skript-/SYSTEM-Abnahme folgen. W32Time-Konfiguration, Dienste, +Geräteidentitäten, PKI und Journale wurden durch diese lokale Arbeit nicht +angefasst. + +## Aktueller kohärenter Nachtrag nach URI- und Reviewfix + +Der neue separate Fall763baf69-10b1-4307-9c99-6942c0f8945f bindet184 Inputs +einschließlich des gemeinsamen Codecs mit der korrigierten Audience +`/agent/v1/time-attestation`. Der ursprüngliche180-Input-Snapshot bleibt +unverändert. Der unabhängige Source-Review von updater_review meldete für das +aktuelle Windowsmodul PASS; dies ist ausdrücklich kein nativer Rollennachweis. + +Aktuelles Modul SHA256 +`6b66612b7a53377c91bc8e41864ac8fb9393ad40b0a6a98aa6ce746fce091ddb`, +Inputmanifest SHA256 +`eb4609c5fca6a32ddb8ebf364775efdb59cd89f99a24b3b731212da08eac6a6e`, +Receipt SHA256 +`e013738caed2d8e02b98ffd1b41e47a80840c44d3dbf895e9a3952b4311ce927`. +Private Belege: +`devstate/windows-signed-clock/qualification-763baf69-10b1-4307-9c99-6942c0f8945f/`. + +Tatsächlich lokal auf den eingefrorenen Bytes bestanden: + +- Release-Linux-Testbinary gebaut und dessen vollständige Liste von13 Tests + und0 Benchmarks geprüft. Nur die drei neuen `signed_clock::tests` ausgeführt: + **3bestanden,0failed/ignored,10 übrige Tests ausdrücklich herausgefiltert**. + Hinzugekommen ist die konkrete Job-/Zeitkey-Rollentrennung auch bei anderer + Hexschreibweise; der Fencetest prüft nun auch den Connectionhead. +- Windows-GNU-Alltargetscheck und Alltargets-Clippy mit `-D warnings` bestanden. +- Windows-Lib-Testbinary aus genau denselben184 Inputs tatsächlich gelinkt. +- Formatcheck der neuen Moduldatei bestanden; keine Unterdrückungen ergänzt. + +Der erste Windows-Linkversuch dieses Falls scheiterte ausschließlich lokal am +Schreibschutz der früher qualifizierten Testexe im wiederverwendeten Target. +Der frühere Pfad und SHA29c037f6 blieben erhalten. Der unveränderte neue +Sourcesnapshot wurde danach in einem neuen eigenen Windowstarget erfolgreich +gelinkt; der ursprüngliche Fehlerbericht bleibt101 und wird nicht überschrieben. +Keine Lockerung des Readers oder der alten Artefaktrechte. + +Die qualifizierte neue Linuxexe hat3374576Byte, SHA256 +`0896a3098f493b67b48e774de5cfe9bca682d2a19ff10971c62c9c7b9681ec14`. +Der Native-Operator muss zunächst exakt die vollständige13er-Liste verlangen +und anschließend ausschließlich die drei neuen Namen auswählen; kein erneutes +Ausführen der zehn alten Fälle oder Verschweigen ihrer Filterung. Dies ist der +vorbereitete Linux-first-Nachweis, **hier durch diesen Worker nicht auf der +Cloud-VM ausgeführt**. + +Die neue Windows-Testexe hat75360791Byte, SHA256 +`3421368eff990d197889da58aa09463e00eff40e1cfebfcfdf1e9b9382e10f03`. +Sie wurde hier nicht auf Windows ausgeführt. Bauen, Linken und Source-Review +eröffnen weiterhin keine Capability. Sämtliche zuvor genannten tatsächlichen +Timer-, Rollen-, Provisionierungs-, Transport- und Runtimegates bleiben offen. + + +## Tatsächlicher Linux-first-Nachweis der drei Guards + +Root führte den unabhängig geprüften Runner +`deploy/windows_signed_clock_linux_acceptance.py`, SHA256 +`70b029a441d27814f646a75cfb69ff9e5af356776027a7f836a252964a29aafd`, +im Originalfall `6ea36dec-254e-4a82-8d1c-c72a1f959ed2` auf der Cloud-Linux-VM +aus: **3bestanden,0ignored,10andere Tests gefiltert, Exit0**. +Die vollständige13er-Liste musste zuvor exakt stimmen. Separater lesender +Originalfall-Readback vollständig; bekannte drei RMM-Prozessgenerationen, +Kontrollbytes, Boot und DB-/Lock-Dateiidentitäten erhalten. Kein RMM-Job, +Produktzeitquery oder Dienststeuerung; Full weiter Autostart disabled. + +Tatsächlich prepare, einmal execute und read mit obigem Originalfall ausgeführt. +FallmanifestSHA256 +`cc83d7bc455dfaa2e0c7b0305b5713452a74ad0b60730c6058132a761aa5f157`; +ExecuteSHA256 +`0a86c11133bce801c86d3af8bd7e1eadfeacdf49456f4ae17291e7281b8ade1f`; +ReadbackSHA256 +`81138562175bf71bc14c0f5cf9ddc37b434c8d7751196b12c90140db5c29e9f1`. +Private184Inputs und ursprüngliche Qualifikationsbelege bleiben unverändert. + +Der veröffentlichte erste Modulstand entspricht exakt6b66612b. Die +`lib.rs`-Modulregistrierung wurde danach ausschließlich alphabetisch gemäß +rustfmt geordnet; die ursprünglichen Compilerinputs werden dadurch nicht +nachträglich geändert. Kein erneuter Semantiktest für diese reine Formatierung. +Nachfolgende Rohcapture-/Runtimeänderungen sind eigene Quellenstände und +werden durch diesen nativen Dreierbeleg nicht mitqualifiziert. Native Windows- +Timer und tatsächliche Zeitquelle bleiben weiter offen; Legacyclock bleibt zu. diff --git a/docs/windows-system-delegation-upgrade.md b/docs/windows-system-delegation-upgrade.md index c1049ab..fcb60bd 100644 --- a/docs/windows-system-delegation-upgrade.md +++ b/docs/windows-system-delegation-upgrade.md @@ -1,7 +1,8 @@ # Gemeinsames passives Windows-Komponentenupgrade -Stand 2026-11-14: **Source vorbereitet; dieser Upgradefall wurde noch nicht auf -der VM ausgeführt.** Lokale Guards und PowerShell-Parserprüfung ersetzen weder +Stand 2026-11-14: **Passive Wartung nach separat dokumentiertem ersten APIfehler und +enger Recovery abgeschlossen. Positive Pipeabnahme weiterhin fehlgeschlagen.** +Lokale Guards und PowerShell-Parserprüfung ersetzen weder die neuen nativen Unitnachweise noch den tatsächlichen Erhaltungs-/Pipebeleg. Der Notebookhost bleibt ausschließlich Entwicklungsrechner. @@ -72,10 +73,78 @@ Runtimeindex per lokalem CAS um einen neuen Komponentenbeleg ergänzt. Ein noch fehlgeschlagener Pipebeleg bleibt ausdrücklich fehlgeschlagen; ein erfolgreiches passives Komponentenupgrade behauptet keine Jobfähigkeit. -Geplante Befehle, **nicht ausgeführt**: +Aufrufvorlagen; tatsächlichen Fallstand unten beachten: ```text python3 deploy/windows/system_delegation_upgrade.py upgrade-passive --manifest --qualification python3 deploy/windows/system_delegation_upgrade.py readback --id python3 deploy/windows/system_delegation_upgrade.py finish --id ``` + +## Tatsächlicher Fall6d2df065: erster Dateiaufruf fehlgeschlagen + +Originalfall `6d2df065-0877-41c4-983c-2c9fdb6e5437` scheiterte zunächst vor dem +Server-Beforecheckpoint. Nach wiederhergestelltem gepinntem SSH-Zugang wurden +fehlender entfernter Fall/Activeintent und unveränderte Originalprozesse separat +lesend bestätigt. Ein zusätzlicher dauerhafter Fortsetzungsintent führte +ausschließlich die erste zuvor nicht erreichte Phase desselben Falls aus. +Originale Fehlermeldung und Quellen blieben erhalten, kein neuer Enrollment- +oder RMM-Jobkontext. + +Native Stopps beider eigenen Dienste bestanden. Frozenbeleg und sämtliche vier +privaten Originalbackups wurden gespeichert. Beim ersten Dateitausch meldete +`[IO.File]::Replace($candidate,$destination,$null)` eine ArgumentException. +Sofortiger gesonderter Readback: Agent/HelperStopped, vier Zielhashesoriginal, +keine Replaced-/Swapped-/Startmarker. Eine weitere Nur-Leseprüfung bestätigt +Frozen-DBbytes, Zeilen, tatsächliche Dateiidentitäten und PKI-Metadaten erhalten. +Nur der erste Agentcandidate (exakter neuer Hash) und sein ursprünglicher +Replaceversuchsmarker existieren; andere Candidates/Replaceversuche fehlen. + +Eigene native Einbyte-API-Fixture `45a21a07-a115-47ec-93e1-694aa519520a`: +Nullbackupaufruf reproduziert ArgumentException, Quelle/Destination unverändert; +separater Aufruf mit explizitem Backup schreibt erwartete Destination und +Originalbackup. Keine Runtime-Datei wurde durch diese Fixture berührt. Die +genauere interne PowerShell-/Framework-Konvertierungsursache wird daraus nicht +als bewiesen behauptet. + +Der ursprüngliche Enter wird nicht erneut ausgeführt, Originalmarker und +Quellen nicht geändert. Eine separate create-only Recovery muss vor jeder +Fortsetzung diesen konkreten Vier-Dateien-/Frozen-/Nichtstartzustand bestätigen, +den existierenden ersten Candidate hashgeprüft erhalten und einen ausdrücklich +benannten zusätzlichen Nativebackup verwenden. Erst nach allen vier neuen +Datei-/ACL-/Frozenbelegen dürfen die bisher noch nicht versuchten eigenen +Helper-/Agentstarts folgen. Kein automatischer Retry oder Rücksetzen. + +## Tatsächliche enge Recovery und Abschluss + +Neue Quelle `deploy/windows/system_delegation_recovery.py`, SHA `64ced170…`, +Script `65e480f2…`, unabhängig geprüft und lokal Python-/PS-AST geprüft. Originale +Quelle `f8dc1c8f…` unverändert. Recoveryfall +`595dd1da-0d7f-4364-9040-a75e16c6da83` bestätigte separat den vollständigen +Stopped-/Frozen-/Datei-ID-/Candidatekontext und führte einmal vier Tausche mit +expliziten zusätzlichen Nativebackups durch. Alle vier neuen Dateien, ACLs und +Frozen-Datenbanken wurden vor dem ersten Start geprüft. Anschließend Helper, +danach Agent jeweils einmal gestartet; getrenntes Readback bindet dieselben +Phasen. Originalmarker und erste ArgumentException bleiben erhalten. + +Originales `finish` war danach ausschließlich lesend: zwei frische WSS- +Heartbeats, konkretes Inventar-ACK/fortgeschrittene Sequenz, gleicher Tenant/ +Geräteidentität und fremder Tenant verweigert. Journale/Dateiidentitäten/Zeilen, +Konfiguration und PKI-Metadaten erhalten. ZählerWindows0/0/0/0, Linux30/30/26/0 +und geschlossene Flags/Rootpolicy unverändert. Runtime-/Komponentenindex erst +nach diesen Belegen lokal per CAS veröffentlicht. Kein OS-Reboot, kein Job, +kein Binding oder neuer Clock-/Wirkungsgate; Intentdateien weiter0Byte. + +Tatsächlicher Agent `89004ad3…`, LocalService/Auto, PID8108, Geburtswert +`134391259111815072`; Helper `e6aacbdd…`, SYSTEM/Manual, PID2620, Geburtswert +`134391259068713651`. Policy `007adf5f…`, reziproker Pin `126670bc…`. +Privater Originalabschluss `result.json` SHA256 +`ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460`; +Recoveryabschluss `acceptance.json` SHA256 +`5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb`. + +Die positive Pipeprobe bleibt ausdrücklich fehlgeschlagen: tatsächlicher neuer +Agent meldet `client_read_reply`/`HELPER_PIPE_IO`, Win32233, kein authentisierter +Austausch und kein privater Helperdiagnosebeleg. Dies ist ein erfolgreicher +passiver Erhaltungs-/Wartungsnachweis, kein SYSTEM-Sync-/Job-/Clocknachweis. +Kein erneutes Enter oder Wiederverwenden der ursprünglichen Startbefehle. diff --git a/docs/windows-system-pipe-drain.md b/docs/windows-system-pipe-drain.md new file mode 100644 index 0000000..d5c315a --- /dev/null +++ b/docs/windows-system-pipe-drain.md @@ -0,0 +1,53 @@ +# Windows-Pipe v2: tatsächlicher Unitnachweis + +Dieser Ergebnisnachtrag ergänzt den unveränderten, im Buildmanifest gebundenen +[Framing-/Drain-Entwurf](windows-helper-pipe-drain.md). Der Entwurf bleibt als +historischer Quellenstand erhalten; dieser Nachtrag verändert weder seinen Hash +noch das ursprüngliche Manifest. + +## Tatsächlich auf Windows bestanden + +Root führte im eigenen nativen Fall +`db25cd4a-bfd2-45d5-9f80-1881950853f7` die beiden konkreten Testprogramme des +Pipe-v2-Packs aus. Beide vollständigen nativen Listen wurden vor irgendeinem +Unitfall exakt geprüft. Alle23 Libraryfälle und alle7 Binaryfälle bestanden; +kein Fall war fehlgeschlagen, ignoriert oder gefiltert. Beide Listenprozesse +und beide Testprozesse endeten mit Exit0 ohne Timeout. Die gemeldete Testdauer +betrug2,76s für die Library und0,07s für das Binary. + +| Gebundener Beleg | SHA256 | +| --- | --- | +| Neues Pipe-v2-Buildmanifest | `b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4` | +| Tatsächlicher Native-PASS | `19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713` | +| Begrenzter Unitrunner | `2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf` | +| Library-Lieferdatei | `3fc2b7314d755f5c5235c8383cf605cbe848180180497bb30540482f4910c2a1` | +| Binary-Lieferdatei | `a3b8f44e87df7af54f82c1d052753217e9a03c495fb28c8a16ba9fe7e1a0af23` | + +Geschützter nativer Beleg im isolierten Pipeworktree: +`devstate/windows-client/native-pipe-v2/db25cd4a-bfd2-45d5-9f80-1881950853f7/passed.json`. +Das zugehörige unveränderliche Buildmanifest liegt unter +`devstate/windows-pipe-drain-build/build-59623db2-15ca-40cd-8728-861f84b2a550/manifest.json`. +Die vorherige Manifestgeneration `928841e7…`, ihre Links und sämtliche früheren +Belege bleiben erhalten. + +## Was dieser PASS belegt + +Die vorhandenen IPC-Codec-/Sicherheits-/Journal-/Runtimefälle liefen tatsächlich +auf Windows als Bootstrapadministrator. Der Beleg weist `no_jobs=true` aus. +Der Unitrunner begrenzt nach einem Timeout die Wartezeit auf das eigene +Testprozessende und auf beide Ausgabe-Tasks; eine verlorene Antwort erlaubt nur +den create-only gespeicherten Fall zu lesen. Das ist keine Änderung des +Produktjob- oder Installerabbruchs. + +`local_service_proof`, `native_pipe_proof` und `clock_adapter_qualified` sind im +Native-PASS ausdrücklich weiterhin `false`. Dieser Unitlauf ist kein +Produkt-LocalService-zu-SYSTEM-Austausch, kein Nachweis, dass Drain v2 die zuvor +beobachtete233-Störung tatsächlich behebt, und keine SYSTEM-/Clock-/Jobfreigabe. +Der bestehende rohe V1-Control ist kein V2-Peernegativnachweis. + +Der erhaltende Paarupgrade, die Bindung an den nach dem Konsolenneustart +vorhandenen tatsächlichen Prozesskontext und der anschließende reale +Agent/Helper-Austausch bleiben gesondert zu prüfen. Vor dessen Ausführung stehen +noch der unabhängige fokussierte Quellreview des neuen Upgrade-Runners und die +explizite Root-Zielaktion. Keine Paket-, SCM-Fixture-, Reboot- oder sonstige +RMM-Wirkung folgt aus dieser Unitabnahme. diff --git a/docs/windows-system-pipe-upgrade.md b/docs/windows-system-pipe-upgrade.md new file mode 100644 index 0000000..ca3207f --- /dev/null +++ b/docs/windows-system-pipe-upgrade.md @@ -0,0 +1,148 @@ +# Windows Pipe-v2: erhaltender Paarupgrade nativ bestanden + +Stand: 2026-11-14. Paarupgrade und tatsächlicher authentisierter Austausch des +laufenden LocalService-Agenten mit seinem SYSTEM-Helper sind bestanden. +Die ursprünglichen Vorbereitungsabschnitte unten bleiben Verlauf. RMM-Jobs, +TrustedClock und Helperwirkungen bleiben weiterhin gesperrt. + +Die ursprüngliche quellengebundene +[Framingdokumentation](windows-helper-pipe-drain.md) bleibt unverändert. Diese +separate Datei beschreibt ausschließlich die späteren Upgradevorbereitungen. +Der Notebookhost bleibt reiner Entwicklungsrechner; Ziel ist die eigene +Windows-VM am endgültigen Cloudserver. + +## Geprüfter Kandidat und begrenzter Bootstrapvertrag + +Der neue Runner +[`system_pipe_upgrade.py`](../deploy/windows/system_pipe_upgrade.py) ist mit +SHA `e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0` +eingefroren. Sein frischer isolierter Prüfer bindet den neuen Pipe-Packtyp und +dessen Originalquellen, genaue native Listen mit **23 Library- und 7 +Binarytests** sowie die erhaltenen Linux-first-Corebelege mit 80 Linux- und +58 Windowsfällen. Es gibt keine Umbenennung alter Delegationsmanifeste und +keine Umleitung des eigenen Source-Roots auf Main. + +Der gebundene Pipe-Pack hat Manifest-SHA +`b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4`. +Die tatsächlichen 23+7 Windows-Administratorunits bestanden im Fall +`db25cd4a-bfd2-45d5-9f80-1881950853f7`; dessen `passed.json` hat SHA +`19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713`. +Das sind Unitnachweise, kein LocalService-/Pipe-/Clock-Erfolgsbeleg. + +Die vorbereitete Mutation verlangt eine separat geprüfte frische Baseline mit +SCM-/Kernel-PID und tatsächlicher Prozessgeburt, Konto, aktivem Service-SID, +Imagehash und ACLs. Ein bereits gestoppter Manual-Helper erhält keinen +Vorabstart. Vor der ersten Ersetzung werden vier private Sicherungen erstellt; +jede Ersetzung verlangt zusätzlich einen eigenen zuvor fehlenden nativen +Backupnamen und frische Datei-ID-/Hash-/ACL-CAS-Prüfungen. Beide Dienste bleiben +bis zur vollständigen neuen EXE-/Policy-/Pingeneration gestoppt. Danach sind +Helper- und Agentstart jeweils create-once. Config-/CA-/Identitäts-/Zertifikats- +und Private-Key-Metadaten samt Datei-IDs werden auch nach den Ersetzungen, +vor dem Start und beim Finish unverändert verlangt. + +`readback` ist rein lesend und kann auch einen fehlenden Zielpfad sowie einen +SCM-Pendingzustand ehrlich zeigen. Baseline, Enter und Finish behalten ihre +strengen Identitätsprüfungen. Nach verlorener Mutationsantwort gibt es keinen +automatischen Enter-/Start-/Rollbackretry. Ein Finish benötigt neue passive +Heartbeats und konkrete Inventar-ACKs; es schreibt nur einen lokalen Beleg. +Main-Indizes werden ausschließlich durch Root separat per CAS fortgeschrieben. + +## Tatsächlicher Fall 14fb: Timeout und geprüfte erste Fortsetzung + +Fallverzeichnis: +`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`. +Der erste `prepare`-Aufruf begann am `2026-11-14T12:39:48.414511+00:00` +und endete nach 180 Sekunden mit `TimeoutExpired` während des ersten +Stagingaufrufs. Zu diesem Zeitpunkt gab es lokal nur den Prepareintent und +Quellkopien, keine Baseline und keinen Enterintent. Die genaue Ursache des +SSH-/Bootstraptimeouts ist nicht nachgewiesen. + +Ein danach gesondert ausgeführter lesender Check bestätigte: beide neuen +EXE-Stagingverzeichnisse, der neue entfernte Komponentenfall und der neue +Active-Marker waren noch nicht vorhanden. Der alte Agent lief, der alte Helper +war gestoppt. Auf dieser Abwesenheit beruhte die explizite create-once +Fortsetzung der tatsächlich noch unerreichten Vorbereitungsphase im selben +Fall; kein neuer Upgradefall und kein wiederholtes Enter. + +| Erhaltener Beleg | SHA-256 | +| --- | --- | +| `prepare-first-stage-timeout.json` | `535faf7c6c4c7b3dba1f8d7b7889bc59acdee09fd51c2830fe397c3c9076f1e9` | +| `first-prepare-readonly-absence.json` | `983b38fcc2cdc8e907436eb3053f32ad2cd131e765a82dd1e9930346e1c6877b` | +| Private Fortsetzungsquelle `continue-first-prepare.py` | `86453aef4a1d59f73e423993b548e58ad0541205961a5952c80807403881cf3b` | +| `continue-first-prepare-intent.json` | `7420622b7866e7b43b34087d5334599444a046b95a89e7f48503aca0f4e03be0` | +| Neue lesende `baseline.json` | `57b79e9c918df6165cac0bb451b33fcd0c207933f15351afcd2ad6c400f4e2d7` | + +Die Fortsetzung erzeugte schließlich den Baseline-/Intentbeleg und die +serverseitigen Vorherbeobachtungen. Das ursprüngliche Timeout und seine +Abwesenheitsmessung wurden nicht überschrieben. + +## Baseline und verbleibende tatsächliche Abnahme + +Die frische Baseline zeigt den weiterhin vorhandenen Agenten `89004ad3…` +unter LocalService (`S-1-5-19`), `Running/Auto`, PID `3172`, mit exakter +Kernel-FILETIME `134391328200102621`. Der vorhandene Helper `e6aacbdd…` +ist `Stopped/Manual`, PID `0`; dafür wird kein laufender Prozess behauptet. +Policy `007adf5f…` und Pin `126670bc…` gehören weiterhin zur alten Generation. +Die Telemetriedatenbank wurde lesend mit `integrity=ok`, Sequenz `2564` und +`pending_inventory_events=0` beobachtet. Ursprüngliche PKI-/DB-/Lock-Datei-IDs, +ACLs und die beiden uninitialisierten Nullbyte-Intentleaves sind im privaten +Baselinebeleg gebunden. + +Vorherige Serverzählungen blieben: +Windows `jobs/outbox/permits/unresolved = 0/0/0/0`, Linux +`30/30/26/0`. Die beobachteten API-/Gateway-Transportfaultflags waren geschlossen; +dies ist eine konkrete Vorhermessung, kein künftiger Nachherbeleg. + +Der vorbereitete Kandidat umfasst Agent `f10c78dd…`, Helper `5f8c62fa…`, +Policy `a3024467…` und Pin `af518db8…`. **Es existiert für diesen Fall noch kein +Enterintent oder tatsächlicher Stop-/Swap-/Start-/Finishbeleg.** Staging ist +keine Installation oder laufende Nutzung der neuen EXEs. Der alte SSH-Zugang +lief anschließend aus; seine getrennte +[Konsolenwiederherstellung](windows-dev-access-recovery.md) ist eine notwendige +Zugangsstrecke und kein Paarupgrade. + +Nach tatsächlicher Wiederherstellung des Zugangs muss Root die Baseline vor +Mutation erneut bewerten. Geänderte PID/Birth-, Datei-, Index- oder andere +gebundene Werte dürfen nicht still übernommen werden. Erst danach können der +einmalige erhaltende Paarupgrade, zwei neue tatsächliche WSS-Heartbeats, +Inventar-ACK, Tenantverweigerung und unveränderte Job-/Policygrenzen geprüft +werden. Ein tatsächlicher authentisierter Austausch des laufenden +LocalService-Agenten mit dem neuen SYSTEM-Helper bleibt offen. Jobfreigabe, +Helperwirkungen und Clockqualifikation bleiben geschlossen. + +## Tatsächlicher Abschluss im selben Fall + +Nach der getrennt verifizierten SSH-Zugangswiederherstellung wurde derselbe +Fall14fb genau einmal betreten. Die frische CAS-Prüfung bestätigte vor der +Mutation die unveränderte ursprüngliche Baseline, beide lokalen Runtimeindizes +und die geschlossenen Serverzähler/Policies. Der bereits gestoppte Helper +wurde nicht vorab gestartet. Beide Dienste blieben während aller vier +Dateiersetzungen gestoppt; Originale und native Backups sind erhalten. + +Das anschließende rein lesende Finish bestätigt: + +- Agent `f10c78dd738e7fb277e0c4d24fadf0f61ae3269458399b9224570ba5e66abc2c` + läuft als LocalService/Auto, PID5528, Geburt `134391415551175930`. +- Helper `5f8c62fab6bc8ea1bbb009166b3d0e741c034c36690a4e32ea4e3cb2d7729a79` + läuft als SYSTEM/Manual, PID9464, Geburt `134391415512591188`. +- Tatsächliche Agentprobe: `authenticated_pipe_exchange=true` und + `client_service_pid_verified_by_helper=true`; Helperkonto/Service-SID und + feste EXE-/Policybindungen geprüft. Der frühere Win32233-Lauf bleibt + fehlgeschlagen; daraus wird keine rückwirkend bewiesene Fehlerursache. +- Zwei neue WSS-Heartbeats, ursprüngliche mTLS-Geräteidentität, + Inventar-ACK/Sequenz2813 und Tenantverweigerung bestätigt. Agent-/Helper- + DB-/Lock-/PKI-Datei-IDs, Historie und leere Intentleaves erhalten. +- Windows0/0/0/0, Linux30/30/26/0, geschlossene Testflags/Policies, + `helper_ready=false`, `helper_clock_qualified=false`, keine SYSTEMcapability + und keine Jobs oder Wirkung. Private Schlüssel wurden nicht gelesen. + +Originaler `result.json`-SHA256: +`d5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed`. +Er wurde samt Intent/Baseline bytegleich im privaten Main-Evidenzpfad +archiviert. Erst danach veröffentlichte Root lokal beide Indizes per CAS unter +einem gemeinsamen Lock, mit erhaltenen Vorgängerdateien und eigener +Publikationsreceipt. Keine erneute Zielmutation: +Runtimeindex `e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2`, +Komponentenindex `005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562`. +Der Nachweis qualifiziert den Pipe-v2-Peertransport und die passive Erhaltung, +keine Clock, SYSTEM-Skriptkonsole oder Paketwirkung. diff --git a/docs/windows-time-service-start.md b/docs/windows-time-service-start.md new file mode 100644 index 0000000..f04dfd7 --- /dev/null +++ b/docs/windows-time-service-start.md @@ -0,0 +1,75 @@ +# Einmaliger Start des vorhandenen Windows-Zeitdiensts + +Stand 2026-11-14: [Bootstrapquelle](../deploy/windows/time_service_start.py) +implementiert, unabhängig quellgeprüft, Python-Syntax und PowerShell-AST lokal +bestanden. **Einmaliger nativer Start und separater Readback bestanden.** +Der Nutzer hat den Start des vorhandenen +W32Time ausdrücklich erlaubt. Die Ausführung übernimmt der Root-Orchestrator +nach Quellenprüfung auf der Windows-VM; das Notebook bleibt Entwicklungsrechner. + +Der einzige Dienstbefehl ist `Start-Service -Name W32Time`. Startart, +Dienstkonto, Imagepfad, Dienst-SDDL, SID-Typ, NTP-Konfiguration und Richtlinien +werden nicht geschrieben. Für einen gestoppten Dienst müssen außerdem null +Dienstabhängigkeiten vorliegen; sonst erfolgt kein Start. Pending-/unbekannte +Zustände blockieren. Ein bereits laufender Dienst wird nur als +`already_running` dokumentiert. Es gibt keinen Resyncbefehl, kein Policyupdate, +keinen RMM-Job und keinen Reboot. Ein natürlicher Zeitsync durch den gestarteten +Dienst ist erlaubt, aber **kein Nachweis einer qualifizierten Uhr**. + +`prepare` verlangt die fünf unabhängig bekannten SHA256-Werte für Agent, +Helper, Agentkonfiguration, Helperkonfiguration und Agentpin. Es legt einen +privaten lokalen Fall an, bindet den bereits gespeicherten zentralen +Beforekontext `time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973`, +überträgt ausschließlich die feste, hashgeprüfte Bootstrapquelle und liest +den tatsächlichen Ausgangszustand. Der Start verwendet diese Originalpins und +diesen Fall unverändert. RMM-PIDs, Prozessentstehung, Dienstdefinitionen, +Binaryhashes sowie Konfigurations-/PKI-Metadaten müssen erhalten bleiben. +Der private Geräteschlüssel wird nur über Dateimetadaten und ACL-Hash geprüft; +seine Bytes werden nicht gelesen oder exportiert. + +Die Registryprüfung hasht nur ausdrücklich aufgeführte stabile Dienst-, NTP- +und Policy-Konfigurationswerte. Sie gibt keine Rohwerte/NTP-Hostnamen aus. +Volatile LastSync-/Laufzeitwerte werden nicht als unveränderlich vorausgesetzt; +der Hash behauptet keine vollständige Abdeckung sämtlicher Registrywerte. +W32Time-Status und dessen PID dürfen sich durch den erlaubten Start ändern. + +Vor dem einzigen Startaufruf werden ein privater Originalbeleg und zwei +dauerhafte, ausschließlich neu anlegbare Startreservierungen gespeichert: +im Fallverzeichnis und als globaler W32Time-Einmalbeleg. Auch lokal entsteht +vor dem SSH-Aufruf ein ausschließlich neu anlegbarer Startversuchsbeleg. +Eine verlorene Antwort, ein Fehler oder ein unvollständiger Beleg erlaubt nur +`readback --id ORIGINALFALL`; weder Startwiederholung noch automatischer +Rollback sind implementiert. Readback meldet den tatsächlichen aktuellen +Zustand und bewahrt unbestätigte Ergebnisse als solche. Frühere private +SSH-Fehler werden vor/nach Aufrufen versioniert erhalten. + +Die folgenden Befehle sind **Aufrufvorlagen**; die Hashplatzhalter +müssen aus dem unabhängig bekannten aktuellen Deployment stammen: + +```text +python3 deploy/windows/time_service_start.py prepare --agent-sha256 HASH --helper-sha256 HASH --config-sha256 HASH --policy-sha256 HASH --pin-sha256 HASH +python3 deploy/windows/time_service_start.py start --id ORIGINALFALL +python3 deploy/windows/time_service_start.py readback --id ORIGINALFALL +``` + +Vollständige Metadaten bleiben in geschützten lokalen/VM-Fallbelegen. Die CLI +gibt nur Fallkennung, Status, Running-/Erhaltungs-/Readback-Merkmale und den +ausdrücklich nicht geprüften Uhrvertrauensstatus aus. Lokaler Quellnachweis: +`devstate/windows-client/time-service-start-source/225c3208-4a3f-4528-8c17-b3846b70812f/qualification.json`; +PowerShell nur geparst, kein Windows-API-/VM-Aufruf und keine Produkttestsuite. + +## Tatsächliche Ausführung + +Fall `c3552c3f-24d1-4713-bd0b-544aee4ffd18` auf dem Windowsgast: +Vorbereitung bestätigte Stopped und die bekannten Originalhashes. Anschließend +genau ein `Start-Service W32Time`, Status Running, Erhaltungsprüfung bestanden. +Getrennter späterer Readback bestätigte denselben Originalresultbeleg und +Running ohne Startwiederholung. Agent5140 und Helper6240 unverändert; +Dienstdefinition/SDDL und ausgewählte NTP-/Policy-Konfigurationswerte erhalten. +Kein privater Schlüsselinhalt gelesen und keine Konfiguration geschrieben. + +Zentraler Kontrollstand vorher/nachher identisch: Windows0Jobs/0Outbox/0Grants/ +0ungeklärt, Linux30/30/26/0; Rootpolicyhash und geschlossene Transporthooks +unverändert. Geschützter Abschlussbeleg `acceptance.json` im Originalfall, +SHA256 `365d897d94f6fb16b3112fcb5126bdc09224b34e0a6ef46940ca8e7a651807fb`. +Quellhash `ef5d4ce8…`. **Kein Uhrqualifikations-, RMM-Job- oder Rebootbeleg.**