diff --git a/Cargo.lock b/Cargo.lock index deebbf2..49f21ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2255,6 +2255,7 @@ dependencies = [ "rmm-domain", "rmm-protocol", "rmm-time-attestation", + "rmm-updater-handoff", "rusqlite", "rustls", "rustls-pemfile", diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 776916f..2759dc7 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.25 · 2026-11-15 · Sprache: Deutsch +Version 1.26 · 2026-11-16 · 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. @@ -92,6 +92,35 @@ Fristen, unabhängige Helperprüfung und WebUI-Genehmigung bleiben erhalten. ## 0 Auftrag und verbindliche Produktanforderungen +**Userentscheidung Version 1.26, Windows-MVP vollständig fortsetzen.** +Der Betreiber beauftragt nach dem ersten festen PowerShell-Test ausdrücklich +auch die verbleibenden Windows-MVP-Arbeiten, möglichst parallel. Die +Loopback-/SSH-Verwaltung ohne OIDC-Anbieter gilt weiterhin. Der sichtbar +simulierte dev/test-WebUI-Prüfer darf nach 0.1 auch die weiteren festen +Abnahmepläne bedienen; ein echter externer Identitätsanbieter wird dadurch +nicht nachträglich zur MVP-Voraussetzung. + +Die zusätzliche, dauerhaft gespeicherte Beschränkung auf den bereits +abgeschlossenen einzelnen Echoauftrag wird nicht durch Dateilöschung, einen +Konfigurationsschalter oder eine Migration automatisch aufgehoben. Ein eigener +interaktiver administrativer WebUI-Abschluss darf ausschließlich nach Prüfung +des exakten früheren Scopes, seiner signierten Quittung, des einmaligen +Originalverbrauchs und des erfolgreichen Ergebnisses diese Zusatzbeschränkung +historienerhaltend beenden. Ursprüngliche Quittungen, Journale, Signaturen, +Geräteidentität, Verbräuche und Ergebnisse bleiben erhalten; der Abschluss wird +zusätzlich unveränderlich protokolliert. Er genehmigt keine Aufträge und +erzeugt keine Bereitschaft. Beide Dienstrollen benötigen anschließend den +regulären unabhängigen Zeit-/SignedSync-Abgleich. Jeder weitere Auftrag hat +seinen eigenen festen Antrag und tatsächlichen WebUI-Genehmigungsschritt. + +Allgemeine LocalService-Skripte und getrennt erlaubte SYSTEM-Vollwartung, +Dienst-/MSI-Aktionen, Zertifikatslebenszyklus und der bereits vorgezogene +signierte Agentupdater bleiben eigenständig tatsächlich abzunehmen. Quellen, +Crossbuilds oder OS-Portbibliotheken sind keine vollständige native Abnahme. +Diese Fortsetzung erteilt keine implizite Freigabe unangekündigter destruktiver +Tests oder Betriebssystemupdates. Aktueller Nachweisstand: +`docs/windows-mvp-completion.md`. + **Userentscheidung Version 1.25, MVP-Verwaltung ausschließlich per SSH-Tunnel.** Der Betreiber verwendet aktuell keinen OIDC-Anbieter. Für den MVP werden WebUI und MCP ausschließlich auf Server-Loopback angeboten und über den @@ -383,6 +412,18 @@ Originaloutcome create-once per bestehendem CAS speichern; vorhandenes Unknown wird nicht überschrieben. Vorhandene Spiegelung und normaler signierter Sync übernehmen exakt diese Bytes und lösen die gleiche ursprüngliche Sperre. +Präzisierung des Windows-Ports in1.26: Die vorhandene geschützte +`time-attestation.json` bindet ebenfalls beide Codeimages. Ein neuer optionaler +streng typisierter Windows-Zeitprofilübergang bindet daher vor Genehmigung +exakte alte/neue Profilbyteshashes und zwei tatsächlich qualifizierte +Rollenbelege; fehlend bleibt er aus historischen Codecbytes ausgelassen. +Serverzeitschlüssel, Schlüsselgeneration, Geräte-/Plattform-/Betriebsannahmen +werden nicht verändert. Das zusätzliche feste fünfte Dateiziel erhält denselben +Intent-/Nachlesevertrag wie Code und Peerpins. Nur dieses neue Windows- +Handoffprofil darf bis18 Ereignisse haben; historische/Linuxprofile bleiben +bei ihrer bisherigen16-Ereignisgrenze. Ein Renderer oder OS-Port allein +qualifiziert weder eine Baseline noch Apply oder Rollback. + Dieser Abschnitt normiert den beauftragten engen Vertrag. Teilquellen/Units, OS-Port, tatsächliche Kernel-/VMnachweise und noch fehlender ausgelieferter Worker/Bootstrap/Apply sind getrennt in `docs/agent-updater-proposal.md`, diff --git a/crates/agent-core/src/update_handoff.rs b/crates/agent-core/src/update_handoff.rs index 5fbedab..3fb34e6 100644 --- a/crates/agent-core/src/update_handoff.rs +++ b/crates/agent-core/src/update_handoff.rs @@ -706,6 +706,8 @@ pub enum NativeService { Agent, General, Full, + WindowsAgent, + WindowsHelper, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -714,6 +716,9 @@ pub enum NativeFileRole { HelperBinary, FullConfig, FullPin, + WindowsSettings, + WindowsPin, + WindowsTimeProfile, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NativeEffectStage { @@ -747,9 +752,9 @@ impl NativeEffectClaim { self.claimed_at } } -pub struct PreparedReturnClaims { +pub struct PreparedReturnClaims { pub return_ledger: NativeEffectClaim, - pub starts: [NativeEffectClaim; 3], + pub starts: [NativeEffectClaim; N], } fn native_context( db: &Connection, @@ -781,6 +786,9 @@ fn native_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole { NativeFileRole::HelperBinary => F::HelperBinary, NativeFileRole::FullConfig => F::LinuxFullConfig, NativeFileRole::FullPin => F::LinuxFullPin, + NativeFileRole::WindowsSettings => F::WindowsSettings, + NativeFileRole::WindowsPin => F::WindowsPin, + NativeFileRole::WindowsTimeProfile => F::WindowsTimeProfile, } } fn native_service(service: NativeService) -> rmm_updater_handoff::Service { @@ -789,6 +797,8 @@ fn native_service(service: NativeService) -> rmm_updater_handoff::Service { NativeService::Agent => S::LinuxAgent, NativeService::General => S::LinuxGeneralHelper, NativeService::Full => S::LinuxFullHelper, + NativeService::WindowsAgent => S::WindowsAgent, + NativeService::WindowsHelper => S::WindowsHelper, } } fn native_key(effect: &NativeEffect) -> Result { @@ -976,6 +986,50 @@ pub fn prepare_return_and_starts( return_event: &[u8], now: DateTime, ) -> Result { + prepare_return_for( + db, + guard, + grant, + expected_head, + return_event, + now, + [ + NativeService::General, + NativeService::Full, + NativeService::Agent, + ], + ) +} +/// Windows' independently qualified SYSTEM helper returns the SAME retained +/// ledger before exactly Helper -> Agent. No Linux Full/General identity or +/// startup claim is invented. This is evidence, never a restart/resume token. +pub fn prepare_windows_return_and_starts( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + expected_head: &str, + return_event: &[u8], + now: DateTime, +) -> Result> { + prepare_return_for( + db, + guard, + grant, + expected_head, + return_event, + now, + [NativeService::WindowsHelper, NativeService::WindowsAgent], + ) +} +fn prepare_return_for( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + expected_head: &str, + return_event: &[u8], + now: DateTime, + sequence: [NativeService; N], +) -> Result> { let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let (h, d, mut j) = native_context(&tx, guard, grant, now)?; ensure!( @@ -985,8 +1039,21 @@ pub fn prepare_return_and_starts( "UPDATE_NATIVE_RETURN_ROLE" ); ensure!( - h.stop_set - .contains(&rmm_updater_handoff::Service::LinuxFullHelper), + (sequence.as_slice() + == [ + NativeService::General, + NativeService::Full, + NativeService::Agent + ] + && h.stop_set + .contains(&rmm_updater_handoff::Service::LinuxFullHelper)) + || (sequence.as_slice() == [NativeService::WindowsHelper, NativeService::WindowsAgent] + && h.pin_transition == rmm_updater_handoff::PinTransition::WindowsCodePairClockV1 + && h.stop_set + == [ + rmm_updater_handoff::Service::WindowsAgent, + rmm_updater_handoff::Service::WindowsHelper + ]), "UPDATE_NATIVE_FULL_PROFILE_REQUIRED" ); let missing:u64=tx.query_row("SELECT count(*) FROM agent_update_native_claims c LEFT JOIN agent_update_native_observations o ON c.grant_id=o.grant_id AND c.effect_key=o.effect_key WHERE c.grant_id=?1 AND o.effect_key IS NULL",[grant.to_string()],|r|r.get(0))?; @@ -1004,11 +1071,7 @@ pub fn prepare_return_and_starts( &NativeEffect::ReturnLedger, NativeEffectStage::Claim, )?; - for service in [ - NativeService::General, - NativeService::Full, - NativeService::Agent, - ] { + for service in sequence { guard.verify_native_effect( &h, &d, @@ -1021,11 +1084,7 @@ pub fn prepare_return_and_starts( let return_ledger = insert_native_claim(&tx, &h, j.head_sha256(), NativeEffect::ReturnLedger, now)?; let mut starts = Vec::new(); - for service in [ - NativeService::General, - NativeService::Full, - NativeService::Agent, - ] { + for service in sequence { starts.push(insert_native_claim( &tx, &h, diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index 1bfd5c7..b05d0ad 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -32,6 +32,7 @@ rmm-domain = { path = "../domain" } rmm-agent-core = { path = "../agent-core" } rmm-protocol = { path = "../protocol" } rmm-time-attestation = { path = "../time-attestation" } +rmm-updater-handoff = { path = "../updater-handoff" } rusqlite = { version = "0.32.1", features = ["bundled"] } fs2 = "0.4.3" x509-parser = { version = "=0.18.1", features = ["verify"] } diff --git a/crates/agent-windows/examples/windows_certificate_acceptance.rs b/crates/agent-windows/examples/windows_certificate_acceptance.rs new file mode 100644 index 0000000..4ca52cd --- /dev/null +++ b/crates/agent-windows/examples/windows_certificate_acceptance.rs @@ -0,0 +1,473 @@ +//! Explicit passive-certificate qualification on a separate fixture identity. +//! Run only as a child of the existing LocalService agent, after WebUI approval. +//! No original agent state, certificate, service configuration or key is read. +#[cfg(windows)] +mod native { + use anyhow::{Context, Result, ensure}; + use chrono::Utc; + use prost::Message; + use rcgen::{CertificateParams, DnType, KeyPair}; + use rmm_agent_windows::{ + certificate_rotation::{DeviceIdentity, ProtectedKeyFiles, RotationStore}, + journal::Journal, + native, + }; + use rmm_protocol::{ + ClientHello, EnrollmentRequest, EnrollmentResponse, Envelope, Heartbeat, MessageBatch, + Payload, + }; + use serde_json::{Value, json}; + use sha2::{Digest, Sha256}; + use std::{fs, io::Write, net::SocketAddr, path::Path, time::Duration}; + use uuid::Uuid; + + const SERVER: &str = "discovery.ease-technologies.de"; + const PERMANENT_AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3"; + + fn hash(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) + } + fn read(path: &Path, maximum: usize) -> Result> { + native::private_path(path, false)?; + ensure!( + fs::metadata(path)?.len() <= maximum as u64, + "FIXTURE_FILE_LIMIT" + ); + Ok(fs::read(path)?) + } + fn create(path: &Path, bytes: &[u8]) -> Result<()> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + // The fixture directory must provide its inherited service DACL before + // any private bytes are written, exactly like ProtectedKeyFiles. + native::private_path(path, false)?; + file.write_all(bytes)?; + file.sync_all()?; + Ok(()) + } + fn client(ca: &[u8], identity: Option<&DeviceIdentity>) -> Result { + let address: SocketAddr = "88.99.80.202:443".parse()?; + let mut builder = reqwest::Client::builder() + .https_only(true) + .tls_built_in_root_certs(false) + .add_root_certificate(reqwest::Certificate::from_pem(ca)?) + .resolve(SERVER, address) + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(10)); + if let Some(identity) = identity { + let mut pair = identity.certificate_pem.clone(); + pair.extend_from_slice(&identity.private_key_pem); + builder = builder.identity(reqwest::Identity::from_pem(&pair)?); + } + Ok(builder.build()?) + } + async fn body(mut response: reqwest::Response, content_type: &str) -> Result> { + ensure!(response.status().as_u16() == 200, "FIXTURE_HTTP_STATUS"); + ensure!( + response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + == Some(content_type), + "FIXTURE_CONTENT_TYPE" + ); + let mut result = Vec::new(); + while let Some(chunk) = response.chunk().await? { + ensure!( + result.len().saturating_add(chunk.len()) <= 65536, + "FIXTURE_RESPONSE_LIMIT" + ); + result.extend_from_slice(&chunk); + } + Ok(result) + } + fn certificate_hash(pem: &[u8]) -> Result { + let mut cursor = std::io::Cursor::new(pem); + let mut certificates = rustls_pemfile::certs(&mut cursor); + Ok(hash( + certificates + .next() + .context("FIXTURE_CERTIFICATE")?? + .as_ref(), + )) + } + fn envelope( + journal: &mut Journal, + agent: &str, + boot: &str, + generation: u64, + payload: Payload, + ) -> Result { + Ok(Envelope { + protocol_major: 1, + protocol_minor: 0, + message_id: Uuid::new_v4().to_string(), + agent_id: agent.into(), + enrollment_generation: 1, + connection_generation: generation, + boot_id: boot.into(), + sequence: journal.next_sequence()?, + observed_at: Utc::now().timestamp_millis(), + payload: Some(payload), + }) + } + async fn send(client: &reqwest::Client, envelope: &Envelope) -> Result { + let bytes = body( + client + .post(format!("https://{SERVER}/agent/v1/messages")) + .header(reqwest::header::CONTENT_TYPE, "application/x-protobuf") + .body( + MessageBatch { + protocol_major: 1, + messages: vec![envelope.clone()], + } + .encode_to_vec(), + ) + .send() + .await?, + "application/x-protobuf", + ) + .await?; + let replies = MessageBatch::decode(bytes.as_slice())?; + ensure!( + replies.protocol_major == 1 && replies.messages.len() == 1, + "FIXTURE_EXACT_REPLY" + ); + let reply = replies + .messages + .into_iter() + .next() + .context("FIXTURE_REPLY")?; + ensure!( + reply.protocol_major == 1 + && reply.protocol_minor == 0 + && reply.agent_id == envelope.agent_id + && reply.enrollment_generation == 1 + && reply.boot_id == envelope.boot_id + && reply.sequence == envelope.sequence, + "FIXTURE_REPLY_BINDING" + ); + Ok(reply) + } + async fn connect( + client: &reqwest::Client, + journal: &mut Journal, + agent: &str, + boot: &str, + ) -> Result { + let hello = envelope( + journal, + agent, + boot, + 0, + Payload::ClientHello(ClientHello { + agent_version: "certificate-acceptance/1".into(), + capabilities: vec!["heartbeat/1".into()], + }), + )?; + let reply = send(client, &hello).await?; + let Some(Payload::ServerHello(server)) = reply.payload else { + anyhow::bail!("FIXTURE_HELLO_REQUIRED") + }; + ensure!( + server.connection_generation > 0 + && reply.connection_generation == server.connection_generation, + "FIXTURE_GENERATION" + ); + let heartbeat = envelope( + journal, + agent, + boot, + server.connection_generation, + Payload::Heartbeat(Heartbeat { + instance_id: Uuid::new_v4().to_string(), + uptime_seconds: 1, + }), + )?; + let acknowledgement = send(client, &heartbeat).await?; + ensure!( + matches!(acknowledgement.payload, Some(Payload::Ack(ref a)) if a.message_id == heartbeat.message_id), + "FIXTURE_HEARTBEAT_ACK" + ); + ensure!( + acknowledgement.connection_generation == server.connection_generation, + "FIXTURE_ACK_GENERATION" + ); + Ok(server.connection_generation) + } + async fn renew(root: &Path, phase: &mut &'static str) -> Result { + *phase = "enrollment"; + create( + &root.join("started.json"), + b"{\"schema_version\":1,\"no_restart\":true}", + )?; + let ca = read(&root.join("ca.pem"), 32768)?; + let key = KeyPair::generate()?; + create(&root.join("device.key"), key.serialize_pem().as_bytes())?; + let mut parameters = CertificateParams::default(); + parameters + .distinguished_name + .push(DnType::CommonName, "certificate-acceptance"); + let csr = parameters.serialize_request(&key)?.pem()?; + let token = String::from_utf8(read(&root.join("enrollment-token"), 128)?)? + .trim() + .to_owned(); + ensure!( + token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()), + "FIXTURE_ENROLLMENT_TOKEN" + ); + let enrolled: EnrollmentResponse = serde_json::from_slice( + &body( + client(&ca, None)? + .post(format!("https://{SERVER}/agent/v1/enroll")) + .json(&EnrollmentRequest { + token, + csr_pem: csr, + }) + .send() + .await?, + "application/json", + ) + .await?, + )?; + let agent = Uuid::parse_str(&enrolled.agent_id)?; + ensure!( + !agent.is_nil() + && enrolled.agent_id != PERMANENT_AGENT + && !Uuid::parse_str(&enrolled.asset_id)?.is_nil(), + "SEPARATE_FIXTURE_IDENTITY" + ); + create( + &root.join("device.pem"), + enrolled.certificate_pem.as_bytes(), + )?; + create(&root.join("identity.json"), &serde_json::to_vec(&enrolled)?)?; + fs::remove_file(root.join("enrollment-token"))?; + let original_key_hash = hash(&read(&root.join("device.key"), 16384)?); + let original_certificate_hash = certificate_hash(enrolled.certificate_pem.as_bytes())?; + let store = RotationStore::new(agent, 1, ca.clone())?; + let mut journal = Journal::open(root)?; + journal.pin_identity(&enrolled.agent_id)?; + let keys = ProtectedKeyFiles::open(root)?; + store.initialize( + journal.connection_mut(), + &keys, + enrolled.certificate_pem.as_bytes(), + Utc::now().timestamp(), + )?; + ensure!( + !store.due(journal.connection(), &keys, Utc::now().timestamp())?, + "FRESH_CERTIFICATE_NOT_DUE" + ); + let original = store.current(journal.connection(), &keys, Utc::now().timestamp())?; + let old_client = client(&ca, Some(&original))?; + let boot = native::boot_id().await?; + let original_generation = + connect(&old_client, &mut journal, &enrolled.agent_id, &boot).await?; + *phase = "renewal_response_discard"; + let pending = store.prepare(journal.connection_mut(), &keys, Utc::now().timestamp())?; + let csr_hash = hash(pending.csr_pem.as_bytes()); + let first = body( + old_client + .post(format!("https://{SERVER}/agent/v1/certificates/renew")) + .json(&json!({"csr_pem":pending.csr_pem})) + .send() + .await?, + "application/json", + ) + .await?; + let first_hash = hash(&first); + // Deliberately do not install the first real server response. Close the + // actual SQLite/key handles; a reopened journal must reuse the CSR. + drop(pending); + drop(first); + drop(keys); + drop(journal); + *phase = "renewal_reopen"; + let mut journal = Journal::open(root)?; + let keys = ProtectedKeyFiles::open(root)?; + let pending = store.prepare(journal.connection_mut(), &keys, Utc::now().timestamp())?; + ensure!( + hash(pending.csr_pem.as_bytes()) == csr_hash, + "EXACT_PENDING_CSR_AFTER_REOPEN" + ); + let second = body( + client(&ca, Some(&pending.identity))? + .post(format!("https://{SERVER}/agent/v1/certificates/renew")) + .json(&json!({"csr_pem":pending.csr_pem})) + .send() + .await?, + "application/json", + ) + .await?; + ensure!( + hash(&second) == first_hash, + "EXACT_IDEMPOTENT_SERVER_RESPONSE" + ); + store.install( + journal.connection_mut(), + &keys, + &pending, + &second, + Utc::now().timestamp(), + )?; + ensure!( + !store.has_pending(journal.connection())?, + "RENEWAL_COMMIT_PENDING" + ); + drop(pending); + drop(keys); + drop(journal); + *phase = "new_certificate_connection"; + let mut journal = Journal::open(root)?; + let keys = ProtectedKeyFiles::open(root)?; + let current = store.current(journal.connection(), &keys, Utc::now().timestamp())?; + let renewed_hash = certificate_hash(¤t.certificate_pem)?; + ensure!( + renewed_hash != original_certificate_hash, + "NEW_CERTIFICATE_REQUIRED" + ); + let renewed_generation = connect( + &client(&ca, Some(¤t))?, + &mut journal, + &enrolled.agent_id, + &boot, + ) + .await?; + ensure!( + renewed_generation > original_generation, + "RENEWAL_RECONNECTED_GENERATION" + ); + ensure!( + hash(&read(&root.join("device.key"), 16384)?) == original_key_hash + && certificate_hash(&read(&root.join("device.pem"), 32768)?)? + == original_certificate_hash, + "ORIGINAL_FIXTURE_FILES_PRESERVED" + ); + Ok( + json!({"schema_version":1,"verified":true,"identity_scope":"separate_fixture","agent_id":agent, + "asset_id":enrolled.asset_id,"boot_id":boot,"execution_sid":"S-1-5-19","service_sid":native::service_sid()?, + "original_certificate_sha256":original_certificate_hash,"renewed_certificate_sha256":renewed_hash, + "csr_sha256":csr_hash,"response_sha256":first_hash,"same_csr_after_reopen":true, + "same_server_response":true,"new_certificate_mtls_hello_and_heartbeat":true, + "original_generation":original_generation,"renewed_generation":renewed_generation, + "original_fixture_files_preserved":true,"permanent_identity_read":false, + "scheduler_age_trigger_tested":false,"jobs_created":false,"completed_at":Utc::now()}), + ) + } + async fn revoked_read(root: &Path, phase: &mut &'static str) -> Result { + *phase = "revoked_identity_denial"; + let before: Value = + serde_json::from_slice(&read(&root.join("renewal-result.json"), 16384)?)?; + ensure!(before["verified"] == true, "PRIOR_RENEWAL_REQUIRED"); + let enrolled: EnrollmentResponse = + serde_json::from_slice(&read(&root.join("identity.json"), 32768)?)?; + ensure!( + enrolled.agent_id != PERMANENT_AGENT && before["agent_id"] == enrolled.agent_id, + "SAME_SEPARATE_FIXTURE" + ); + let ca = read(&root.join("ca.pem"), 32768)?; + let store = RotationStore::new(Uuid::parse_str(&enrolled.agent_id)?, 1, ca.clone())?; + let mut journal = Journal::open(root)?; + let keys = ProtectedKeyFiles::open(root)?; + let identity = store.current(journal.connection(), &keys, Utc::now().timestamp())?; + ensure!( + before["renewed_certificate_sha256"] == certificate_hash(&identity.certificate_pem)?, + "SAME_RENEWED_CERTIFICATE" + ); + let hello = envelope( + &mut journal, + &enrolled.agent_id, + &native::boot_id().await?, + 0, + Payload::ClientHello(ClientHello { + agent_version: "certificate-acceptance/1".into(), + capabilities: vec!["heartbeat/1".into()], + }), + )?; + let response = client(&ca, Some(&identity))? + .post(format!("https://{SERVER}/agent/v1/messages")) + .header(reqwest::header::CONTENT_TYPE, "application/x-protobuf") + .body( + MessageBatch { + protocol_major: 1, + messages: vec![hello], + } + .encode_to_vec(), + ) + .send() + .await?; + // A TLS or network failure is not accepted as proof of revocation. + ensure!( + response.status().as_u16() == 401, + "EXACT_AUTHENTICATED_REVOCATION_DENIAL" + ); + Ok( + json!({"schema_version":1,"verified":true,"agent_id":enrolled.agent_id, + "execution_sid":"S-1-5-19","http_status":401,"permanent_identity_read":false, + "jobs_created":false,"completed_at":Utc::now()}), + ) + } + pub fn main() -> Result<()> { + native::require_local_service()?; + let arguments: Vec<_> = std::env::args().skip(1).collect(); + ensure!(arguments.len() == 2, "FIXTURE_ARGUMENTS"); + let id = Uuid::parse_str(&arguments[1])?; + ensure!( + !id.is_nil() && id.to_string() == arguments[1], + "FIXTURE_CASE_UUID" + ); + let root = std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\certificate-acceptance") + .join(id.to_string()); + native::private_path(&root, true)?; + let report = match arguments[0].as_str() { + "renew" => root.join("renewal-result.json"), + "revoked-read" => root.join("revocation-result.json"), + _ => anyhow::bail!("FIXTURE_MODE"), + }; + ensure!(!report.try_exists()?, "FIXTURE_REPORT_ALREADY_PRESENT"); + let mut phase = "initialization"; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let result = runtime.block_on(async { + if arguments[0] == "renew" { + renew(&root, &mut phase).await + } else { + revoked_read(&root, &mut phase).await + } + }); + match result { + Ok(value) => { + create(&report, &serde_json::to_vec(&value)?)?; + println!("{}", serde_json::to_string(&value)?); + Ok(()) + } + Err(_) => { + // No network/library error text, credential or private key goes + // into the approved job's output or its public receipt. + let failure = json!({"schema_version":1,"verified":false,"phase":phase, + "error_code":"CERTIFICATE_ACCEPTANCE_FAILED","restart_allowed":false}); + create(&report, &serde_json::to_vec(&failure)?)?; + println!("{}", serde_json::to_string(&failure)?); + anyhow::bail!("CERTIFICATE_ACCEPTANCE_FAILED") + } + } + } +} + +#[cfg(windows)] +fn main() { + if native::main().is_err() { + eprintln!("CERTIFICATE_ACCEPTANCE_FAILED"); + std::process::exit(1); + } +} +#[cfg(not(windows))] +fn main() { + eprintln!("Native Windows LocalService fixture only"); + std::process::exit(1); +} diff --git a/crates/agent-windows/examples/windows_reviewed_recovery.rs b/crates/agent-windows/examples/windows_reviewed_recovery.rs index bfdcea5..96fabe0 100644 --- a/crates/agent-windows/examples/windows_reviewed_recovery.rs +++ b/crates/agent-windows/examples/windows_reviewed_recovery.rs @@ -160,8 +160,134 @@ mod windows { ensure!(bytes.len() as u64 <= max, "public file changed"); Ok(bytes) } + fn complete_echo(apply: bool) -> Result<()> { + let readers = [ipc::service_sid(SERVICE_NAME)?]; + let _root = PinnedFile::open(Path::new(ROOT), true, &readers, &[], false)?; + let mut pin = PinnedFile::open( + &Path::new(ROOT).join("binding.json"), + false, + &readers, + &[], + false, + )?; + let bytes = data(&mut pin.file, 8192)?; + ensure!(hash(&bytes) == BINDING_SHA256, "changed job binding"); + let binding: Binding = serde_json::from_slice(&bytes)?; + let (settings, _pins) = helper_system::read_settings()?; + let mut config = PinnedFile::open( + &Path::new(ROOT).join("config.json"), + false, + &readers, + &[], + false, + )?; + ensure!( + config.sha256()? == PASSIVE && !settings.enable_effects && !settings.allow_reboot, + "restore original passive pair first" + ); + let stopped = both_stopped()?; + ensure!( + !apply || stopped, + "both services must be stopped by the operator" + ); + let mut locks = vec![]; + if stopped { + for path in [ + Path::new(STATE).join("agent.lock"), + Path::new(helper_system::STATE_ROOT).join("executor.lock"), + ] { + let file = leaf(&path)?; + file.try_lock_exclusive().context("service lock busy")?; + locks.push(file); + } + ensure!(both_stopped()?, "service started during completion"); + } + native::private_path(Path::new(STATE), true)?; + for p in [AGENT_DB, LOCAL_DB] { + native::private_path(Path::new(p), false)?; + } + let helper_sid = [ipc::service_sid(ipc::HELPER_SERVICE)?]; + let _helper_state = PinnedFile::open_read_shared( + Path::new(helper_system::STATE_ROOT), + true, + &[], + &helper_sid, + )?; + let helper_file = + PinnedFile::open_read_shared(Path::new(HELPER_DB), false, &[], &helper_sid)?; + let mut agent = Db::open(AGENT_DB, apply, stopped)?; + let consumption = Db::open(LOCAL_DB, false, stopped)?; + let helper = Db::open(HELPER_DB, false, stopped)?; + let (ledger, lock, pin): (Vec, Vec, String) = helper.db.query_row( + "SELECT ledger,executor_lock,binding_sha256 FROM windows_helper_files WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + )?; + ensure!( + serde_json::from_slice::(&ledger)? == helper_file.identity + && pin == ipc::binding_hash(&settings.binding)?, + "helper journal or binding changed" + ); + let witness = rmm_agent_windows::echo_completion::witness( + &agent.db, + &consumption.db, + &helper.db, + &binding, + &settings.binding, + )?; + println!("{}", serde_json::to_string(&witness)?); + if apply { + ensure!( + serde_json::from_slice::(&lock)? + == ipc::file_identity(&locks[1])?, + "helper lock identity changed" + ); + let path = + Path::new(r"C:\ProgramData\RustDiscoveryBootstrap\windows-echo-completion.json"); + let _folder = PinnedFile::open( + path.parent().context("completion folder")?, + true, + &[], + &[], + false, + )?; + let mut file = PinnedFile::open(path, false, &[], &[], false)?; + let receipt = data(&mut file.file, 131072)?; + let boot = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(native::boot_id())?; + let boot = uuid::Uuid::parse_str(&boot)?; + ensure!(both_stopped()?, "service started during completion"); + let pair = rmm_agent_windows::echo_completion::LocalPair { + consumption: &consumption.db, + helper: &helper.db, + binding: &binding, + helper_binding: &settings.binding, + }; + rmm_agent_windows::echo_completion::apply( + &mut agent.db, + pair, + &receipt, + boot, + chrono::Utc::now(), + )?; + println!( + "additional echo restriction retired; original history retained; ordinary signed pair sync and each WebUI job approval remain required" + ); + } + Ok(()) + } pub fn run() -> Result<()> { let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() == 1 + && matches!( + args[0].as_str(), + "echo-completion-read" | "echo-completion-apply" + ) + { + return complete_echo(args[0] == "echo-completion-apply"); + } ensure!( args.len() == 1 && matches!( diff --git a/crates/agent-windows/examples/windows_updater_preflight.rs b/crates/agent-windows/examples/windows_updater_preflight.rs new file mode 100644 index 0000000..d0e1e59 --- /dev/null +++ b/crates/agent-windows/examples/windows_updater_preflight.rs @@ -0,0 +1,53 @@ +//! Read-only native updater OS-port preflight. No activation/capability proof. +#[cfg(all(windows, feature = "system-helper"))] +fn main() -> anyhow::Result<()> { + use rmm_agent_core::helper_reconcile::BootSource; + use rmm_agent_windows::{ + helper_system, + update_native::{Budget, Role, files, services::Running}, + }; + use std::time::Duration; + use uuid::Uuid; + struct Boot(Uuid); + impl BootSource for Boot { + fn current_boot(&self) -> anyhow::Result { + Ok(self.0) + } + } + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let boot = Boot( + runtime + .block_on(rmm_agent_windows::native::boot_id())? + .parse()?, + ); + let budget = Budget::new(&boot, boot.0, Duration::from_secs(30))?; + let (settings, _guards) = helper_system::read_settings()?; + let mut running = Running::observe([settings.agent.clone(), settings.helper.clone()], &budget)?; + let mut files = Vec::new(); + for role in [ + Role::Agent, + Role::Helper, + Role::Settings, + Role::Pin, + Role::TimeProfile, + ] { + files.push(serde_json::json!({"role":role,"proof":files::observe(role, &budget)?})); + } + running.check(&budget)?; + println!( + "{}", + serde_json::to_string(&serde_json::json!({ + "schema_version":1,"read_only":true,"boot_id":boot.0, + "services":running.proofs(),"files":files,"native_apply_tested":false, + "job_created":false,"capability_qualified":false + }))? + ); + Ok(()) +} +#[cfg(not(all(windows, feature = "system-helper")))] +fn main() { + eprintln!("Windows with system-helper feature required; no test executed"); + std::process::exit(2); +} diff --git a/crates/agent-windows/src/certificate_rotation.rs b/crates/agent-windows/src/certificate_rotation.rs index 0005b25..91dbdef 100644 --- a/crates/agent-windows/src/certificate_rotation.rs +++ b/crates/agent-windows/src/certificate_rotation.rs @@ -3,7 +3,7 @@ //! The caller must retain the existing exclusive agent-state journal lock. use anyhow::{Context, Result, ensure}; use rcgen::{CertificateParams, DnType, KeyPair}; -use rusqlite::{Connection, params}; +use rusqlite::{Connection, OptionalExtension, params}; use rustls::{RootCertStore, pki_types::UnixTime, sign::CertifiedKey}; use serde::Deserialize; use std::{io::Cursor, sync::Arc, time::Duration}; @@ -61,7 +61,10 @@ impl RotationStore { ) -> Result<()> { let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; tx.execute_batch("CREATE TABLE IF NOT EXISTS tls_versions(version TEXT PRIMARY KEY,certificate BLOB,csr TEXT); - CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version));")?; + CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version)); + CREATE TABLE IF NOT EXISTS tls_idle_admission(version TEXT PRIMARY KEY REFERENCES tls_versions(version),witness BLOB NOT NULL CHECK(length(witness) BETWEEN 1 AND 32768)); + CREATE TRIGGER IF NOT EXISTS tls_idle_no_update BEFORE UPDATE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END; + CREATE TRIGGER IF NOT EXISTS tls_idle_no_delete BEFORE DELETE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END;")?; let present: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM tls_rotation)", [], |r| { r.get(0) })?; @@ -173,6 +176,20 @@ impl RotationStore { pub fn has_pending(&self, db: &Connection) -> Result { Ok(self.selector(db)?.1.is_some()) } + /// Retained local maintenance context, never readiness or job authority. + /// Legacy passive requests deliberately have no active-idle admission. + pub fn pending_idle_admission(&self, db: &Connection) -> Result>> { + let Some(version) = self.selector(db)?.1 else { + return Ok(None); + }; + Ok(db + .query_row( + "SELECT witness FROM tls_idle_admission WHERE version=?1", + [version.to_string()], + |r| r.get(0), + ) + .optional()?) + } /// A crash before the transaction leaves only an unselected key file. A /// response loss reuses the committed CSR/key and still-valid old mTLS leaf. pub fn prepare( @@ -181,9 +198,37 @@ impl RotationStore { keys: &impl KeyFiles, now: i64, ) -> Result { + self.prepare_with_idle_admission(db, keys, now, None) + } + /// Commit a caller-verified idle witness in the SAME transaction as the + /// pending CSR/selector. A resumed active request must retain exact bytes. + pub fn prepare_with_idle_admission( + &self, + db: &mut Connection, + keys: &impl KeyFiles, + now: i64, + admission: Option<&[u8]>, + ) -> Result { + ensure!( + admission.is_none_or(|bytes| !bytes.is_empty() && bytes.len() <= 32768), + "ROTATION_IDLE_ADMISSION_LIMIT" + ); let identity = self.current(db, keys, now)?; let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; let (base, pending) = self.selector(&tx)?; + if let (Some(version), Some(expected)) = (pending, admission) { + let saved: Option> = tx + .query_row( + "SELECT witness FROM tls_idle_admission WHERE version=?1", + [version.to_string()], + |r| r.get(0), + ) + .optional()?; + ensure!( + saved.as_deref() == Some(expected), + "ROTATION_IDLE_ADMISSION_CHANGED" + ); + } let (version, csr_pem) = if let Some(version) = pending { ensure!( !version.is_nil() && version != base, @@ -231,6 +276,12 @@ impl RotationStore { "UPDATE tls_rotation SET pending_version=?1 WHERE id=1", [version.to_string()], )?; + if let Some(witness) = admission { + tx.execute( + "INSERT INTO tls_idle_admission VALUES(?1,?2)", + params![version.to_string(), witness], + )?; + } (version, csr) }; tx.commit()?; @@ -299,6 +350,71 @@ impl RotationStore { } } +/// A local idle witness for certificate maintenance, not an execution grant. +/// All accepted/unknown work and missing effect evidence block rotation. The +/// caller retains both existing database guards while computing this digest. +pub fn idle_history_sha256(journal: &Connection, ledger: &Connection) -> Result { + use rusqlite::types::ValueRef; + use sha2::{Digest, Sha256}; + let safe: bool = journal.query_row("SELECT count(*)=1 AND min(last_decision IS NOT NULL AND pending_request IS NULL AND fault IS NULL AND generation>0) FROM reconcile_meta WHERE id=1", [], |r| r.get(0))?; + let idle: bool = journal.query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')) AND NOT EXISTS(SELECT 1 FROM job_events) AND NOT EXISTS(SELECT 1 FROM events)", [], |r| r.get(0))?; + let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL) AND NOT EXISTS(SELECT 1 FROM execution_evidence e LEFT JOIN consumed c USING(grant_id) WHERE c.grant_id IS NULL)", [], |r| r.get(0))?; + ensure!( + safe && idle && resolved, + "ROTATION_EFFECT_OR_CONTROL_UNRESOLVED" + ); + let mut hash = Sha256::new(); + hash.update(b"rmm.windows.tls-idle.v1\0"); + for (db, sql) in [ + (journal, "SELECT seq FROM counter WHERE id=1"), + ( + journal, + "SELECT journal_id,checkpoint,high_sequence,generation,last_decision,pending_request,helper_id,helper_checkpoint,fault FROM reconcile_meta WHERE id=1", + ), + ( + journal, + "SELECT job,attempt,offer,state,revision,grant_id,cancel_requested FROM job_attempts ORDER BY job,attempt", + ), + ( + ledger, + "SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) ORDER BY c.grant_id", + ), + ] { + hash.update(sql.as_bytes()); + let mut query = db.prepare(sql)?; + let columns = query.column_count(); + let mut rows = query.query([])?; + let mut count = 0u64; + while let Some(row) = rows.next()? { + count += 1; + ensure!(count <= 256, "ROTATION_HISTORY_LIMIT"); + hash.update([0xff]); + for column in 0..columns { + match row.get_ref(column)? { + ValueRef::Null => hash.update([0]), + ValueRef::Integer(value) => { + hash.update([1]); + hash.update(value.to_be_bytes()); + } + ValueRef::Text(bytes) | ValueRef::Blob(bytes) => { + ensure!(bytes.len() <= 1048576, "ROTATION_HISTORY_BLOB_LIMIT"); + hash.update([if matches!(row.get_ref(column)?, ValueRef::Text(_)) { + 2 + } else { + 3 + }]); + hash.update((bytes.len() as u64).to_be_bytes()); + hash.update(bytes); + } + ValueRef::Real(_) => anyhow::bail!("ROTATION_HISTORY_TYPE"), + } + } + } + hash.update(count.to_be_bytes()); + } + Ok(format!("{:x}", hash.finalize())) +} + #[cfg(windows)] pub struct ProtectedKeyFiles { root: std::path::PathBuf, @@ -474,6 +590,146 @@ mod tests { .unwrap() } #[test] + fn active_idle_admission_is_atomic_retained_and_cannot_adopt_legacy_pending() { + let (mut db, keys, store, _, _) = setup(); + let witness = b"exact independently checked idle context"; + db.execute_batch("CREATE TEMP TRIGGER deny_idle BEFORE INSERT ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'TEST_IDLE_COMMIT_DENIED');END;").unwrap(); + assert!( + store + .prepare_with_idle_admission(&mut db, &keys, now(), Some(witness)) + .is_err() + ); + assert_eq!(store.selector(&db).unwrap(), (Uuid::nil(), None)); + assert_eq!( + db.query_row("SELECT count(*) FROM tls_versions", [], |r| r + .get::<_, u64>(0)) + .unwrap(), + 1 + ); + db.execute_batch("DROP TRIGGER deny_idle").unwrap(); + let original = store + .prepare_with_idle_admission(&mut db, &keys, now(), Some(witness)) + .unwrap(); + assert_eq!( + store.pending_idle_admission(&db).unwrap().as_deref(), + Some(witness.as_slice()) + ); + assert!( + store + .prepare_with_idle_admission(&mut db, &keys, now(), Some(b"changed context")) + .is_err() + ); + let retained = store + .prepare_with_idle_admission(&mut db, &keys, now(), Some(witness)) + .unwrap(); + assert_eq!(original.version, retained.version); + assert_eq!(original.csr_pem, retained.csr_pem); + assert!( + db.execute( + "UPDATE tls_idle_admission SET witness=?1", + [b"replacement".as_slice()] + ) + .is_err() + ); + assert!(db.execute("DELETE FROM tls_idle_admission", []).is_err()); + let (mut legacy, legacy_keys, legacy_store, _, _) = setup(); + legacy_store + .prepare(&mut legacy, &legacy_keys, now()) + .unwrap(); + assert!( + legacy_store + .pending_idle_admission(&legacy) + .unwrap() + .is_none() + ); + assert!( + legacy_store + .prepare_with_idle_admission(&mut legacy, &legacy_keys, now(), Some(witness)) + .is_err() + ); + } + #[test] + fn idle_history_rejects_unfinished_jobs_missing_effect_evidence_and_changed_heads() { + let root = std::env::temp_dir().join(format!("rmm-rotation-idle-{}", Uuid::new_v4())); + std::fs::create_dir(&root).unwrap(); + let journal = crate::journal::Journal::open(&root).unwrap(); + let ledger = Connection::open_in_memory().unwrap(); + rmm_agent_core::ledger::initialize_ledger(&ledger).unwrap(); + assert!(idle_history_sha256(journal.connection(), &ledger).is_err()); + journal + .connection() + .execute( + "UPDATE reconcile_meta SET generation=1,last_decision=?1 WHERE id=1", + [Uuid::new_v4().to_string()], + ) + .unwrap(); + let clean = idle_history_sha256(journal.connection(), &ledger).unwrap(); + journal.connection().execute("INSERT INTO job_attempts(job,attempt,offer,state) VALUES('fixture','attempt',x'01','accepted')",[]).unwrap(); + for state in [ + "queued", + "accepted", + "requesting", + "running", + "verifying", + "unknown", + "awaiting_reboot", + ] { + journal + .connection() + .execute("UPDATE job_attempts SET state=?1", [state]) + .unwrap(); + assert!( + idle_history_sha256(journal.connection(), &ledger).is_err(), + "{state}" + ); + } + journal + .connection() + .execute("UPDATE job_attempts SET state='succeeded'", []) + .unwrap(); + let finished = idle_history_sha256(journal.connection(), &ledger).unwrap(); + assert_ne!(clean, finished); + ledger + .execute( + "INSERT INTO consumed VALUES('grant','agent',1,'fixture','attempt',NULL)", + [], + ) + .unwrap(); + assert!(idle_history_sha256(journal.connection(), &ledger).is_err()); + ledger + .execute("UPDATE consumed SET result=x'02'", []) + .unwrap(); + assert!(idle_history_sha256(journal.connection(), &ledger).is_err()); + ledger + .execute( + "INSERT INTO execution_evidence VALUES('grant',x'01',x'02')", + [], + ) + .unwrap(); + let resolved = idle_history_sha256(journal.connection(), &ledger).unwrap(); + journal + .connection() + .execute( + "UPDATE reconcile_meta SET checkpoint=checkpoint+1 WHERE id=1", + [], + ) + .unwrap(); + assert_ne!( + resolved, + idle_history_sha256(journal.connection(), &ledger).unwrap() + ); + journal + .connection() + .execute( + "UPDATE reconcile_meta SET pending_request='pending' WHERE id=1", + [], + ) + .unwrap(); + assert!(idle_history_sha256(journal.connection(), &ledger).is_err()); + drop(journal); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn response_loss_reuses_exact_pending_csr_and_private_key_stays_outside_sqlite() { let (mut db, keys, store, issuer, old) = setup(); assert!(store.due(&db, &keys, now()).unwrap()); diff --git a/crates/agent-windows/src/echo_completion.rs b/crates/agent-windows/src/echo_completion.rs new file mode 100644 index 0000000..771d45f --- /dev/null +++ b/crates/agent-windows/src/echo_completion.rs @@ -0,0 +1,463 @@ +//! Append-only retirement of the additional development echo restriction. +//! Preserves all original scope, journal, fault history and consumption bytes. +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, Utc}; +use prost::Message; +use rmm_agent_core::{ + auth::{Binding, Request}, + crypto::{DalekVerifier, Ed25519Verifier}, +}; +use rmm_domain::{ + checkpoint_repair::{SignedReceipt, inventory_sha256}, + jobs::{ExecutionPermitPayload, JobPayload, hash}, + windows_echo_completion::{Receipt, Witness, successful_outcome}, + windows_echo_probe::{ProbeReceipt, ProbeScope}, +}; +use rmm_protocol::JobOffer; +use rusqlite::{Connection, TransactionBehavior, params}; +use serde_json::Value; + +const TABLE: &str = "windows_echo_scope_completion"; +const DDL: &str = "CREATE TABLE windows_echo_scope_completion(id INTEGER PRIMARY KEY CHECK(id=1),original_receipt BLOB NOT NULL,witness_sha256 TEXT NOT NULL,applied_at TEXT NOT NULL)"; +fn schema() -> [String; 4] { + [DDL.into(), + "CREATE TRIGGER windows_echo_completion_no_replace BEFORE INSERT ON windows_echo_scope_completion WHEN EXISTS(SELECT 1 FROM windows_echo_scope_completion) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into(), + "CREATE TRIGGER windows_echo_completion_no_change BEFORE UPDATE ON windows_echo_scope_completion BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into(), + "CREATE TRIGGER windows_echo_completion_no_delete BEFORE DELETE ON windows_echo_scope_completion BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into()] +} +fn verify(binding: &Binding, bytes: &[u8], signature: &[u8]) -> Result<()> { + let b = &binding.public_key_hex; + ensure!( + b.len() == 64 && b.is_ascii() && bytes.len() <= 65536 && signature.len() == 64, + "completion pin/size" + ); + let key = (0..64) + .step_by(2) + .map(|i| u8::from_str_radix(&b[i..i + 2], 16)) + .collect::, _>>()?; + ensure!( + DalekVerifier.verify(&key, bytes, signature)?, + "completion original signature" + ); + Ok(()) +} +fn receipt(raw: &[u8], binding: &Binding) -> Result { + ensure!(raw.len() <= 131072, "completion envelope size"); + let signed: SignedReceipt = serde_json::from_slice(raw)?; + verify(binding, &signed.payload, &signed.signature)?; + let r: Receipt = serde_json::from_slice(&signed.payload)?; + ensure!(r.valid(r.issued_at), "completion historical profile"); + let key = (0..64) + .step_by(2) + .map(|i| u8::from_str_radix(&binding.public_key_hex[i..i + 2], 16)) + .collect::, _>>()?; + ensure!(r.key_id == hash(&key), "completion signing key"); + Ok(r) +} +fn matches_original(r: &Receipt, scope: &ProbeScope, original: &[u8]) -> Result<()> { + let old: SignedReceipt = serde_json::from_slice(original)?; + let p: ProbeReceipt = serde_json::from_slice(&old.payload)?; + ensure!( + &r.witness.scope == scope + && r.witness.probe_receipt_id == p.receipt_id + && r.witness.probe_receipt_sha256 == hash(&old.payload) + && r.witness.probe_signature_sha256 == hash(&old.signature), + "completion retained scope" + ); + Ok(()) +} +pub fn installed( + db: &Connection, + binding: &Binding, + scope: &ProbeScope, + original: &[u8], +) -> Result { + let exists: bool = db.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name=?)", + [TABLE], + |r| r.get(0), + )?; + if !exists { + return Ok(false); + } + let names = [ + TABLE, + "windows_echo_completion_no_replace", + "windows_echo_completion_no_change", + "windows_echo_completion_no_delete", + ]; + for (name, expected) in names.iter().zip(schema()) { + let actual: String = + db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| { + r.get(0) + })?; + ensure!(actual == expected, "completion schema"); + } + let (raw, digest): (Vec, String) = db.query_row( + "SELECT original_receipt,witness_sha256 FROM windows_echo_scope_completion WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + let r = receipt(&raw, binding)?; + matches_original(&r, scope, original)?; + ensure!(digest == r.witness_sha256, "completion archive digest"); + Ok(true) +} + +/// Independent read of original native start, signatures and exact successful outcome. +pub fn witness( + db: &Connection, + consumption: &Connection, + helper: &Connection, + binding: &Binding, + helper_binding: &Binding, +) -> Result { + let (scope, original) = + crate::echo_probe::archive(db, binding)?.context("original echo scope missing")?; + let old: SignedReceipt = serde_json::from_slice(&original)?; + verify(helper_binding, &old.payload, &old.signature)?; + let probe: ProbeReceipt = serde_json::from_slice(&old.payload)?; + ensure!( + ( + helper_binding.tenant_id, + helper_binding.asset_id, + helper_binding.agent_id, + helper_binding.enrollment_generation, + helper_binding.assignment_version + ) == ( + binding.tenant_id, + binding.asset_id, + binding.agent_id, + binding.enrollment_generation, + binding.assignment_version + ), + "completion independent helper identity" + ); + for journal in [db, consumption, helper] { + let check: String = journal.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; + ensure!(check == "ok", "completion journal integrity"); + } + let fault: Option = + db.query_row("SELECT fault FROM reconcile_meta WHERE id=1", [], |r| { + r.get(0) + })?; + ensure!(fault.is_none(), "current reconciliation fault"); + let jobs: u64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?; + ensure!(jobs == 1, "completion requires exact native single probe"); + let (offer, state, grant): (Vec, String, String) = db.query_row( + "SELECT offer,state,grant_id FROM job_attempts WHERE job=? AND attempt=?", + params![scope.job_id.to_string(), scope.attempt_id.to_string()], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + )?; + let offer = JobOffer::decode(offer.as_slice())?; + let job: JobPayload = serde_json::from_slice(&offer.payload_bytes)?; + ensure!( + state == "succeeded" && crate::echo_probe::permits_offer(&scope, &offer, &job), + "native completed echo offer" + ); + let count: u64 = consumption.query_row("SELECT count(*) FROM consumed", [], |r| r.get(0))?; + let evidence: u64 = + consumption.query_row("SELECT count(*) FROM execution_evidence", [], |r| r.get(0))?; + let helper_count: u64 = helper.query_row("SELECT count(*) FROM consumed", [], |r| r.get(0))?; + ensure!( + count == 1 && evidence == 1 && helper_count == 0, + "completion original consumption inventory" + ); + let (start,outcome,result):(Vec,Vec,Vec)=consumption.query_row("SELECT e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=? AND c.agent=? AND c.generation=? AND c.job=? AND c.attempt=?",params![grant,binding.agent_id.to_string(),binding.enrollment_generation,scope.job_id.to_string(),scope.attempt_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?; + let start: Value = serde_json::from_slice(&start)?; + let request: Request = serde_json::from_value(start["request"].clone())?; + verify(binding, &request.permit_bytes, &request.signature)?; + verify(helper_binding, &request.permit_bytes, &request.signature)?; + let g: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?; + ensure!( + g.domain == "rmm.execution-permit" + && g.schema_version == 1 + && g.agent_update_plan_id.is_none() + && g.start_before - g.not_before <= chrono::Duration::seconds(60) + && request.job_bytes == offer.payload_bytes + && request.authorization_id.to_string() == offer.authorization_id + && request.plan_hash == scope.plan_hash + && g.grant_id.to_string() == grant + && g.plan_hash == scope.plan_hash + && g.authorization_id == request.authorization_id + && g.job_payload_hash == scope.job_payload_hash + && (g.tenant_id, g.asset_id, g.agent_id, g.job_id, g.attempt_id) + == ( + scope.tenant_id, + scope.asset_id, + scope.agent_id, + scope.job_id, + scope.attempt_id + ) + && (g.enrollment_generation, g.assignment_version) + == (scope.enrollment_generation, scope.assignment_version) + && g.execution_identity == "agent_service" + && g.action == "run_script" + && g.not_before >= scope.not_before + && g.start_before <= scope.start_before + && g.not_before < g.start_before + && g.max_runtime_seconds == scope.max_runtime_seconds, + "completion retained signed grant" + ); + let outcome: Value = serde_json::from_slice(&outcome)?; + let result: Value = serde_json::from_slice(&result)?; + ensure!( + outcome == result && successful_outcome(&outcome), + "completion exact native outcome" + ); + let boot_id = serde_json::from_value(start["previous_boot_id"].clone())?; + let w = Witness { + scope, + probe_receipt_id: probe.receipt_id, + probe_receipt_sha256: hash(&old.payload), + probe_signature_sha256: hash(&old.signature), + grant_id: g.grant_id, + grant_payload_sha256: hash(&request.permit_bytes), + grant_signature_sha256: hash(&request.signature), + outcome_sha256: inventory_sha256(&outcome)?, + boot_id, + }; + ensure!(w.valid(), "completion witness profile"); + Ok(w) +} +pub struct LocalPair<'a> { + pub consumption: &'a Connection, + pub helper: &'a Connection, + pub binding: &'a Binding, + pub helper_binding: &'a Binding, +} +pub fn apply( + db: &mut Connection, + pair: LocalPair<'_>, + raw: &[u8], + boot: uuid::Uuid, + now: DateTime, +) -> Result<()> { + let LocalPair { + consumption, + helper, + binding, + helper_binding, + } = pair; + let r = receipt(raw, binding)?; + let signed: SignedReceipt = serde_json::from_slice(raw)?; + verify(helper_binding, &signed.payload, &signed.signature)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let expected = witness(&tx, consumption, helper, binding, helper_binding)?; + ensure!( + r.witness == expected && expected.boot_id == boot, + "completion differs from native evidence" + ); + let (scope, original) = crate::echo_probe::archive(&tx, binding)?.context("original scope")?; + if installed(&tx, binding, &scope, &original)? { + let prior: Vec = tx.query_row( + "SELECT original_receipt FROM windows_echo_scope_completion WHERE id=1", + [], + |r| r.get(0), + )?; + ensure!(prior == raw, "different completion already applied"); + return Ok(()); + } + ensure!(r.valid(now), "completion expired or premature"); + for sql in schema() { + tx.execute_batch(&sql)?; + } + tx.execute( + "INSERT INTO windows_echo_scope_completion VALUES(1,?,?,?)", + params![raw, r.witness_sha256, now.to_rfc3339()], + )?; + crate::echo_probe::retire_triggers(&tx)?; + ensure!( + crate::echo_probe::installed(&tx, binding)?.is_none(), + "completion did not retire additional scope" + ); + tx.commit()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::{Signer, SigningKey}; + use rmm_domain::{ + jobs::{Action, PlanPayload, PlannedJob, WindowsExecutionProfile}, + windows_echo_probe as echo, + }; + use uuid::Uuid; + #[test] + fn scope_retirement_is_append_only_and_does_not_rewrite_history() -> Result<()> { + let key = SigningKey::from_bytes(&[24; 32]); + let now = Utc::now(); + let binding = Binding { + tenant_id: echo::TENANT, + asset_id: echo::ASSET, + agent_id: echo::AGENT, + enrollment_generation: 1, + assignment_version: 1, + public_key_hex: key + .verifying_key() + .to_bytes() + .iter() + .map(|b| format!("{b:02x}")) + .collect(), + }; + let job = JobPayload { + schema_version: 1, + tenant_id: echo::TENANT, + asset_id: echo::ASSET, + agent_id: echo::AGENT, + enrollment_generation: 1, + assignment_version: 1, + job_id: Uuid::new_v4(), + attempt_id: Uuid::new_v4(), + action: Action::RunScript { + interpreter: "powershell".into(), + script_utf8: echo::SCRIPT.into(), + arguments: vec![], + expected_stdout: Some(echo::OUTPUT.into()), + windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned), + privileged_script_profile: None, + }, + execution_identity: "agent_service".into(), + not_before: now, + start_before: now + chrono::Duration::minutes(15), + max_runtime_seconds: 60, + max_output_bytes: 65536, + }; + let job_bytes = serde_json::to_vec(&job)?; + let plan = PlanPayload { + schema_version: 1, + tenant_id: echo::TENANT, + plan_id: Uuid::new_v4(), + principal: format!("automation:{}", echo::TENANT), + reason: "fixture".into(), + jobs: vec![PlannedJob { + payload: job.clone(), + job_payload_hash: hash(&job_bytes), + script_sha256: Some(hash(echo::SCRIPT.as_bytes())), + }], + max_parallel: 1, + halt_after_failures: 1, + recipe_references: vec![], + artifact_references: vec![], + }; + let scope = ProbeScope::from_plan(&plan, Uuid::new_v4()).context("fixture fixed scope")?; + let probe = ProbeReceipt { + domain: echo::DOMAIN.into(), + schema_version: 1, + request_id: Uuid::new_v4(), + receipt_id: Uuid::new_v4(), + witness: Value::Null, + witness_sha256: "0".repeat(64), + scope: scope.clone(), + scope_sha256: scope.digest().unwrap(), + job_payload_bytes: job_bytes.clone(), + key_id: hash(&key.verifying_key().to_bytes()), + issued_at: now, + valid_until: now + chrono::Duration::minutes(10), + confirmed_by: echo::TEST_PRINCIPAL.into(), + approval_origin: "dev_test_browser_simulation".into(), + testsimulation: true, + }; + let probe_payload = serde_json::to_vec(&probe)?; + let old = SignedReceipt { + signature: key.sign(&probe_payload).to_bytes().to_vec(), + payload: probe_payload, + }; + let original = serde_json::to_vec(&old)?; + let mut db = Connection::open_in_memory()?; + db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT);CREATE TABLE original_history(raw BLOB);INSERT INTO original_history VALUES(x'00ff2a')")?; + let tx = db.transaction()?; + crate::echo_probe::install(&tx, &scope, &job_bytes, &original)?; + tx.commit()?; + let w = Witness { + scope: scope.clone(), + probe_receipt_id: probe.receipt_id, + probe_receipt_sha256: hash(&old.payload), + probe_signature_sha256: hash(&old.signature), + grant_id: Uuid::new_v4(), + grant_payload_sha256: "1".repeat(64), + grant_signature_sha256: "2".repeat(64), + outcome_sha256: "3".repeat(64), + boot_id: Uuid::new_v4(), + }; + let r = Receipt { + domain: rmm_domain::windows_echo_completion::DOMAIN.into(), + schema_version: 1, + receipt_id: Uuid::new_v4(), + witness_sha256: w.digest().unwrap(), + witness: w, + key_id: hash(&key.verifying_key().to_bytes()), + issued_at: now, + valid_until: now + chrono::Duration::minutes(10), + confirmed_by: echo::TEST_PRINCIPAL.into(), + approval_origin: "dev_test_browser_simulation".into(), + testsimulation: true, + ready: false, + helper_ready: false, + unlock: false, + }; + let seal = |r: &Receipt| -> Result> { + let payload = serde_json::to_vec(r)?; + Ok(serde_json::to_vec(&SignedReceipt { + signature: key.sign(&payload).to_bytes().to_vec(), + payload, + })?) + }; + let raw = seal(&r)?; + for field in 0..4 { + let mut bad = r.clone(); + match field { + 0 => bad.ready = true, + 1 => bad.helper_ready = true, + 2 => bad.unlock = true, + _ => bad.testsimulation = false, + }; + assert!(receipt(&seal(&bad)?, &binding).is_err()); + } + assert!( + receipt( + &raw, + &Binding { + public_key_hex: "00".repeat(32), + ..binding.clone() + } + ) + .is_err() + ); + assert!(!installed(&db, &binding, &scope, &original)?); + let tx = db.transaction()?; + for sql in schema() { + tx.execute_batch(&sql)?; + } + tx.execute( + "INSERT INTO windows_echo_scope_completion VALUES(1,?,?,?)", + params![raw, r.witness_sha256, now.to_rfc3339()], + )?; + crate::echo_probe::retire_triggers(&tx)?; + tx.commit()?; + assert!(installed(&db, &binding, &scope, &original)?); + crate::echo_probe::check(&db, &scope, &job_bytes, &original)?; + assert_eq!( + db.query_row("SELECT raw FROM original_history", [], |r| r + .get::<_, Vec>(0))?, + vec![0, 255, 42] + ); + for sql in [ + "DELETE FROM windows_echo_scope_completion", + "UPDATE windows_echo_scope_completion SET applied_at='other'", + "INSERT OR REPLACE INTO windows_echo_scope_completion SELECT * FROM windows_echo_scope_completion", + "DELETE FROM windows_echo_probe_scope", + ] { + assert!(db.execute(sql, []).is_err()); + } + let tx = db.transaction()?; + tx.execute_batch("DROP TRIGGER windows_echo_completion_no_change")?; + assert!(installed(&tx, &binding, &scope, &original).is_err()); + tx.rollback()?; + let mut changed = scope.clone(); + changed.attempt_id = Uuid::new_v4(); + assert!(installed(&db, &binding, &changed, &original).is_err()); + Ok(()) + } +} diff --git a/crates/agent-windows/src/echo_probe.rs b/crates/agent-windows/src/echo_probe.rs index ea40823..1ebe23c 100644 --- a/crates/agent-windows/src/echo_probe.rs +++ b/crates/agent-windows/src/echo_probe.rs @@ -24,17 +24,26 @@ const IMMUTABLE: &str = "CREATE TRIGGER windows_echo_probe_no_change BEFORE UPDA const RETAIN: &str = "CREATE TRIGGER windows_echo_probe_no_delete BEFORE DELETE ON windows_echo_probe_scope BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END"; const BOUND: &str = "WHEN NOT EXISTS(SELECT 1 FROM windows_echo_probe_scope s WHERE s.id=1 AND s.job=NEW.job AND s.attempt=NEW.attempt AND typeof(NEW.offer)='blob' AND length(NEW.offer)=length(s.prefix)+36+length(s.suffix) AND substr(NEW.offer,1,length(s.prefix))=s.prefix AND substr(NEW.offer,-length(s.suffix))=s.suffix) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_OFFER_OUT_OF_SCOPE'); END"; -fn schema() -> [String; 6] { +fn schema(completed: bool) -> [String; 6] { + let bound = if completed { + BOUND.replacen( + "WHEN ", + "WHEN NOT EXISTS(SELECT 1 FROM windows_echo_scope_completion WHERE id=1) AND ", + 1, + ) + } else { + BOUND.to_owned() + }; [ POLICY.to_owned(), "CREATE TRIGGER windows_echo_probe_no_replace BEFORE INSERT ON windows_echo_probe_scope WHEN EXISTS(SELECT 1 FROM windows_echo_probe_scope) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END".to_owned(), IMMUTABLE.to_owned(), RETAIN.to_owned(), format!( - "CREATE TRIGGER windows_echo_probe_offer_insert BEFORE INSERT ON job_attempts {BOUND}" + "CREATE TRIGGER windows_echo_probe_offer_insert BEFORE INSERT ON job_attempts {bound}" ), format!( - "CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {BOUND}" + "CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {bound}" ), ] } @@ -82,7 +91,7 @@ pub fn install( review: &[u8], ) -> Result<()> { let (prefix, suffix) = blobs(scope, payload)?; - for sql in schema() { + for sql in schema(false) { tx.execute_batch(&sql)?; } tx.execute( @@ -100,7 +109,12 @@ pub fn install( } pub fn check(db: &Connection, scope: &ProbeScope, payload: &[u8], review: &[u8]) -> Result<()> { let (prefix, suffix) = blobs(scope, payload)?; - for (name, expected) in OBJECTS.iter().zip(schema()) { + let completed: bool = db.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='windows_echo_scope_completion')", + [], + |r| r.get(0), + )?; + for (name, expected) in OBJECTS.iter().zip(schema(completed)) { let actual: String = db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| { r.get(0) @@ -115,6 +129,20 @@ pub fn installed( db: &Connection, binding: &rmm_agent_core::auth::Binding, ) -> Result> { + let Some((scope, raw)) = archive(db, binding)? else { + return Ok(None); + }; + if crate::echo_completion::installed(db, binding, &scope, &raw)? { + return Ok(None); + } + Ok(Some(scope)) +} + +/// Verify the retained original, including after the separately reviewed completion. +pub fn archive( + db: &Connection, + binding: &rmm_agent_core::auth::Binding, +) -> Result)>> { use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier}; use rmm_domain::{ checkpoint_repair::SignedReceipt, windows_echo_probe::ProbeReceipt, @@ -141,7 +169,17 @@ pub fn installed( "Echo archive signature" ); check(db, &r.scope, &r.job_payload_bytes, &raw)?; - Ok(Some(r.scope)) + Ok(Some((r.scope, raw))) +} + +pub(crate) fn retire_triggers(tx: &Transaction<'_>) -> Result<()> { + for name in &OBJECTS[4..] { + tx.execute_batch(&format!("DROP TRIGGER {name}"))?; + } + for ddl in &schema(true)[4..] { + tx.execute_batch(ddl)?; + } + Ok(()) } pub fn permits_offer(scope: &ProbeScope, offer: &JobOffer, job: &JobPayload) -> bool { scope.matches_job(job) diff --git a/crates/agent-windows/src/helper_runtime.rs b/crates/agent-windows/src/helper_runtime.rs index 8e9ed26..b16546d 100644 --- a/crates/agent-windows/src/helper_runtime.rs +++ b/crates/agent-windows/src/helper_runtime.rs @@ -26,6 +26,8 @@ const PROBE_FILE: &str = "helper-probe.json"; pub struct Client { pin: ipc::Pin, lane: Arc, + qualified_capabilities: Vec, + probed_at: Option, } pub struct ControlSnapshot { pub raw: Snapshot, @@ -73,7 +75,7 @@ impl Client { "HELPER_JOB_BINDING_MISMATCH" ); } - Ok(Some(Self { pin, lane })) + Ok(Some(Self { pin, lane, qualified_capabilities:vec![], probed_at:None })) } pub async fn refresh( agent_id: String, @@ -89,8 +91,8 @@ impl Client { tokio::task::spawn_blocking(move || { let _permit = permit; let result=(|| { - let client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane).context(ipc::Stage::DiscoverPin)?; - if let Some(client)=&client {client.probe_blocking(&state)?;} + let mut client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane).context(ipc::Stage::DiscoverPin)?; + if let Some(client)=&mut client {client.probe_blocking(&state)?;} Ok(client) })(); if result.is_err() || matches!(&result,Ok(None)) && state.join(PROBE_FILE).try_exists()? { @@ -338,7 +340,7 @@ impl Client { }) .await? } - fn probe_blocking(&self, state: &Path) -> Result<()> { + fn probe_blocking(&mut self, state: &Path) -> Result<()> { self.check_pin().context(ipc::Stage::DiscoverPin)?; let pin = &self.pin; let call = ipc::Call::new(pin, ipc::Operation::Probe {}); @@ -357,8 +359,16 @@ impl Client { }; let value = json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_service":crate::SERVICE_NAME,"agent_id":pin.binding.agent_id,"asset_id":pin.binding.asset_id,"challenge":reply.challenge,"observed_at":chrono::Utc::now(),"helper_service":ipc::HELPER_SERVICE,"verified_helper_user_sid":pin.helper.user_sid,"verified_helper_service_sid":pin.helper.service_sid,"helper_binary_sha256":reply.helper_binary_sha256,"policy_sha256":reply.policy_sha256,"authenticated_pipe_exchange":true,"client_service_pid_verified_by_helper":true,"ledger_file_id":ledger,"executor_lock_file_id":lock,"helper_clock_qualified":clock_qualified,"helper_ready":ready,"system_capability_advertised":false,"no_jobs":true}); self.check_pin()?; + self.qualified_capabilities=crate::system_capabilities::qualified(pin,clock_qualified)?; + self.probed_at=Some(std::time::Instant::now()); + let mut value=value; + value["system_capability_advertised"]=json!(!self.qualified_capabilities.is_empty()); + value["qualified_capabilities"]=json!(self.qualified_capabilities); write_current_probe(state, &value).context(ipc::Stage::ClientReport) } + pub fn qualified_capabilities(&self) -> Vec { + if self.probed_at.is_some_and(|at|at.elapsed()<=Duration::from_secs(90)) {self.qualified_capabilities.clone()} else {vec![]} + } /// Pure admission shape only; no capability or qualification is asserted. pub fn supports_system(&self, job: &JobPayload) -> bool { system_shape(job) diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs index 14c80aa..f3f652e 100644 --- a/crates/agent-windows/src/lib.rs +++ b/crates/agent-windows/src/lib.rs @@ -6,6 +6,9 @@ pub mod certificate_rotation; #[cfg(windows)] pub mod clock; pub mod echo_probe; +pub mod echo_completion; +#[cfg(all(windows, feature = "system-helper"))] +pub mod system_capabilities; pub mod event_log; #[cfg(windows)] pub mod event_log_job; @@ -32,6 +35,8 @@ pub mod service; pub mod signed_clock; #[cfg(all(windows, feature = "system-helper"))] mod system_script; +#[cfg(feature = "system-helper")] +pub mod update_native; pub const SERVICE_NAME: &str = "RmmDiscoveryWindows"; pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"]; diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index 4df0bc2..f60d933 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -49,6 +49,42 @@ struct Config { )] windows_execution_profile: Option, } +/// Local TLS maintenance evidence only. It never restores readiness; after +/// renewal both roles must pass their ordinary fresh signed synchronization. +#[derive(serde::Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct RotationIdleAdmission { + schema_version: u32, + agent_id: String, + binding_sha256: String, + boot_id: String, + journal_file_id: [u32; 3], + ledger_file_id: [u32; 3], + history_sha256: String, + helper_pin_sha256: Option, + helper_anchor_sha256: Option, + intent_file_id: Option<[u32; 3]>, +} +fn rotation_file_id(path: &Path) -> Result<[u32; 3]> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle, + }; + native::private_path(path, false)?; + let file = fs::File::open(path)?; + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: live file handle and correctly sized writable native structure. + ensure!( + unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0 + && info.nNumberOfLinks == 1, + "ROTATION_FILE_IDENTITY" + ); + Ok([ + info.dwVolumeSerialNumber, + info.nFileIndexHigh, + info.nFileIndexLow, + ]) +} impl Config { fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool { self.enable_jobs @@ -536,6 +572,137 @@ struct Agent { deferred_permit: Option<(u64, ExecutionPermit)>, } impl Agent { + fn rotation_without_effects(&self) -> Result<()> { + ensure!( + self.running.is_none() && self.deferred_permit.is_none() && !self.prepared, + "ROTATION_BUSY" + ); + let idle: bool = self.journal.connection().query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired'))", [], |r| r.get(0))?; + ensure!(idle, "ROTATION_EFFECT_UNRESOLVED"); + if let Some(ledger) = &self.ledger { + let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL)", [], |r| r.get(0))?; + ensure!(resolved, "ROTATION_CONSUMPTION_UNRESOLVED"); + } + #[cfg(feature = "system-helper")] + { + ensure!( + self.helper_control.is_none() + && self.helper_probe.is_none() + && !self.helper_apply_unconfirmed, + "ROTATION_HELPER_CONTROL_PENDING" + ); + if Path::new(rmm_agent_windows::helper_runtime::intent::DB).try_exists()? { + let intents = rmm_agent_windows::helper_runtime::intent::Store::open(false)?; + ensure!( + intents.pending()?.is_empty(), + "ROTATION_SYSTEM_DELEGATION_PENDING" + ); + } + } + Ok(()) + } + fn rotation_admission( + &self, + generation: Option, + retained: Option<&[u8]>, + ) -> Result> { + self.rotation_without_effects()?; + let old: Option = + retained.map(serde_json::from_slice).transpose()?; + if let Some(generation) = generation { + #[cfg(feature = "system-helper")] + let helper_present = self.helper.is_some(); + #[cfg(not(feature = "system-helper"))] + let helper_present = false; + ensure!( + self.ready_identity(generation, helper_present), + "ROTATION_SIGNED_IDLE_REQUIRED" + ); + } else { + ensure!( + self.fence.generation.load(Ordering::SeqCst) == 0 && old.is_some(), + "ROTATION_PENDING_IDLE_ADMISSION_REQUIRED" + ); + } + #[cfg(feature = "system-helper")] + let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = { + use rmm_agent_windows::helper_runtime::{Client, intent}; + let helper = Client::discover( + &self.identity.agent_id, + &self.identity.asset_id, + self.binding.as_ref(), + self.helper_lane.clone(), + )?; + let pin = helper.as_ref().map(|h| { + format!( + "{:x}", + Sha256::digest( + format!("{}:{}", h.pin_hash(), h.helper_binary_hash()).as_bytes() + ) + ) + }); + let anchor = if helper.is_some() { + if generation.is_some() { + Some(format!( + "{:x}", + Sha256::digest(serde_json::to_vec( + self.helper_anchor + .as_ref() + .context("ROTATION_HELPER_ANCHOR_REQUIRED")? + )?) + )) + } else { + let saved = old + .as_ref() + .and_then(|a| a.helper_anchor_sha256.clone()) + .context("ROTATION_RETAINED_HELPER_ANCHOR_REQUIRED")?; + ensure!( + saved.len() == 64 && saved.bytes().all(|b| b.is_ascii_hexdigit()), + "ROTATION_RETAINED_HELPER_ANCHOR_INVALID" + ); + Some(saved) + } + } else { + None + }; + let file = Path::new(intent::DB) + .try_exists()? + .then(|| rotation_file_id(Path::new(intent::DB))) + .transpose()?; + (pin, anchor, file) + }; + #[cfg(not(feature = "system-helper"))] + let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = (None, None, None); + let admission = RotationIdleAdmission { + schema_version: 1, + agent_id: self.identity.agent_id.clone(), + binding_sha256: format!( + "{:x}", + Sha256::digest(serde_json::to_vec( + self.binding.as_ref().context("ROTATION_BINDING_REQUIRED")? + )?) + ), + boot_id: self.boot.clone(), + journal_file_id: rotation_file_id( + &self.config.state_directory.join("telemetry.sqlite"), + )?, + ledger_file_id: rotation_file_id( + &self.config.state_directory.join("consumption.sqlite"), + )?, + history_sha256: rmm_agent_windows::certificate_rotation::idle_history_sha256( + self.journal.connection(), + self.ledger.as_ref().context("ROTATION_LEDGER_REQUIRED")?, + )?, + helper_pin_sha256, + helper_anchor_sha256, + intent_file_id, + }; + ensure!( + old.as_ref().is_none_or(|saved| saved == &admission), + "ROTATION_IDLE_STATE_CHANGED" + ); + Ok(serde_json::to_vec(&admission)?) + } #[cfg(feature = "system-helper")] fn start_time_refresh( &mut self, @@ -958,6 +1125,12 @@ impl Agent { caps.push(rmm_agent_windows::actions::REMOTE_SIGNED_PROFILE_CAPABILITY.into()); } } + #[cfg(feature = "system-helper")] + if !self.config.windows_echo_probe_only + && let Some(helper) = &self.helper + { + caps.extend(helper.qualified_capabilities()); + } } caps } @@ -1679,11 +1852,16 @@ impl Agent { // Server commit may have fenced Hello even if its HTTP response was // lost. Recover the durable original CSR before requiring any channel. if self.certificates.has_pending(self.journal.connection())? { - ensure!( - !self.config.enable_jobs, - "ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY" - ); - self.renew_certificate().await?; + let admission = if self.config.enable_jobs { + let retained = self + .certificates + .pending_idle_admission(self.journal.connection())? + .context("ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY")?; + Some(self.rotation_admission(None, Some(&retained))?) + } else { + None + }; + self.renew_certificate(admission.as_deref()).await?; } self.boot = native::boot_id().await?; let advertised = self.capabilities(); @@ -1747,6 +1925,7 @@ impl Agent { let mut inventory = Instant::now(); let mut update_at = Instant::now(); let mut rotation_at = Instant::now(); + let mut rotation_after = Duration::from_secs(30); let mut heartbeat = Instant::now() - Duration::from_secs(60); let mut heartbeat_after = Duration::from_secs(30); let mut tick = tokio::time::interval(Duration::from_secs(1)); @@ -1834,19 +2013,32 @@ impl Agent { if stop.load(Ordering::SeqCst) { continue; } - // This slice renews only passive clients. Job admission and helper - // lifecycle are not extended by certificate maintenance. - if !self.config.enable_jobs && rotation_at.elapsed() >= Duration::from_secs(30) { + // Certificate maintenance cannot interrupt accepted, ambiguous or + // live work. Active rotation also retains its exact signed-idle + // context for a closed, effect-free retry after response loss. + if rotation_at.elapsed() >= rotation_after { rotation_at = Instant::now(); + rotation_after = Duration::from_secs(30); let now = Utc::now().timestamp(); if self .certificates .due(self.journal.connection(), &self.key_files, now)? { - self.renew_certificate().await?; - // The server fences the previous connection generation. - // A new Hello/Sync uses the newly selected pair. - return Ok(()); + let admission = if self.config.enable_jobs { + self.rotation_admission(Some(generation), None).map(Some) + } else { + self.rotation_without_effects().map(|()| None) + }; + if let Ok(admission) = admission { + self.renew_certificate(admission.as_deref()).await?; + // No offers are processed during renewal. The server + // fences this channel; fresh Hello/Sync must qualify + // both roles again before any subsequent job starts. + return Ok(()); + } + // Avoid phase-locking a due renewal to the 30s helper + // probe cadence. Busy work keeps its guard and continues. + rotation_after = Duration::from_secs(1); } } if heartbeat.elapsed() >= heartbeat_after { @@ -1901,13 +2093,23 @@ impl Agent { } Ok(()) } - async fn renew_certificate(&mut self) -> Result<()> { - ensure!(!self.config.enable_jobs, "PASSIVE_RENEWAL_ONLY"); + async fn renew_certificate(&mut self, admission: Option<&[u8]>) -> Result<()> { + self.rotation_without_effects()?; + ensure!( + !self.config.enable_jobs || admission.is_some(), + "ROTATION_ACTIVE_IDLE_REQUIRED" + ); self.close_gate(); - let request = self.certificates.prepare( + #[cfg(feature = "system-helper")] + self.stop_time_refresh().await; + if self.config.enable_jobs { + self.rotation_admission(None, admission)?; + } + let request = self.certificates.prepare_with_idle_admission( self.journal.connection_mut(), &self.key_files, Utc::now().timestamp(), + admission, )?; let client = crate::https_channel::mtls_client( self.config.connect_address, diff --git a/crates/agent-windows/src/system_capabilities.rs b/crates/agent-windows/src/system_capabilities.rs new file mode 100644 index 0000000..4bf5c1e --- /dev/null +++ b/crates/agent-windows/src/system_capabilities.rs @@ -0,0 +1,154 @@ +//! Operator-provisioned native qualification intersected with a live authenticated helper. +//! A source build or a permissive policy by itself cannot publish SYSTEM capabilities. +use crate::{ + helper_ipc::{self as ipc, Pin, PinnedFile}, + helper_system, +}; +use anyhow::{Result, ensure}; +use serde::Deserialize; +use std::{collections::BTreeSet, io::Read, path::Path}; +use uuid::Uuid; + +pub const PATH: &str = r"C:\ProgramData\RustDiscoverySystem\system-qualification.json"; +pub const RESULT_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\system-native-result.json"; +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Qualification { + schema_version: u32, + tenant_id: Uuid, + asset_id: Uuid, + agent_id: Uuid, + enrollment_generation: u64, + assignment_version: u64, + agent_binary_sha256: String, + helper_binary_sha256: String, + policy_sha256: String, + native_result_sha256: String, + qualification_reference: Uuid, + actions: Vec, +} +pub fn qualified(pin: &Pin, clock_qualified: bool) -> Result> { + if !clock_qualified || !Path::new(PATH).try_exists()? { + return Ok(vec![]); + } + let readers = [ + ipc::service_sid(crate::SERVICE_NAME)?, + ipc::service_sid(ipc::HELPER_SERVICE)?, + ]; + let root = Path::new(PATH) + .parent() + .expect("fixed qualification parent"); + let mut dir = PinnedFile::open_read_shared(root, true, &readers, &[])?; + let mut file = PinnedFile::open(Path::new(PATH), false, &readers, &[], false)?; + let mut bytes = vec![]; + (&mut file.file).take(16385).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= 16384, "system qualification size"); + file.check()?; + dir.check()?; + let q: Qualification = serde_json::from_slice(&bytes)?; + ensure!( + q.schema_version == 1 + && ( + q.tenant_id, + q.asset_id, + q.agent_id, + q.enrollment_generation, + q.assignment_version + ) == ( + pin.binding.tenant_id, + pin.binding.asset_id, + pin.binding.agent_id, + pin.binding.enrollment_generation, + pin.binding.assignment_version + ) + && q.agent_binary_sha256 == pin.agent.binary_sha256 + && q.helper_binary_sha256 == pin.helper.binary_sha256 + && q.policy_sha256 == pin.policy_sha256 + && ipc::digest(&q.native_result_sha256) + && !q.qualification_reference.is_nil() + && !q.actions.is_empty() + && q.actions.len() <= 3 + && q.actions.iter().collect::>().len() == q.actions.len() + && q.actions.iter().all(|a| matches!( + a.as_str(), + "run_script" | "set_service_state" | "ensure_package" + )), + "system qualification binding" + ); + let mut result = PinnedFile::open(Path::new(RESULT_PATH), false, &readers, &[], false)?; + let mut result_bytes = vec![]; + (&mut result.file) + .take(65537) + .read_to_end(&mut result_bytes)?; + ensure!( + result_bytes.len() <= 65536 + && rmm_domain::jobs::hash(&result_bytes) == q.native_result_sha256, + "system native qualification evidence hash" + ); + result.check()?; + let evidence: serde_json::Value = serde_json::from_slice(&result_bytes)?; + ensure!( + evidence["schema_version"] == 1 + && evidence["platform"] == "windows-x86_64" + && evidence["qualification_reference"] == q.qualification_reference.to_string() + && evidence["helper_binary_sha256"] == q.helper_binary_sha256 + && evidence["validated_actions"] == serde_json::to_value(&q.actions)? + && evidence["status"] == "passed", + "system native qualification evidence profile" + ); + let (settings, _handles) = helper_system::read_settings()?; + ensure!( + serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)? + && settings.enable_effects, + "system qualification effective policy" + ); + let mut caps = vec![ + "helper.system.v1".into(), + format!("helper.binary.sha256:{}", pin.helper.binary_sha256), + format!("helper.policy.sha256:{}", pin.policy_sha256), + ]; + for action in q.actions { + match action.as_str() { + "run_script" => { + ensure!( + settings.schema_version == 3 + && settings.allowed_script_profiles.as_deref() + == Some(&[ + rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1 + ]) + && crate::actions::powershell().is_ok(), + "system script qualification policy" + ); + caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string)); + } + "set_service_state" => { + ensure!( + !settings.allowed_services.is_empty(), + "system SCM qualification policy" + ); + caps.extend(["set_service_state", "system:set_service_state"].map(str::to_string)); + } + "ensure_package" => { + ensure!( + settings.schema_version >= 2 + && settings + .allowed_msi_recipe_sha256 + .as_ref() + .is_some_and(|v| !v.is_empty()) + && crate::msi_cache::stage_configured(), + "system MSI qualification policy" + ); + caps.extend( + [ + "ensure_package", + "system:ensure_package", + rmm_domain::windows_execution::MSI_CAPABILITY, + ] + .map(str::to_string), + ); + } + _ => unreachable!("validated qualification action"), + } + } + Ok(caps) +} diff --git a/crates/agent-windows/src/update_native/fence.rs b/crates/agent-windows/src/update_native/fence.rs new file mode 100644 index 0000000..9ea23e2 --- /dev/null +++ b/crates/agent-windows/src/update_native/fence.rs @@ -0,0 +1,278 @@ +//! File-swap fence against the SAME original guarded SYSTEM helper ledger. +//! Construction never re-enters a partial replacement or creates a handoff. +use super::{ + Budget, DurableEffectFence, Effect, Role, digest, + files::{self, Location, Proof}, +}; +use anyhow::{Result, ensure}; +use rmm_agent_core::{ + reconcile::SyncClock, + update_handoff::{ + self as core, NativeEffect, NativeEffectClaim, NativeFileRole, Participant, + UpdateParticipantGuard, + }, +}; +use rmm_updater_handoff::{Evidence, Handoff, Phase, PinTransition}; +use rusqlite::Connection; + +const ROLES: [Role; 5] = [ + Role::Agent, + Role::Helper, + Role::Settings, + Role::Pin, + Role::TimeProfile, +]; +fn native(role: Role) -> NativeFileRole { + match role { + Role::Agent => NativeFileRole::AgentBinary, + Role::Helper => NativeFileRole::HelperBinary, + Role::Settings => NativeFileRole::WindowsSettings, + Role::Pin => NativeFileRole::WindowsPin, + Role::TimeProfile => NativeFileRole::WindowsTimeProfile, + } +} +pub struct LedgerFence<'a, 'b, G, C> { + db: &'a mut Connection, + guard: &'a G, + clock: &'a C, + budget: &'a Budget<'b>, + original: Handoff, + originals: &'a [Proof; 5], + staged: &'a [Proof; 5], + pending: Option<(Effect, NativeEffectClaim)>, + next: usize, + saved: bool, + poisoned: bool, +} +/// Bindings are independently re-read before effects; parsed/transferred Proof +/// records never substitute for actual protected file identities/bytes. +pub struct Inputs<'a, 'b, G, C> { + pub db: &'a mut Connection, + pub guard: &'a G, + pub clock: &'a C, + pub budget: &'a Budget<'b>, + pub original: &'a Handoff, + pub originals: &'a [Proof; 5], + pub staged: &'a [Proof; 5], +} +impl<'a, 'b, G: UpdateParticipantGuard, C: SyncClock> LedgerFence<'a, 'b, G, C> { + pub fn new(input: Inputs<'a, 'b, G, C>) -> Result { + input.budget.check()?; + input.original.validate()?; + ensure!( + input.original.pin_transition == PinTransition::WindowsCodePairClockV1 + && input.guard.participant() == Participant::StableUpdater, + "UPDATE_WINDOWS_FENCE_ROLE" + ); + let grant = input.original.attempt.grant_id; + let journal = core::read(input.db, input.guard, grant)?; + ensure!( + journal.phase() == Phase::UpdaterOwnsLedger, + "UPDATE_NO_FENCE_RESUME" + ); + // Retained Handoff is immutable and read through the actual executor + // guard. No separately supplied record may stand in for those bytes. + let raw: Vec = input.db.query_row( + "SELECT record FROM agent_update_handoffs WHERE grant_id=?1", + [grant.to_string()], + |r| r.get(0), + )?; + ensure!( + raw == input.original.bytes()?, + "UPDATE_WINDOWS_ORIGINAL_HANDOFF" + ); + for (i, role) in ROLES.iter().copied().enumerate() { + let original = &input.original.files[i]; + ensure!( + original.role == role.handoff_role() + && original.old_sha256 == input.originals[i].sha256 + && original.new_sha256 == input.staged[i].sha256 + && input.originals[i].identity.volume_serial + == input.staged[i].identity.volume_serial + && input.originals[i].identity != input.staged[i].identity + && input.originals[i].security_sha256 == input.staged[i].security_sha256 + && files::observe_bound( + role, + input.original.owner_nonce, + Location::Target, + input.budget + )? == input.originals[i] + && files::observe_bound( + role, + input.original.owner_nonce, + Location::Stage, + input.budget + )? == input.staged[i], + "UPDATE_WINDOWS_SWAP_FILES" + ); + } + Ok(Self { + db: input.db, + guard: input.guard, + clock: input.clock, + budget: input.budget, + original: input.original.clone(), + originals: input.originals, + staged: input.staged, + pending: None, + next: 0, + saved: false, + poisoned: false, + }) + } + fn append(&mut self, evidence: Evidence) -> Result<()> { + self.budget.check()?; + let grant = self.original.attempt.grant_id; + let journal = core::read(self.db, self.guard, grant)?; + let now = self.clock.reading()?.upper; + ensure!( + u64::try_from(now.timestamp())? < self.original.finish_before, + "UPDATE_WINDOWS_DEADLINE" + ); + let bytes = journal.prepare(u64::try_from(now.timestamp())?, evidence)?; + core::append(self.db, self.guard, grant, journal.head_sha256(), &bytes) + } + pub fn finish(mut self) -> Result<()> { + ensure!( + !self.poisoned && self.pending.is_none() && self.next == ROLES.len() && !self.saved, + "UPDATE_WINDOWS_FENCE_INCOMPLETE" + ); + for (i, role) in ROLES.iter().copied().enumerate() { + ensure!( + files::observe_bound( + role, + self.original.owner_nonce, + Location::Target, + self.budget + )? == self.staged[i] + && files::observe_bound( + role, + self.original.owner_nonce, + Location::Previous, + self.budget + )? == self.originals[i], + "UPDATE_WINDOWS_FINAL_PAIR_CHANGED" + ); + } + self.append(Evidence::PairVerified { + pair: self.original.target.clone(), + retained_state_sha256: self.original.retained_state_sha256.clone(), + }) + } +} +impl DurableEffectFence for LedgerFence<'_, '_, G, C> { + fn before_effect(&mut self, effect: &Effect) -> Result<()> { + ensure!( + !self.poisoned && self.pending.is_none() && self.next < ROLES.len(), + "UPDATE_WINDOWS_FENCE_REENTRY" + ); + self.poisoned = true; + self.budget.check()?; + let role = ROLES[self.next]; + let native = match *effect { + Effect::SavePredecessor { role: r } if r == role && !self.saved => { + ensure!( + files::observe_bound( + role, + self.original.owner_nonce, + Location::Target, + self.budget + )? == self.originals[self.next] + && files::observe_bound( + role, + self.original.owner_nonce, + Location::Stage, + self.budget + )? == self.staged[self.next], + "UPDATE_WINDOWS_FILES_CHANGED" + ); + self.append(Evidence::ReplaceIntent { + role: role.handoff_role(), + })?; + NativeEffect::SavePredecessor { role: native(role) } + } + Effect::PublishReplacement { role: r } if r == role && self.saved => { + ensure!( + files::observe_bound( + role, + self.original.owner_nonce, + Location::Previous, + self.budget + )? == self.originals[self.next] + && files::observe_bound( + role, + self.original.owner_nonce, + Location::Stage, + self.budget + )? == self.staged[self.next], + "UPDATE_WINDOWS_FILES_CHANGED" + ); + NativeEffect::PublishReplacement { role: native(role) } + } + _ => anyhow::bail!("UPDATE_WINDOWS_SWAP_FENCE_SCOPE"), + }; + let journal = core::read(self.db, self.guard, self.original.attempt.grant_id)?; + let claim = core::claim_native_effect( + self.db, + self.guard, + self.original.attempt.grant_id, + journal.head_sha256(), + &native, + self.clock.reading()?.upper, + )?; + self.pending = Some((effect.clone(), claim)); + Ok(()) + } + fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> { + let (expected, claim) = self + .pending + .take() + .ok_or_else(|| anyhow::anyhow!("UPDATE_WINDOWS_EFFECT_NOT_CLAIMED"))?; + ensure!( + self.poisoned && *effect == expected, + "UPDATE_WINDOWS_EFFECT_CALLBACK_CHANGED" + ); + self.budget.check()?; + let role = ROLES[self.next]; + let replaced = matches!(effect, Effect::PublishReplacement { .. }); + let proof = files::observe_bound( + role, + self.original.owner_nonce, + if replaced { + Location::Target + } else { + Location::Previous + }, + self.budget, + )?; + ensure!( + proof + == if replaced { + self.staged[self.next].clone() + } else { + self.originals[self.next].clone() + } + && digest(&serde_json::to_vec(&proof)?) == observation, + "UPDATE_WINDOWS_EFFECT_READBACK_CHANGED" + ); + core::observe_native_effect( + self.db, + self.guard, + &claim, + observation, + self.clock.reading()?.upper, + )?; + if replaced { + self.append(Evidence::Replaced { + role: role.handoff_role(), + observed_sha256: proof.sha256, + })?; + self.next += 1; + self.saved = false; + } else { + self.saved = true; + } + self.poisoned = false; + Ok(()) + } +} diff --git a/crates/agent-windows/src/update_native/files.rs b/crates/agent-windows/src/update_native/files.rs new file mode 100644 index 0000000..2458664 --- /dev/null +++ b/crates/agent-windows/src/update_native/files.rs @@ -0,0 +1,576 @@ +//! Fixed-file, same-volume native staging and one-step-at-a-time publication. +//! No archive extraction, free target path, overwrite, replacement of journals, +//! or implicit retry/rollback. A failed rename/readback is an uncertain effect. +use super::{Budget, DurableEffectFence, Effect, Role, digest, valid_digest}; +use crate::{ + helper_ipc::{self as ipc, FileIdentity, PinnedFile}, + job_binding, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::File, + io::{Read, Seek, SeekFrom, Write}, + mem::{offset_of, size_of, zeroed}, + os::windows::{ + ffi::OsStrExt, + io::{AsRawHandle, FromRawHandle}, + }, + path::{Path, PathBuf}, + ptr, +}; +use uuid::Uuid; +use windows_sys::Win32::{ + Foundation::{INVALID_HANDLE_VALUE, LocalFree}, + Security::{ + self, + Authorization::{GetSecurityInfo, SE_FILE_OBJECT}, + SECURITY_ATTRIBUTES, + }, + Storage::FileSystem::*, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Proof { + pub identity: FileIdentity, + pub bytes: u64, + pub sha256: String, + pub security_sha256: String, +} +/// All ancestors remain open without DELETE sharing. The protected immediate +/// directory also remains pinned by file identity/owner/DACL throughout effects. +struct Directory { + root: PinnedFile, + ancestors: Vec, +} +fn regular(file: &File, directory: bool) -> Result<()> { + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; + ensure!( + unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0 + && info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 + && (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory + && (directory || info.nNumberOfLinks == 1), + "UPDATE_NONREGULAR_FILE" + ); + Ok(()) +} +fn open( + path: &Path, + desired: u32, + creation: u32, + security: *const SECURITY_ATTRIBUTES, +) -> Result { + let handle = unsafe { + CreateFileW( + ipc::wide(path).as_ptr(), + desired, + FILE_SHARE_READ, + security, + creation, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, + ptr::null_mut(), + ) + }; + ensure!( + handle != INVALID_HANDLE_VALUE, + "UPDATE_NATIVE_FILE_OPEN: {}", + std::io::Error::last_os_error() + ); + let file = unsafe { File::from_raw_handle(handle) }; + regular(&file, false)?; + Ok(file) +} +impl Directory { + fn open(role: Role) -> Result { + let path = Path::new(role.target()) + .parent() + .context("UPDATE_TARGET_DIRECTORY")?; + let readers = vec![ + ipc::service_sid(crate::SERVICE_NAME)?, + ipc::service_sid(ipc::HELPER_SERVICE)?, + ]; + let root = PinnedFile::open_read_shared(path, true, &readers, &[])?; + let mut ancestors = Vec::new(); + for ancestor in path.ancestors().skip(1) { + let raw = unsafe { + CreateFileW( + ipc::wide(ancestor).as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + }; + ensure!(raw != INVALID_HANDLE_VALUE, "UPDATE_ANCESTOR_OPEN"); + let file = unsafe { File::from_raw_handle(raw) }; + regular(&file, true)?; + ancestors.push(file); + } + Ok(Self { root, ancestors }) + } + fn check(&mut self) -> Result<()> { + self.root.check()?; + for ancestor in &self.ancestors { + regular(ancestor, true)?; + } + Ok(()) + } + fn child(&self, name: &str) -> PathBuf { + self.root.path.join(name) + } +} +struct SecurityDescriptor(*mut core::ffi::c_void); +impl Drop for SecurityDescriptor { + fn drop(&mut self) { + unsafe { + LocalFree(self.0); + } + } +} +impl SecurityDescriptor { + fn read(file: &File) -> Result { + let mut descriptor = ptr::null_mut(); + ensure!( + unsafe { + GetSecurityInfo( + file.as_raw_handle(), + SE_FILE_OBJECT, + Security::OWNER_SECURITY_INFORMATION + | Security::GROUP_SECURITY_INFORMATION + | Security::DACL_SECURITY_INFORMATION, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + &mut descriptor, + ) + } == 0 + && !descriptor.is_null(), + "UPDATE_FILE_SECURITY" + ); + Ok(Self(descriptor)) + } + fn hash(&self) -> Result { + let mut owner = ptr::null_mut(); + let mut group = ptr::null_mut(); + let mut defaulted = 0; + let mut present = 0; + let mut acl = ptr::null_mut(); + let mut control = 0; + let mut revision = 0; + ensure!( + unsafe { + Security::GetSecurityDescriptorOwner(self.0, &mut owner, &mut defaulted) != 0 + && Security::GetSecurityDescriptorGroup(self.0, &mut group, &mut defaulted) != 0 + && Security::GetSecurityDescriptorDacl( + self.0, + &mut present, + &mut acl, + &mut defaulted, + ) != 0 + && Security::GetSecurityDescriptorControl(self.0, &mut control, &mut revision) + != 0 + } && !owner.is_null() + && !group.is_null() + && present != 0 + && !acl.is_null(), + "UPDATE_FILE_SECURITY_PARTS" + ); + // Only actual owner, group, ACL bytes and inheritance protection are + // hashed. Windows may clear the informational AUTO_INHERITED bit when + // creating an explicitly protected object; that bit grants no rights. + let mut bytes = Vec::new(); + for sid in [owner, group] { + let len = unsafe { Security::GetLengthSid(sid) }; + ensure!((8..=256).contains(&len), "UPDATE_SECURITY_SID_SIZE"); + bytes.extend_from_slice(&len.to_le_bytes()); + bytes.extend_from_slice(unsafe { + std::slice::from_raw_parts(sid.cast::(), len as usize) + }); + } + let len = unsafe { (*acl).AclSize }; + ensure!( + (size_of::() as u16..=32768).contains(&len), + "UPDATE_SECURITY_ACL_SIZE" + ); + bytes.extend_from_slice(&(control & Security::SE_DACL_PROTECTED).to_le_bytes()); + bytes.extend_from_slice(unsafe { + std::slice::from_raw_parts(acl.cast::(), len as usize) + }); + Ok(digest(&bytes)) + } + fn attributes(&self) -> SECURITY_ATTRIBUTES { + SECURITY_ATTRIBUTES { + nLength: size_of::() as u32, + lpSecurityDescriptor: self.0, + bInheritHandle: 0, + } + } +} +fn hash_file(file: &mut File, max: u64) -> Result { + ensure!((1..=256 * 1024 * 1024).contains(&max), "UPDATE_FILE_LIMIT"); + file.seek(SeekFrom::Start(0))?; + let mut hash = Sha256::new(); + let mut count = 0u64; + let mut buf = [0u8; 65536]; + loop { + let read = file.read(&mut buf)?; + if read == 0 { + break; + } + count = count + .checked_add(read as u64) + .context("UPDATE_FILE_LIMIT")?; + ensure!(count <= max, "UPDATE_FILE_LIMIT"); + hash.update(&buf[..read]); + } + Ok(format!("{:x}", hash.finalize())) +} +fn proof(file: &mut File, path: &Path, max: u64) -> Result { + regular(file, false)?; + job_binding::check_admin_readonly(path)?; + let identity = ipc::file_identity(file)?; + let bytes = file.metadata()?.len(); + ensure!(bytes > 0 && bytes <= max, "UPDATE_FILE_SIZE"); + let security_sha256 = SecurityDescriptor::read(file)?.hash()?; + let sha256 = hash_file(file, max)?; + regular(file, false)?; + ensure!( + ipc::file_identity(file)? == identity + && file.metadata()?.len() == bytes + && SecurityDescriptor::read(file)?.hash()? == security_sha256, + "UPDATE_FILE_CHANGED_DURING_READ" + ); + let named = unsafe { + CreateFileW( + ipc::wide(path).as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + }; + ensure!(named != INVALID_HANDLE_VALUE, "UPDATE_FILE_NAME_READBACK"); + let named = unsafe { File::from_raw_handle(named) }; + regular(&named, false)?; + ensure!( + ipc::file_identity(&named)? == identity, + "UPDATE_FILE_NAME_REPLACED" + ); + Ok(Proof { + identity, + bytes, + sha256, + security_sha256, + }) +} +/// Read-only predecessor capture while the original services may still run. +/// This is an observation, not an authenticated InstalledRecord or baseline. +pub fn observe(role: Role, budget: &Budget<'_>) -> Result { + budget.check()?; + let mut directory = Directory::open(role)?; + let mut file = open( + Path::new(role.target()), + FILE_GENERIC_READ, + OPEN_EXISTING, + ptr::null(), + )?; + let value = proof(&mut file, Path::new(role.target()), role.max_bytes())?; + directory.check()?; + budget.check()?; + Ok(value) +} +#[derive(Clone, Copy)] +pub(crate) enum Location { + Target, + Stage, + Previous, +} +/// Independent readback while the actual swap retains DELETE/write handles. +/// Opening this read-only observer grants no write/delete access or authority. +pub(crate) fn observe_bound( + role: Role, + nonce: Uuid, + location: Location, + budget: &Budget<'_>, +) -> Result { + ensure!(!nonce.is_nil(), "UPDATE_READBACK_NONCE"); + budget.check()?; + let mut directory = Directory::open(role)?; + let path = match location { + Location::Target => PathBuf::from(role.target()), + Location::Stage => directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label())), + Location::Previous => { + directory.child(&format!(".rmm-update-{nonce}-{}.previous", role.label())) + } + }; + let raw = unsafe { + CreateFileW( + ipc::wide(&path).as_ptr(), + FILE_GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + }; + ensure!(raw != INVALID_HANDLE_VALUE, "UPDATE_READBACK_OPEN"); + let mut file = unsafe { File::from_raw_handle(raw) }; + let result = proof(&mut file, &path, role.max_bytes())?; + directory.check()?; + budget.check()?; + Ok(result) +} + +pub struct StageDescriptor<'a> { + pub role: Role, + pub owner_nonce: Uuid, + pub original: &'a Proof, + pub replacement_sha256: &'a str, + pub replacement_bytes: u64, +} +pub struct Staged { + role: Role, + nonce: Uuid, + directory: Directory, + path: PathBuf, + file: File, + original: Proof, + staged: Proof, +} +impl Staged { + /// Source is a bounded stream of already independently release-verified + /// artifact bytes. No URL or caller-chosen destination is accepted. Both + /// code files MUST be fully staged before original activation consumption. + pub fn create( + descriptor: StageDescriptor<'_>, + source: &mut impl Read, + budget: &Budget<'_>, + fence: &mut impl DurableEffectFence, + ) -> Result { + let StageDescriptor { + role, + owner_nonce: nonce, + original, + replacement_sha256, + replacement_bytes, + } = descriptor; + ensure!( + !nonce.is_nil() + && valid_digest(&original.sha256) + && valid_digest(replacement_sha256) + && replacement_bytes > 0 + && replacement_bytes <= role.max_bytes(), + "UPDATE_STAGE_DESCRIPTOR" + ); + budget.check()?; + let mut directory = Directory::open(role)?; + let mut predecessor = open( + Path::new(role.target()), + FILE_GENERIC_READ, + OPEN_EXISTING, + ptr::null(), + )?; + ensure!( + proof(&mut predecessor, Path::new(role.target()), role.max_bytes())? == *original, + "UPDATE_PREDECESSOR_CHANGED" + ); + let security = SecurityDescriptor::read(&predecessor)?; + let attributes = security.attributes(); + let path = directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label())); + let effect = Effect::StageFile { role }; + fence.before_effect(&effect)?; + budget.check()?; + directory.check()?; + let mut file = open( + &path, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE, + CREATE_NEW, + &attributes, + )?; + let mut total = 0u64; + let mut buffer = [0u8; 65536]; + loop { + budget.check()?; + let read = source.read(&mut buffer)?; + if read == 0 { + break; + } + total = total + .checked_add(read as u64) + .context("UPDATE_STAGE_LENGTH")?; + ensure!(total <= replacement_bytes, "UPDATE_STAGE_EXTRA_BYTES"); + file.write_all(&buffer[..read])?; + } + ensure!(total == replacement_bytes, "UPDATE_STAGE_TRUNCATED"); + file.sync_all()?; + let staged = proof(&mut file, &path, role.max_bytes())?; + ensure!( + staged.bytes == replacement_bytes + && staged.sha256 == replacement_sha256 + && staged.identity != original.identity + && staged.identity.volume_serial == original.identity.volume_serial + && staged.security_sha256 == original.security_sha256, + "UPDATE_STAGE_VERIFICATION" + ); + directory.check()?; + budget.check()?; + fence.after_effect(&effect, &digest(&serde_json::to_vec(&staged)?))?; + Ok(Self { + role, + nonce, + directory, + path, + file, + original: original.clone(), + staged, + }) + } + pub fn original(&self) -> &Proof { + &self.original + } + pub fn staged(&self) -> &Proof { + &self.staged + } + /// Publication consists of TWO separately fenced native renames. This is + /// explicitly not an atomic pair swap. Any missing reply/readback requires + /// retained-namespace adjudication, never automatic re-entry/replacement. + pub fn publish( + mut self, + stopped: &super::services::Stopped, + budget: &Budget<'_>, + fence: &mut impl DurableEffectFence, + ) -> Result { + stopped.check(budget)?; + self.directory.check()?; + ensure!( + proof(&mut self.file, &self.path, self.role.max_bytes())? == self.staged, + "UPDATE_STAGED_FILE_CHANGED" + ); + let target = Path::new(self.role.target()); + let mut original = open( + target, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE, + OPEN_EXISTING, + ptr::null(), + )?; + ensure!( + proof(&mut original, target, self.role.max_bytes())? == self.original, + "UPDATE_PREDECESSOR_CHANGED" + ); + let previous = self.directory.child(&format!( + ".rmm-update-{}-{}.previous", + self.nonce, + self.role.label() + )); + let save = Effect::SavePredecessor { role: self.role }; + fence.before_effect(&save)?; + budget.check()?; + stopped.check(budget)?; + self.directory.check()?; + rename_new(&original, &previous)?; + let saved = proof(&mut original, &previous, self.role.max_bytes())?; + ensure!(saved == self.original, "UPDATE_SAVED_PREDECESSOR_CHANGED"); + fence.after_effect(&save, &digest(&serde_json::to_vec(&saved)?))?; + let publish = Effect::PublishReplacement { role: self.role }; + fence.before_effect(&publish)?; + budget.check()?; + stopped.check(budget)?; + self.directory.check()?; + rename_new(&self.file, target)?; + let published = proof(&mut self.file, target, self.role.max_bytes())?; + ensure!(published == self.staged, "UPDATE_PUBLISHED_FILE_CHANGED"); + fence.after_effect(&publish, &digest(&serde_json::to_vec(&published)?))?; + Ok(Published { + role: self.role, + directory: self.directory, + original, + predecessor: previous, + original_proof: saved, + replacement: self.file, + replacement_proof: published, + }) + } +} +fn rename_new(file: &File, target: &Path) -> Result<()> { + let name: Vec = target.as_os_str().encode_wide().collect(); + ensure!( + target.is_absolute() && name.len() <= 32767 && !name.contains(&0), + "UPDATE_RENAME_TARGET" + ); + let length = offset_of!(FILE_RENAME_INFO, FileName) + name.len() * 2; + let mut bytes = vec![0usize; length.div_ceil(size_of::())]; + let info = bytes.as_mut_ptr().cast::(); + // SAFETY: aligned, zeroed buffer with exact capacity for the fixed header + // and full UTF16 name. The native call is handle-relative to the already + // held SOURCE; ReplaceIfExists=false refuses files, links or a raced target. + unsafe { + (*info).Anonymous.ReplaceIfExists = false; + (*info).RootDirectory = ptr::null_mut(); + (*info).FileNameLength = (name.len() * 2) as u32; + ptr::copy_nonoverlapping( + name.as_ptr(), + ptr::addr_of_mut!((*info).FileName).cast::(), + name.len(), + ); + } + ensure!( + unsafe { + SetFileInformationByHandle( + file.as_raw_handle(), + FileRenameInfo, + info.cast(), + length as u32, + ) + } != 0, + "UPDATE_RENAME_UNCERTAIN: {}", + std::io::Error::last_os_error() + ); + // Flush the held write-through file after the rename; a power loss or + // failed metadata observation still remains uncertain in the durable ledger. + file.sync_all()?; + Ok(()) +} +pub struct Published { + role: Role, + directory: Directory, + original: File, + predecessor: PathBuf, + original_proof: Proof, + replacement: File, + replacement_proof: Proof, +} +impl Published { + pub fn proof(&self) -> &Proof { + &self.replacement_proof + } + pub fn verify(&mut self, budget: &Budget<'_>) -> Result<()> { + budget.check()?; + self.directory.check()?; + ensure!( + proof(&mut self.original, &self.predecessor, self.role.max_bytes())? + == self.original_proof + && proof( + &mut self.replacement, + Path::new(self.role.target()), + self.role.max_bytes() + )? == self.replacement_proof, + "UPDATE_PUBLISHED_PAIR_CHANGED" + ); + Ok(()) + } + /// Close replacement/delete handles before SCM startup. The caller retains + /// the proofs and must independently reopen/recheck them during Health. + /// No predecessor is removed; this module contains no cleanup primitive. + pub fn release(mut self, budget: &Budget<'_>) -> Result<(Proof, Proof)> { + self.verify(budget)?; + Ok((self.original_proof, self.replacement_proof)) + } +} diff --git a/crates/agent-windows/src/update_native/mod.rs b/crates/agent-windows/src/update_native/mod.rs new file mode 100644 index 0000000..78c347b --- /dev/null +++ b/crates/agent-windows/src/update_native/mod.rs @@ -0,0 +1,198 @@ +//! Native Windows primitives for the separately provisioned stable updater. +//! +//! This module neither approves an update nor activates a worker. The caller +//! authenticates the approved original admission and (after staging) consumed +//! handoff, owns the existing ledger guard, and supplies a durable effect fence. +//! No default/permissive fence, resume, +//! reset, shell, reboot, or arbitrary service/path operation is provided. +use anyhow::{Result, ensure}; +use rmm_agent_core::helper_reconcile::BootSource; +use serde::{Deserialize, Serialize}; +use std::time::{Duration, Instant}; +use uuid::Uuid; + +#[cfg(windows)] +pub mod fence; +#[cfg(windows)] +pub mod files; +#[cfg(windows)] +pub mod services; +pub mod transition; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Service { + Agent, + Helper, +} +impl Service { + pub fn name(self) -> &'static str { + match self { + Self::Agent => "RmmDiscoveryWindows", + Self::Helper => "RmmDiscoverySystemHelper", + } + } + pub fn handoff_service(self) -> rmm_updater_handoff::Service { + match self { + Self::Agent => rmm_updater_handoff::Service::WindowsAgent, + Self::Helper => rmm_updater_handoff::Service::WindowsHelper, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + Agent, + Helper, + Settings, + Pin, + TimeProfile, +} +impl Role { + pub fn target(self) -> &'static str { + match self { + Self::Agent => r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe", + Self::Helper => r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe", + Self::Settings => r"C:\ProgramData\RustDiscoverySystem\helper.json", + Self::Pin => r"C:\ProgramData\RustDiscoverySystem\agent-pin.json", + Self::TimeProfile => r"C:\ProgramData\RustDiscoverySystem\time-attestation.json", + } + } + pub fn handoff_role(self) -> rmm_updater_handoff::FileRole { + match self { + Self::Agent => rmm_updater_handoff::FileRole::AgentBinary, + Self::Helper => rmm_updater_handoff::FileRole::HelperBinary, + Self::Settings => rmm_updater_handoff::FileRole::WindowsSettings, + Self::Pin => rmm_updater_handoff::FileRole::WindowsPin, + Self::TimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, + } + } + #[cfg(windows)] + fn label(self) -> &'static str { + match self { + Self::Agent => "agent", + Self::Helper => "helper", + Self::Settings => "settings", + Self::Pin => "pin", + Self::TimeProfile => "time-profile", + } + } + pub fn max_bytes(self) -> u64 { + match self { + Self::Agent | Self::Helper => 256 * 1024 * 1024, + Self::Settings | Self::Pin | Self::TimeProfile => 64 * 1024, + } + } +} + +/// The embedding worker must additionally check its original trusted-clock +/// interval and signed deadline at each effect. This budget cannot extend it. +pub struct Budget<'a> { + boot: &'a dyn BootSource, + boot_id: Uuid, + until: Instant, +} +impl<'a> Budget<'a> { + pub fn new(boot: &'a dyn BootSource, expected: Uuid, remaining: Duration) -> Result { + ensure!( + !expected.is_nil() && !remaining.is_zero() && remaining <= Duration::from_secs(600), + "UPDATE_BUDGET" + ); + let value = Self { + boot, + boot_id: expected, + until: Instant::now() + .checked_add(remaining) + .ok_or_else(|| anyhow::anyhow!("UPDATE_BUDGET"))?, + }; + value.check()?; + Ok(value) + } + pub fn check(&self) -> Result<()> { + ensure!(Instant::now() < self.until, "UPDATE_DEADLINE"); + ensure!( + self.boot.current_boot()? == self.boot_id, + "UPDATE_BOOT_CHANGED" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)] +pub enum Effect { + StopService { service: Service }, + StageFile { role: Role }, + SavePredecessor { role: Role }, + PublishReplacement { role: Role }, + RestorePredecessor { role: Role }, + StartService { service: Service }, +} + +/// Implementations MUST independently check the original approved admission +/// for StageFile; every later effect additionally needs the consumed original +/// handoff. Retained owner/process/boot/clock/ledger witnesses and a COMMITTED +/// create-once intent are required. Observation failure never allows a retry. +pub trait DurableEffectFence { + fn before_effect(&mut self, effect: &Effect) -> Result<()>; + fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()>; +} +fn valid_digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +#[cfg(windows)] +fn digest(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + struct Boot(AtomicBool, Uuid); + impl BootSource for Boot { + fn current_boot(&self) -> Result { + Ok(if self.0.load(Ordering::SeqCst) { + Uuid::nil() + } else { + self.1 + }) + } + } + #[test] + fn budget_is_original_boot_bound_and_never_has_an_unbounded_window() { + let boot = Boot(AtomicBool::new(false), Uuid::new_v4()); + assert!(Budget::new(&boot, boot.1, Duration::ZERO).is_err()); + assert!(Budget::new(&boot, boot.1, Duration::from_secs(601)).is_err()); + assert!(Budget::new(&boot, Uuid::nil(), Duration::from_secs(1)).is_err()); + let bound = Budget::new(&boot, boot.1, Duration::from_secs(1)).unwrap(); + bound.check().unwrap(); + boot.0.store(true, Ordering::SeqCst); + assert!(bound.check().is_err()); + } + #[test] + fn windows_roles_are_closed_and_effects_reject_unknown_fields() { + assert_eq!(Service::Agent.name(), crate::SERVICE_NAME); + assert_eq!( + Role::Pin.handoff_role(), + rmm_updater_handoff::FileRole::WindowsPin + ); + for raw in [ + r#"{"effect":"stop_service","service":"updater"}"#, + r#"{"effect":"publish_replacement","role":"arbitrary"}"#, + r#"{"effect":"stop_service","service":"helper","command":"extra"}"#, + ] { + assert!(serde_json::from_str::(raw).is_err()); + } + assert!(valid_digest(&"ab".repeat(32))); + assert!(!valid_digest(&"AB".repeat(32))); + } +} diff --git a/crates/agent-windows/src/update_native/services.rs b/crates/agent-windows/src/update_native/services.rs new file mode 100644 index 0000000..7e3d28c --- /dev/null +++ b/crates/agent-windows/src/update_native/services.rs @@ -0,0 +1,393 @@ +//! Closed native SCM stop/start with held original process witnesses. +//! Service recovery actions, triggers and dependencies are refused rather than +//! modified. Every native request is issued once after a durable caller intent. +use super::{Budget, DurableEffectFence, Effect, Service, digest}; +use crate::helper_ipc::{PeerPin, PeerProof, utf16_pointer, wide}; +use anyhow::{Result, ensure}; +use rmm_updater_handoff::{Process, StartedService}; +use serde::{Deserialize, Serialize}; +use std::{ + mem::{size_of, zeroed}, + ptr, thread, + time::Duration, +}; +use windows_sys::Win32::System::Services::*; + +struct Handle(SC_HANDLE); +impl Drop for Handle { + fn drop(&mut self) { + unsafe { + CloseServiceHandle(self.0); + } + } +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Configuration { + pub service: Service, + pub command: String, + pub account: String, + pub start_type: u32, + pub error_control: u32, + pub sid_type: u32, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Proof { + pub configuration: Configuration, + pub process: Process, +} +struct HeldService { + service: Service, + handle: Handle, + peer: PeerProof, + proof: Proof, +} +fn handle(service: Service, rights: u32) -> Result { + let manager = Handle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }); + ensure!(!manager.0.is_null(), "UPDATE_SCM_MANAGER"); + let value = Handle(unsafe { OpenServiceW(manager.0, wide(service.name()).as_ptr(), rights) }); + ensure!(!value.0.is_null(), "UPDATE_SCM_SERVICE"); + Ok(value) +} +fn status(handle: &Handle) -> Result { + let mut value = unsafe { zeroed() }; + let mut needed = 0; + ensure!( + unsafe { + QueryServiceStatusEx( + handle.0, + SC_STATUS_PROCESS_INFO, + (&mut value as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut needed, + ) + } != 0, + "UPDATE_SCM_STATUS" + ); + Ok(value) +} +fn config2(handle: &Handle, kind: u32) -> Result> { + let mut needed = 0; + unsafe { + QueryServiceConfig2W(handle.0, kind, ptr::null_mut(), 0, &mut needed); + } + ensure!((1..=32768).contains(&needed), "UPDATE_SCM_CONFIG_SIZE"); + let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { + QueryServiceConfig2W( + handle.0, + kind, + bytes.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } != 0, + "UPDATE_SCM_CONFIG" + ); + Ok(bytes) +} +fn configuration(handle: &Handle, service: Service, pin: &PeerPin) -> Result { + pin.validate(service == Service::Helper)?; + let mut needed = 0; + unsafe { + QueryServiceConfigW(handle.0, ptr::null_mut(), 0, &mut needed); + } + ensure!((1..=32768).contains(&needed), "UPDATE_SCM_CONFIG_SIZE"); + let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { QueryServiceConfigW(handle.0, bytes.as_mut_ptr().cast(), needed, &mut needed) } + != 0, + "UPDATE_SCM_CONFIG" + ); + let cfg = unsafe { &*bytes.as_ptr().cast::() }; + let command = unsafe { utf16_pointer(cfg.lpBinaryPathName) }?; + let account = unsafe { utf16_pointer(cfg.lpServiceStartName) }?; + let expected = if service == Service::Agent { + format!( + "\"{}\" --service --config \"C:\\ProgramData\\RustDiscovery\\config.json\"", + pin.binary.display() + ) + } else { + format!("\"{}\" --service", pin.binary.display()) + }; + ensure!( + cfg.dwServiceType == SERVICE_WIN32_OWN_PROCESS + && command == expected + && cfg.dwStartType + == if service == Service::Agent { + SERVICE_AUTO_START + } else { + SERVICE_DEMAND_START + } + && (cfg.lpDependencies.is_null() || unsafe { *cfg.lpDependencies } == 0) + && (cfg.lpLoadOrderGroup.is_null() || unsafe { *cfg.lpLoadOrderGroup } == 0), + "UPDATE_SCM_UNEXPECTED_CONFIGURATION" + ); + let recovery = config2(handle, SERVICE_CONFIG_FAILURE_ACTIONS)?; + let recovery = unsafe { &*recovery.as_ptr().cast::() }; + ensure!(recovery.cActions == 0, "UPDATE_SCM_RECOVERY_ACTIONS"); + let triggers = config2(handle, SERVICE_CONFIG_TRIGGER_INFO)?; + let triggers = unsafe { &*triggers.as_ptr().cast::() }; + ensure!(triggers.cTriggers == 0, "UPDATE_SCM_TRIGGERS"); + let sid = config2(handle, SERVICE_CONFIG_SERVICE_SID_INFO)?; + let sid = unsafe { &*sid.as_ptr().cast::() }; + ensure!( + sid.dwServiceSidType == SERVICE_SID_TYPE_UNRESTRICTED, + "UPDATE_SCM_SERVICE_SID" + ); + // Refuse active dependent services; stopping this pair cannot stop another + // product or cause StartService's implicit dependency side effects. + let mut dependent_bytes = 0; + let mut dependent_count = 0; + let no_dependents = unsafe { + EnumDependentServicesW( + handle.0, + SERVICE_ACTIVE, + ptr::null_mut(), + 0, + &mut dependent_bytes, + &mut dependent_count, + ) + }; + ensure!( + no_dependents != 0 && dependent_count == 0 && dependent_bytes == 0, + "UPDATE_SCM_ACTIVE_DEPENDENTS" + ); + Ok(Configuration { + service, + command, + account, + start_type: cfg.dwStartType, + error_control: cfg.dwErrorControl, + sid_type: sid.dwServiceSidType, + }) +} +fn observe(service: Service, pin: &PeerPin, budget: &Budget<'_>) -> Result { + budget.check()?; + let handle = handle( + service, + SERVICE_QUERY_STATUS + | SERVICE_QUERY_CONFIG + | SERVICE_ENUMERATE_DEPENDENTS + | SERVICE_STOP + | SERVICE_START, + )?; + let before = configuration(&handle, service, pin)?; + let state = status(&handle)?; + ensure!( + state.dwCurrentState == SERVICE_RUNNING && state.dwProcessId > 0, + "UPDATE_SERVICE_NOT_RUNNING" + ); + let mut peer = PeerProof::for_service(pin, state.dwProcessId)?; + peer.check()?; + let id = peer.identity(); + let proof = Proof { + configuration: before.clone(), + process: Process { + pid: id.pid, + birth: id.creation_ticks, + image_sha256: id.image_sha256.clone(), + }, + }; + ensure!( + configuration(&handle, service, pin)? == before + && status(&handle)?.dwProcessId == proof.process.pid, + "UPDATE_SERVICE_OBSERVATION_CHANGED" + ); + budget.check()?; + Ok(HeldService { + service, + handle, + peer, + proof, + }) +} + +/// Observation holds both original processes/images, not a freely constructible +/// Running flag. Drop these witnesses only after confirmed process termination. +pub struct Running { + pins: [PeerPin; 2], + held: Vec, +} +impl Running { + pub fn observe(pins: [PeerPin; 2], budget: &Budget<'_>) -> Result { + let held = vec![ + observe(Service::Agent, &pins[0], budget)?, + observe(Service::Helper, &pins[1], budget)?, + ]; + Ok(Self { pins, held }) + } + pub fn proofs(&self) -> Vec { + self.held.iter().map(|s| s.proof.clone()).collect() + } + pub fn check(&mut self, budget: &Budget<'_>) -> Result<()> { + budget.check()?; + for (i, service) in self.held.iter_mut().enumerate() { + service.peer.check()?; + ensure!( + configuration(&service.handle, service.service, &self.pins[i])? + == service.proof.configuration, + "UPDATE_SERVICE_CONFIG_CHANGED" + ); + } + Ok(()) + } + pub fn stop( + mut self, + budget: &Budget<'_>, + fence: &mut impl DurableEffectFence, + ) -> Result { + self.check(budget)?; + for (i, service) in self.held.iter_mut().enumerate() { + service.peer.check()?; + ensure!( + configuration(&service.handle, service.service, &self.pins[i])? + == service.proof.configuration, + "UPDATE_SERVICE_CONFIG_CHANGED" + ); + let effect = Effect::StopService { + service: service.service, + }; + fence.before_effect(&effect)?; + budget.check()?; + service.peer.check()?; + let mut stopped = unsafe { zeroed() }; + ensure!( + unsafe { ControlService(service.handle.0, SERVICE_CONTROL_STOP, &mut stopped) } + != 0, + "UPDATE_STOP_REQUEST_UNCERTAIN" + ); + loop { + budget.check()?; + let state = status(&service.handle)?; + if state.dwCurrentState == SERVICE_STOPPED + && state.dwProcessId == 0 + && service.peer.exited()? + { + break; + } + ensure!( + matches!(state.dwCurrentState, SERVICE_STOP_PENDING | SERVICE_STOPPED), + "UPDATE_STOP_STATE_UNCERTAIN" + ); + thread::sleep(Duration::from_millis(20)); + } + fence.after_effect(&effect, &digest(&serde_json::to_vec(&service.proof)?))?; + } + let proofs = self.proofs(); + let stopped = Stopped { + pins: self.pins, + configurations: [ + proofs[0].configuration.clone(), + proofs[1].configuration.clone(), + ], + }; + // Held image handles intentionally close here, after BOTH exact original + // processes have terminated. Neither PID reuse nor SCM state suffices. + drop(self.held); + stopped.check(budget)?; + Ok(stopped) + } +} + +/// Only the actual completed stop sequence constructs this token. It is not a +/// closed-reader census or a helper-ledger lock; those remain separate gates. +pub struct Stopped { + pins: [PeerPin; 2], + configurations: [Configuration; 2], +} +impl Stopped { + pub fn check(&self, budget: &Budget<'_>) -> Result<()> { + budget.check()?; + for (i, service) in [Service::Agent, Service::Helper].into_iter().enumerate() { + let handle = handle( + service, + SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_ENUMERATE_DEPENDENTS, + )?; + let state = status(&handle)?; + ensure!( + state.dwCurrentState == SERVICE_STOPPED + && state.dwProcessId == 0 + && configuration(&handle, service, &self.pins[i])? == self.configurations[i], + "UPDATE_STOPPED_STATE_CHANGED" + ); + } + Ok(()) + } + /// Caller MUST commit the original ledger-return/start-reservation before + /// dropping its guard and calling this. Helper starts before agent. This + /// function never retries a failed or uncertain native start request. + pub fn start( + self, + replacement_pins: [PeerPin; 2], + budget: &Budget<'_>, + fence: &mut impl DurableEffectFence, + ) -> Result { + self.check(budget)?; + let mut started = Vec::with_capacity(2); + for (i, service) in [(1, Service::Helper), (0, Service::Agent)] { + replacement_pins[i].validate(service == Service::Helper)?; + ensure!( + replacement_pins[i].binary == self.pins[i].binary + && replacement_pins[i].service_name == self.pins[i].service_name + && replacement_pins[i].service_sid == self.pins[i].service_sid + && replacement_pins[i].user_sid == self.pins[i].user_sid, + "UPDATE_REPLACEMENT_SERVICE_IDENTITY" + ); + let handle = handle( + service, + SERVICE_QUERY_STATUS + | SERVICE_QUERY_CONFIG + | SERVICE_ENUMERATE_DEPENDENTS + | SERVICE_START, + )?; + ensure!( + configuration(&handle, service, &replacement_pins[i])? == self.configurations[i], + "UPDATE_SERVICE_CONFIG_CHANGED" + ); + let effect = Effect::StartService { service }; + fence.before_effect(&effect)?; + budget.check()?; + ensure!( + status(&handle)?.dwCurrentState == SERVICE_STOPPED, + "UPDATE_START_ALREADY_RUNNING" + ); + ensure!( + unsafe { StartServiceW(handle.0, 0, ptr::null()) } != 0, + "UPDATE_START_REQUEST_UNCERTAIN" + ); + loop { + budget.check()?; + let state = status(&handle)?; + if state.dwCurrentState == SERVICE_RUNNING { + break; + } + ensure!( + state.dwCurrentState == SERVICE_START_PENDING, + "UPDATE_START_STATE_UNCERTAIN" + ); + thread::sleep(Duration::from_millis(20)); + } + let held = observe(service, &replacement_pins[i], budget)?; + fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?; + started.push(held); + } + started.reverse(); + let mut running = Running { + pins: replacement_pins, + held: started, + }; + running.check(budget)?; + Ok(running) + } +} +impl Proof { + pub fn started(&self) -> StartedService { + StartedService { + service: self.configuration.service.handoff_service(), + process: self.process.clone(), + } + } +} diff --git a/crates/agent-windows/src/update_native/transition.rs b/crates/agent-windows/src/update_native/transition.rs new file mode 100644 index 0000000..397f7ff --- /dev/null +++ b/crates/agent-windows/src/update_native/transition.rs @@ -0,0 +1,540 @@ +//! Closed Windows code/pin/time-profile rendering, without OS effects. +//! +//! Input bytes must come from protected, independently authenticated original +//! files. Candidate time qualifications must be independently verified by the +//! embedding admission worker BEFORE offering a release. This pure renderer +//! binds their exact bytes/hashes; parsing a receipt hash does not qualify code. +use super::valid_digest; +use crate::signed_clock::{ActiveGuestOperation, TrustedOsConfiguration, TrustedPlatform}; +use anyhow::{Result, ensure}; +use rmm_agent_core::{ + auth::Binding, + crypto::{DalekVerifier, Ed25519Verifier}, +}; +use rmm_domain::{ + agent_update::{PeerPinTransition, WindowsTimeProfileTransition}, + jobs::{PrivilegedScriptProfile, hash}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::path::PathBuf; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Peer { + service_name: String, + service_sid: String, + user_sid: String, + binary: PathBuf, + binary_sha256: String, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Rule { + name: String, + binary: PathBuf, + binary_sha256: String, +} +/// Versioned snapshot of Settings' SERIALIZATION field order. No new rights, +/// service rules, reboot setting or interpreter policy can be introduced here. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Settings { + schema_version: u32, + binding: Binding, + agent: Peer, + helper: Peer, + allowed_services: Vec, + max_runtime_seconds: u32, + enable_effects: bool, + allow_reboot: bool, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "strict_hashes" + )] + allowed_msi_recipe_sha256: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "rmm_domain::jobs::deserialize_script_profiles" + )] + allowed_script_profiles: Option>, +} +fn strict_hashes<'de, D: serde::Deserializer<'de>>( + d: D, +) -> std::result::Result>, D::Error> { + Vec::::deserialize(d).map(Some) +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Pin { + schema_version: u32, + binding: Binding, + policy_sha256: String, + agent: Peer, + helper: Peer, +} +#[derive(Deserialize)] +struct PeerSpan<'a> { + #[serde(borrow)] + binary_sha256: &'a RawValue, +} +#[derive(Deserialize)] +struct Spans<'a> { + #[serde(borrow)] + agent: PeerSpan<'a>, + #[serde(borrow)] + helper: PeerSpan<'a>, + #[serde(default, borrow)] + policy_sha256: Option<&'a RawValue>, +} +pub struct CodePairTransition { + proof: PeerPinTransition, + settings: Vec, + pin: Vec, + time_profile: Vec, +} +impl CodePairTransition { + pub fn proof(&self) -> &PeerPinTransition { + &self.proof + } + pub fn settings_bytes(&self) -> &[u8] { + &self.settings + } + pub fn pin_bytes(&self) -> &[u8] { + &self.pin + } + pub fn time_profile_bytes(&self) -> &[u8] { + &self.time_profile + } +} +pub struct Inputs<'a> { + pub settings: &'a [u8], + pub pin: &'a [u8], + pub time_profile: &'a [u8], + pub qualified_candidate_time_profile: &'a [u8], + pub target_agent_sha256: &'a str, + pub target_helper_sha256: &'a str, +} +fn bound_peer(peer: &Peer, helper: bool) -> bool { + let service = if helper { + super::Service::Helper + } else { + super::Service::Agent + }; + let role = if helper { + super::Role::Helper + } else { + super::Role::Agent + }; + peer.service_name == service.name() + && peer.user_sid == if helper { "S-1-5-18" } else { "S-1-5-19" } + && peer.service_sid.starts_with("S-1-5-80-") + && peer.binary.to_str() == Some(role.target()) + && valid_digest(&peer.binary_sha256) +} +fn time_configuration( + bytes: &[u8], + binding: &Binding, + agent: &str, + helper: &str, +) -> Result { + let value: TrustedOsConfiguration = serde_json::from_slice(bytes)?; + let profile = &value.trusted_os_active_guest; + ensure!( + value.schema_version == 2 + && value.key_generation > 0 + && !value.server_instance.is_nil() + && serde_json::to_value(&value.binding)? == serde_json::to_value(binding)? + && !value.public_keys_hex.is_empty() + && value.public_keys_hex.len() <= 8 + && matches!( + profile.operating_assumption, + ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend + ) + && matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock) + && valid_digest(&profile.platform_provenance_sha256) + && profile.qualifications.len() == 2, + "UPDATE_TIME_PROFILE_BINDING" + ); + for (id, public) in &value.public_keys_hex { + ensure!( + !id.is_empty() + && id.len() <= 64 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) + && valid_digest(public) + && public != &binding.public_key_hex, + "UPDATE_TIME_PROFILE_KEY" + ); + let key = (0..32) + .map(|i| u8::from_str_radix(&public[i * 2..i * 2 + 2], 16)) + .collect::, _>>()?; + ensure!(DalekVerifier.validate_key(&key)?, "UPDATE_TIME_PROFILE_KEY"); + } + for (role, image) in [ + (rmm_time_attestation::Role::Agent, agent), + (rmm_time_attestation::Role::SystemHelper, helper), + ] { + let found: Vec<_> = profile + .qualifications + .iter() + .filter(|q| q.role == role) + .collect(); + ensure!( + found.len() == 1 + && found[0].binary_sha256 == image + && valid_digest(&found[0].qualification_sha256), + "UPDATE_TIME_PROFILE_QUALIFICATION" + ); + } + Ok(value) +} +pub fn render(input: Inputs<'_>) -> Result { + for raw in [ + input.settings, + input.pin, + input.time_profile, + input.qualified_candidate_time_profile, + ] { + ensure!( + !raw.is_empty() && raw.len() <= 32768, + "UPDATE_WINDOWS_RENDER_LIMIT" + ); + } + ensure!( + valid_digest(input.target_agent_sha256) && valid_digest(input.target_helper_sha256), + "UPDATE_WINDOWS_IMAGE" + ); + let mut settings: Settings = serde_json::from_slice(input.settings)?; + let mut pin: Pin = serde_json::from_slice(input.pin)?; + ensure!( + matches!(settings.schema_version, 1..=3) + && !settings.allow_reboot + && (1..=120).contains(&settings.max_runtime_seconds) + && settings.allowed_services.len() <= 16 + && (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none()) + && (settings.schema_version == 3 || settings.allowed_script_profiles.is_none()) + && bound_peer(&settings.agent, false) + && bound_peer(&settings.helper, true) + && !settings.binding.tenant_id.is_nil() + && !settings.binding.asset_id.is_nil() + && !settings.binding.agent_id.is_nil() + && settings.binding.enrollment_generation > 0 + && settings.binding.assignment_version > 0 + && pin.schema_version == 1 + && pin.policy_sha256 == hash(&serde_json::to_vec(&settings)?) + && serde_json::to_value(&pin.binding)? == serde_json::to_value(&settings.binding)? + && serde_json::to_value(&pin.agent)? == serde_json::to_value(&settings.agent)? + && serde_json::to_value(&pin.helper)? == serde_json::to_value(&settings.helper)?, + "UPDATE_WINDOWS_ORIGINAL_PAIR" + ); + let old_agent = settings.agent.binary_sha256.clone(); + let old_helper = settings.helper.binary_sha256.clone(); + let old_time = time_configuration( + input.time_profile, + &settings.binding, + &old_agent, + &old_helper, + )?; + let candidate = time_configuration( + input.qualified_candidate_time_profile, + &settings.binding, + input.target_agent_sha256, + input.target_helper_sha256, + )?; + let mut unchanged_candidate = serde_json::to_value(&candidate)?; + unchanged_candidate["trusted_os_active_guest"]["qualifications"] = + serde_json::to_value(&old_time.trusted_os_active_guest.qualifications)?; + ensure!( + unchanged_candidate == serde_json::to_value(&old_time)?, + "UPDATE_TIME_TRUST_OR_PLATFORM_CHANGE" + ); + for new in &candidate.trusted_os_active_guest.qualifications { + let old = old_time + .trusted_os_active_guest + .qualifications + .iter() + .find(|q| q.role == new.role) + .ok_or_else(|| anyhow::anyhow!("UPDATE_TIME_ROLE"))?; + ensure!( + new.binary_sha256 == old.binary_sha256 + || new.qualification_sha256 != old.qualification_sha256, + "UPDATE_TIME_OLD_QUALIFICATION_REUSED" + ); + } + settings.agent.binary_sha256 = input.target_agent_sha256.into(); + settings.helper.binary_sha256 = input.target_helper_sha256.into(); + pin.agent.binary_sha256 = input.target_agent_sha256.into(); + pin.helper.binary_sha256 = input.target_helper_sha256.into(); + pin.policy_sha256 = hash(&serde_json::to_vec(&settings)?); + let settings_spans: Spans<'_> = serde_json::from_slice(input.settings)?; + let pin_spans: Spans<'_> = serde_json::from_slice(input.pin)?; + let settings_bytes = replace( + input.settings, + vec![ + ( + settings_spans.agent.binary_sha256, + input.target_agent_sha256, + ), + ( + settings_spans.helper.binary_sha256, + input.target_helper_sha256, + ), + ], + )?; + let pin_bytes = replace( + input.pin, + vec![ + (pin_spans.agent.binary_sha256, input.target_agent_sha256), + (pin_spans.helper.binary_sha256, input.target_helper_sha256), + ( + pin_spans + .policy_sha256 + .ok_or_else(|| anyhow::anyhow!("UPDATE_PIN_POLICY_HASH"))?, + &pin.policy_sha256, + ), + ], + )?; + // Confirm the span edits exactly equal the typed, closed intended objects. + ensure!( + serde_json::to_value(serde_json::from_slice::(&settings_bytes)?)? + == serde_json::to_value(&settings)? + && serde_json::to_value(serde_json::from_slice::(&pin_bytes)?)? + == serde_json::to_value(&pin)?, + "UPDATE_WINDOWS_RENDER_CHANGED" + ); + let quals = &candidate.trusted_os_active_guest.qualifications; + let agent = quals + .iter() + .find(|q| q.role == rmm_time_attestation::Role::Agent) + .unwrap(); + let helper = quals + .iter() + .find(|q| q.role == rmm_time_attestation::Role::SystemHelper) + .unwrap(); + let transition = PeerPinTransition::WindowsCodePairV1 { + old_settings_sha256: hash(input.settings), + new_settings_sha256: hash(&settings_bytes), + old_pin_sha256: hash(input.pin), + new_pin_sha256: hash(&pin_bytes), + time_profile: Some(WindowsTimeProfileTransition { + schema_version: 1, + old_time_profile_sha256: hash(input.time_profile), + new_time_profile_sha256: hash(input.qualified_candidate_time_profile), + agent_qualification_sha256: agent.qualification_sha256.clone(), + helper_qualification_sha256: helper.qualification_sha256.clone(), + }), + }; + Ok(CodePairTransition { + proof: transition, + settings: settings_bytes, + pin: pin_bytes, + time_profile: input.qualified_candidate_time_profile.to_vec(), + }) +} +fn replace(bytes: &[u8], values: Vec<(&RawValue, &str)>) -> Result> { + let mut spans = Vec::new(); + for (raw, replacement) in values { + let raw = raw.get(); + let start = (raw.as_ptr() as usize) + .checked_sub(bytes.as_ptr() as usize) + .ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?; + let end = start + .checked_add(raw.len()) + .ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?; + ensure!( + bytes.get(start..end) == Some(raw.as_bytes()) + && raw.len() == 66 + && raw.starts_with('"') + && raw.ends_with('"') + && valid_digest(&raw[1..65]) + && valid_digest(replacement), + "UPDATE_RENDER_HASH_ENCODING" + ); + spans.push((start, end, format!("\"{replacement}\""))); + } + spans.sort_by_key(|s| s.0); + ensure!( + spans.windows(2).all(|p| p[0].1 <= p[1].0), + "UPDATE_RENDER_OVERLAP" + ); + let mut result = Vec::with_capacity(bytes.len()); + let mut cursor = 0; + for (start, end, value) in spans { + result.extend_from_slice(&bytes[cursor..start]); + result.extend_from_slice(value.as_bytes()); + cursor = end; + } + result.extend_from_slice(&bytes[cursor..]); + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::SigningKey; + use serde_json::{Value, json}; + struct Fixture { + settings: Vec, + pin: Vec, + time: Vec, + candidate: Vec, + } + fn fixture() -> Fixture { + let public = |byte| { + SigningKey::from_bytes(&[byte; 32]) + .verifying_key() + .to_bytes() + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + }; + let binding = json!({"tenant_id":uuid::Uuid::from_u128(1),"asset_id":uuid::Uuid::from_u128(2), + "agent_id":uuid::Uuid::from_u128(3),"enrollment_generation":1,"assignment_version":1,"public_key_hex":public(17)}); + let peer = |helper: bool| { + json!({"service_name":if helper {super::super::Service::Helper.name()}else{super::super::Service::Agent.name()}, + "service_sid":if helper {"S-1-5-80-1-2-3-4-5"}else{"S-1-5-80-6-7-8-9-10"}, + "user_sid":if helper{"S-1-5-18"}else{"S-1-5-19"}, + "binary":if helper {super::super::Role::Helper.target()}else{super::super::Role::Agent.target()}, + "binary_sha256":if helper{"cd".repeat(32)}else{"ab".repeat(32)}}) + }; + let settings = json!({"schema_version":3,"binding":binding,"agent":peer(false),"helper":peer(true), + "allowed_services":[{"name":"RmmDiscoveryFixtureUpdater","binary":"C:\\Program Files\\RustDiscoveryFixtures\\fixture.exe","binary_sha256":"ab".repeat(32)}], + "max_runtime_seconds":120,"enable_effects":true,"allow_reboot":false, + "allowed_msi_recipe_sha256":[],"allowed_script_profiles":["full_maintenance_v1"]}); + let typed: Settings = serde_json::from_value(settings.clone()).unwrap(); + let pin = json!({"schema_version":1,"binding":binding,"policy_sha256":hash(&serde_json::to_vec(&typed).unwrap()),"agent":peer(false),"helper":peer(true)}); + let time = json!({"schema_version":2,"key_generation":1,"server_instance":uuid::Uuid::from_u128(4),"binding":binding, + "public_keys_hex":{"development_time_v1":public(19)},"trusted_os_active_guest":{ + "operating_assumption":"active_guest_no_pause_save_restore_snapshot_migration_host_suspend","platform":"kvm_qemu_hypervclock", + "platform_provenance_sha256":"01".repeat(32),"qualifications":[ + {"role":"agent","binary_sha256":"ab".repeat(32),"qualification_sha256":"02".repeat(32)}, + {"role":"system_helper","binary_sha256":"cd".repeat(32),"qualification_sha256":"03".repeat(32)}]}}); + let mut candidate = time.clone(); + candidate["trusted_os_active_guest"]["qualifications"][0]["binary_sha256"] = + json!("ef".repeat(32)); + candidate["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] = + json!("04".repeat(32)); + candidate["trusted_os_active_guest"]["qualifications"][1]["binary_sha256"] = + json!("ac".repeat(32)); + candidate["trusted_os_active_guest"]["qualifications"][1]["qualification_sha256"] = + json!("05".repeat(32)); + Fixture { + settings: serde_json::to_vec_pretty(&settings).unwrap(), + pin: serde_json::to_vec_pretty(&pin).unwrap(), + time: serde_json::to_vec_pretty(&time).unwrap(), + candidate: serde_json::to_vec_pretty(&candidate).unwrap(), + } + } + fn render_fixture(f: &Fixture) -> Result { + render(Inputs { + settings: &f.settings, + pin: &f.pin, + time_profile: &f.time, + qualified_candidate_time_profile: &f.candidate, + target_agent_sha256: &"ef".repeat(32), + target_helper_sha256: &"ac".repeat(32), + }) + } + #[test] + fn windows_transition_preserves_raw_policy_bytes_and_binds_prequalified_time_profile() { + let f = fixture(); + let result = render_fixture(&f).unwrap(); + let old: Settings = serde_json::from_slice(&f.settings).unwrap(); + let new: Settings = serde_json::from_slice(result.settings_bytes()).unwrap(); + assert_eq!( + new.allowed_services[0].binary_sha256, + old.agent.binary_sha256 + ); + let reversed = String::from_utf8(result.settings_bytes().to_vec()) + .unwrap() + .replace(&"ef".repeat(32), &"ab".repeat(32)) + .replace(&"ac".repeat(32), &"cd".repeat(32)); + assert_eq!(reversed.as_bytes(), f.settings); + assert_eq!(result.time_profile_bytes(), f.candidate); + let new_pin: Pin = serde_json::from_slice(result.pin_bytes()).unwrap(); + assert_eq!( + new_pin.policy_sha256, + hash(&serde_json::to_vec(&new).unwrap()) + ); + let PeerPinTransition::WindowsCodePairV1 { + time_profile: Some(t), + .. + } = result.proof() + else { + panic!("fixed clock transition") + }; + assert_eq!(t.old_time_profile_sha256, hash(&f.time)); + assert_eq!(t.new_time_profile_sha256, hash(&f.candidate)); + assert_eq!(t.agent_qualification_sha256, "04".repeat(32)); + #[cfg(windows)] + { + // Both OS-native production codecs must derive the SAME policy + // hash; a mirrored test-only serialization cannot satisfy this. + let actual: crate::helper_system::Settings = + serde_json::from_slice(result.settings_bytes()).unwrap(); + assert_eq!(actual.policy_sha256().unwrap(), new_pin.policy_sha256); + let _: crate::helper_ipc::Pin = serde_json::from_slice(result.pin_bytes()).unwrap(); + } + } + #[test] + fn windows_transition_denies_changed_time_trust_reused_qualification_and_unbound_pin() { + for change in [ + "key", + "platform", + "qualification", + "role", + "extra", + "pin", + "null", + ] { + let mut f = fixture(); + if change == "pin" { + let mut value: Value = serde_json::from_slice(&f.pin).unwrap(); + value["policy_sha256"] = json!("ff".repeat(32)); + f.pin = serde_json::to_vec(&value).unwrap(); + } else if change == "null" { + let mut value: Value = serde_json::from_slice(&f.settings).unwrap(); + value["allowed_msi_recipe_sha256"] = Value::Null; + f.settings = serde_json::to_vec(&value).unwrap(); + } else { + let mut value: Value = serde_json::from_slice(&f.candidate).unwrap(); + match change { + "key" => value["key_generation"] = json!(2), + "platform" => { + value["trusted_os_active_guest"]["platform_provenance_sha256"] = + json!("ff".repeat(32)) + } + "qualification" => { + value["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] = + json!("02".repeat(32)) + } + "role" => { + value["trusted_os_active_guest"]["qualifications"][1]["role"] = + json!("agent") + } + _ => value["trusted_os_active_guest"]["assume_ready"] = json!(true), + } + f.candidate = serde_json::to_vec(&value).unwrap(); + } + assert!(render_fixture(&f).is_err(), "changed field {change}"); + } + let f = fixture(); + let mut value: Value = serde_json::from_slice(&f.pin).unwrap(); + value["helper"]["binary_sha256"] = json!("ff".repeat(32)); + assert!( + render(Inputs { + settings: &f.settings, + pin: &serde_json::to_vec(&value).unwrap(), + time_profile: &f.time, + qualified_candidate_time_profile: &f.candidate, + target_agent_sha256: &"ef".repeat(32), + target_helper_sha256: &"ac".repeat(32) + }) + .is_err() + ); + } +} diff --git a/crates/domain/examples/agent_update_golden.rs b/crates/domain/examples/agent_update_golden.rs index 3ef01b9..349df70 100644 --- a/crates/domain/examples/agent_update_golden.rs +++ b/crates/domain/examples/agent_update_golden.rs @@ -65,6 +65,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value { new_settings_sha256: "12".repeat(32), old_pin_sha256: "13".repeat(32), new_pin_sha256: "14".repeat(32), + time_profile: None, }, }; let update = ResolvedAgentUpdate { diff --git a/crates/domain/src/agent_update.rs b/crates/domain/src/agent_update.rs index 2ab33d1..3d2a2f0 100644 --- a/crates/domain/src/agent_update.rs +++ b/crates/domain/src/agent_update.rs @@ -211,6 +211,15 @@ pub struct LinuxFullTransition { pub effective_signing_key_id: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WindowsTimeProfileTransition { + pub schema_version: u32, + pub old_time_profile_sha256: String, + pub new_time_profile_sha256: String, + pub agent_qualification_sha256: String, + pub helper_qualification_sha256: String, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(tag = "profile", rename_all = "snake_case", deny_unknown_fields)] pub enum PeerPinTransition { UnchangedGeneralPinV1 { @@ -225,8 +234,40 @@ pub enum PeerPinTransition { new_settings_sha256: String, old_pin_sha256: String, new_pin_sha256: String, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "strict_windows_time_profile" + )] + time_profile: Option, }, } +fn strict_windows_time_profile<'de, D: serde::Deserializer<'de>>( + d: D, +) -> Result, D::Error> { + WindowsTimeProfileTransition::deserialize(d).map(Some) +} + +#[cfg(test)] +mod windows_time_transition_tests { + use super::*; + #[test] + fn optional_windows_clock_binding_is_additive_and_null_is_never_missing() { + let old = serde_json::json!({"profile":"windows_code_pair_v1","old_settings_sha256":"11".repeat(32), + "new_settings_sha256":"22".repeat(32),"old_pin_sha256":"33".repeat(32),"new_pin_sha256":"44".repeat(32)}); + let decoded: PeerPinTransition = serde_json::from_value(old.clone()).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), old); + let mut invalid = old.clone(); + invalid["time_profile"] = serde_json::Value::Null; + assert!(serde_json::from_value::(invalid).is_err()); + let mut current = old; + current["time_profile"] = serde_json::json!({"schema_version":1, + "old_time_profile_sha256":"55".repeat(32),"new_time_profile_sha256":"66".repeat(32), + "agent_qualification_sha256":"77".repeat(32),"helper_qualification_sha256":"88".repeat(32)}); + let decoded: PeerPinTransition = serde_json::from_value(current.clone()).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), current); + } +} impl PeerPinTransition { fn validate(&self, platform: Platform, predecessor: &Predecessor, target_helper: &str) -> bool { match self { @@ -261,6 +302,7 @@ impl PeerPinTransition { new_settings_sha256, old_pin_sha256, new_pin_sha256, + time_profile, } => { platform == Platform::WindowsX64 && [ @@ -273,6 +315,18 @@ impl PeerPinTransition { .all(|h| digest(h)) && old_settings_sha256 != new_settings_sha256 && old_pin_sha256 != new_pin_sha256 + && time_profile.as_ref().is_none_or(|t| { + t.schema_version == 1 + && [ + &t.old_time_profile_sha256, + &t.new_time_profile_sha256, + &t.agent_qualification_sha256, + &t.helper_qualification_sha256, + ] + .iter() + .all(|h| digest(h)) + && t.old_time_profile_sha256 != t.new_time_profile_sha256 + }) } } } @@ -751,6 +805,7 @@ pub fn handoff_matches_job( new_settings_sha256, old_pin_sha256, new_pin_sha256, + time_profile: None, }, PinTransition::WindowsCodePairV1, ) => { @@ -762,6 +817,29 @@ pub fn handoff_matches_job( && f.new_sha256 == *new_settings_sha256 }) } + ( + PeerPinTransition::WindowsCodePairV1 { + old_settings_sha256, + new_settings_sha256, + old_pin_sha256, + new_pin_sha256, + time_profile: Some(time), + }, + PinTransition::WindowsCodePairClockV1, + ) => { + h.predecessor.pin_sha256 == *old_pin_sha256 + && h.target.pin_sha256 == *new_pin_sha256 + && h.files.get(2).is_some_and(|f| { + f.role == FileRole::WindowsSettings + && f.old_sha256 == *old_settings_sha256 + && f.new_sha256 == *new_settings_sha256 + }) + && h.files.get(4).is_some_and(|f| { + f.role == FileRole::WindowsTimeProfile + && f.old_sha256 == time.old_time_profile_sha256 + && f.new_sha256 == time.new_time_profile_sha256 + }) + } _ => false, } } diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index 5210b6d..a1ee984 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -7,6 +7,7 @@ pub mod inventory_document; pub mod jobs; pub mod reconciliation; pub mod windows_echo_probe; +pub mod windows_echo_completion; pub mod windows_execution; pub mod windows_sync_history; diff --git a/crates/domain/src/windows_echo_completion.rs b/crates/domain/src/windows_echo_completion.rs new file mode 100644 index 0000000..2a85cb9 --- /dev/null +++ b/crates/domain/src/windows_echo_completion.rs @@ -0,0 +1,100 @@ +//! Retirement of an additional development-only scope after its exact probe. +//! This administrative receipt is neither a job approval nor a readiness lease. +use crate::{checkpoint_repair::inventory_sha256, windows_echo_probe::ProbeScope}; +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use uuid::Uuid; + +pub const DOMAIN: &str = "rmm.dev.windows-echo-completion.v1"; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Witness { + pub scope: ProbeScope, + pub probe_receipt_id: Uuid, + pub probe_receipt_sha256: String, + pub probe_signature_sha256: String, + pub grant_id: Uuid, + pub grant_payload_sha256: String, + pub grant_signature_sha256: String, + pub outcome_sha256: String, + pub boot_id: Uuid, +} +impl Witness { + pub fn digest(&self) -> Option { + inventory_sha256(&serde_json::to_value(self).ok()?).ok() + } + pub fn valid(&self) -> bool { + !self.probe_receipt_id.is_nil() + && !self.grant_id.is_nil() + && !self.boot_id.is_nil() + && [ + &self.probe_receipt_sha256, + &self.probe_signature_sha256, + &self.grant_payload_sha256, + &self.grant_signature_sha256, + &self.outcome_sha256, + ] + .iter() + .all(|h| { + h.len() == 64 + && h.bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) + } +} + +/// Both server result and retained native Outcome use this one comparison. +pub fn successful_outcome(v: &Value) -> bool { + v["state"] == "succeeded" + && v["exit_code"] == 0 + && v["stdout"] == json!(crate::windows_echo_probe::OUTPUT.as_bytes()) + && v["stderr"] == json!([]) + && v["output_truncated"] == false + && v["reboot_required"] == false + && v["error_code"] == "" + && v["evidence"]["postconditions_passed"] == true + && v["evidence"]["execution_sid"] == "S-1-5-19" + && v["evidence"]["execution_policy_scope"] == "process" + && v["evidence"]["execution_policy_requested"] == "RemoteSigned" + && v["evidence"]["script_sha256"] + == crate::jobs::hash(crate::windows_echo_probe::SCRIPT.as_bytes()) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Receipt { + pub domain: String, + pub schema_version: u32, + pub receipt_id: Uuid, + pub witness: Witness, + pub witness_sha256: String, + pub key_id: String, + pub issued_at: DateTime, + pub valid_until: DateTime, + pub confirmed_by: String, + pub approval_origin: String, + pub testsimulation: bool, + pub ready: bool, + pub helper_ready: bool, + pub unlock: bool, +} +impl Receipt { + pub fn valid(&self, now: DateTime) -> bool { + self.domain == DOMAIN + && self.schema_version == 1 + && !self.receipt_id.is_nil() + && self.witness.valid() + && self.witness.digest().as_deref() == Some(self.witness_sha256.as_str()) + && self.confirmed_by == crate::windows_echo_probe::TEST_PRINCIPAL + && self.approval_origin == "dev_test_browser_simulation" + && self.testsimulation + && !self.ready + && !self.helper_ready + && !self.unlock + && self.issued_at <= now + && now < self.valid_until + && self.valid_until - self.issued_at <= Duration::minutes(10) + } +} diff --git a/crates/privileged-helper/src/update_guard.rs b/crates/privileged-helper/src/update_guard.rs index 6eb0fc3..fbd8bff 100644 --- a/crates/privileged-helper/src/update_guard.rs +++ b/crates/privileged-helper/src/update_guard.rs @@ -372,6 +372,9 @@ impl<'a> FullUpdateGuard<'a> { NativeService::Agent => Service::Agent, NativeService::General => Service::General, NativeService::Full => Service::Full, + NativeService::WindowsAgent | NativeService::WindowsHelper => { + anyhow::bail!("UPDATE_WINDOWS_SERVICE_ON_LINUX") + } }; let held = self.services.observe(service, &self.budget)?; held.verify(&self.budget)?; @@ -550,6 +553,9 @@ impl UpdateParticipantGuard for FullUpdateGuard<'_> { NativeService::Agent => Service::Agent, NativeService::General => Service::General, NativeService::Full => Service::Full, + NativeService::WindowsAgent | NativeService::WindowsHelper => { + anyhow::bail!("UPDATE_WINDOWS_SERVICE_ON_LINUX") + } }; self.services .observe(service, &self.budget)? @@ -564,6 +570,9 @@ impl UpdateParticipantGuard for FullUpdateGuard<'_> { NativeService::Agent => Service::Agent, NativeService::General => Service::General, NativeService::Full => Service::Full, + NativeService::WindowsAgent | NativeService::WindowsHelper => { + anyhow::bail!("UPDATE_WINDOWS_SERVICE_ON_LINUX") + } }; self.services .observe(service, &self.budget)? diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 2297cf4..bfd57b3 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -28,6 +28,7 @@ mod tls; mod update_artifact_store; mod windows_checkpoint_review; mod windows_echo_probe; +mod windows_echo_completion; mod windows_msi_catalog; mod windows_policy; @@ -187,6 +188,7 @@ async fn main() -> Result<()> { routes = routes.route("/auth/dev/login", post(auth::login)); routes = windows_checkpoint_review::routes(routes); routes = windows_echo_probe::routes(routes); + routes = windows_echo_completion::routes(routes); } routes = routes .route("/auth/config", get(auth::configuration)) diff --git a/crates/server/src/windows_echo_completion.rs b/crates/server/src/windows_echo_completion.rs new file mode 100644 index 0000000..2549c4d --- /dev/null +++ b/crates/server/src/windows_echo_completion.rs @@ -0,0 +1,444 @@ +//! Interactive retirement of the temporary fixed-probe restriction. Never approves jobs. +use crate::{auth::Principal, jobs::Error, windows_checkpoint_review::access}; +use axum::{ + Json, Router, + extract::{Path, State}, + http::{HeaderMap, StatusCode}, + routing::{get, post}, +}; +use chrono::{Duration, SubsecRound, Utc}; +use openssl::{ + pkey::{Id, PKey}, + sign::Verifier, +}; +use rmm_domain::{ + checkpoint_repair::{SignedReceipt, inventory_sha256}, + jobs::{ExecutionPermitPayload, JobPayload, hash}, + windows_echo_completion::{DOMAIN, Receipt, Witness, successful_outcome}, + windows_echo_probe::{AGENT, ASSET, ProbeReceipt, TENANT, TEST_PRINCIPAL}, + windows_sync_history::case_witness, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{Postgres, Row, Transaction}; +use uuid::Uuid; +type Result = std::result::Result; +fn mismatch() -> Error { + Error(StatusCode::CONFLICT, "WINDOWS_ECHO_COMPLETION_MISMATCH") +} +fn browser(p: &Principal) -> Result<&str> { + if p.name != TEST_PRINCIPAL + || p.tenant != TENANT + || !p.testsimulation + || !p.operator + || p.identity.is_some() + || p.scopes.is_some() + || p.csrf.is_none() + { + return Err(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED")); + } + p.session_hash + .as_deref() + .ok_or(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED")) +} +pub fn routes(r: Router) -> Router { + r.route( + "/api/v1/tenants/{tenant}/windows-echo-completion", + get(read), + ) + .route( + "/api/v1/tenants/{tenant}/windows-echo-completion/confirm", + post(confirm), + ) + .route( + "/api/v1/tenants/{tenant}/windows-echo-completion/receipt", + get(download), + ) +} +fn verify(s: &crate::State, bytes: &[u8], signature: &[u8]) -> Result<()> { + let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519) + .map_err(|_| mismatch())?; + if bytes.len() > 65536 + || signature.len() != 64 + || !Verifier::new_without_digest(&key) + .map_err(|_| mismatch())? + .verify_oneshot(signature, bytes) + .map_err(|_| mismatch())? + { + return Err(mismatch()); + } + Ok(()) +} +struct Review { + witness: Witness, + existing: Option, +} +impl Review { + fn view(&self) -> Value { + json!({"witness":self.witness,"witness_sha256":self.witness.digest(), + "receipt":self.existing.as_ref().and_then(|s|serde_json::from_slice::(&s.payload).ok())}) + } +} +async fn review(tx: &mut Transaction<'_, Postgres>, s: &crate::State) -> Result { + review_for(tx, s, &case_witness()).await +} +async fn review_for( + tx: &mut Transaction<'_, Postgres>, + s: &crate::State, + expected: &Value, +) -> Result { + crate::agent_service::control_lock(tx, TENANT, AGENT).await?; + let dev=sqlx::query("SELECT asset_id,revoked_at IS NULL AS active,enrollment_generation,assignment_version,connection_boot_id,restore_blocked,sequence_regressed,sync_recovery_required FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 FOR UPDATE") + .bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?; + if dev.get::("asset_id") != ASSET + || !dev.get::("active") + || dev.get::("enrollment_generation") != 1 + || dev.get::("assignment_version") != 1 + || dev.get::("restore_blocked") + || dev.get::("sequence_regressed") + || dev.get::("sync_recovery_required") + { + return Err(mismatch()); + } + let row = sqlx::query( + "SELECT receipt,signature,receipt_id FROM windows_echo_probe_scopes WHERE tenant_id=$1", + ) + .bind(TENANT) + .fetch_one(&mut **tx) + .await?; + let raw: Vec = row.get("receipt"); + let sig: Vec = row.get("signature"); + verify(s, &raw, &sig)?; + let probe: ProbeReceipt = serde_json::from_slice(&raw)?; + if !probe.matches_reviewed_witness(expected, probe.issued_at) + || probe.receipt_id != row.get::("receipt_id") + { + return Err(mismatch()); + } + let scope = &probe.scope; + let job=sqlx::query("SELECT state,payload,payload_hash,result FROM jobs WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND job_id=$4 AND attempt_id=$5 AND operation_id=$6 FOR SHARE") + .bind(TENANT).bind(AGENT).bind(ASSET).bind(scope.job_id).bind(scope.attempt_id).bind(scope.operation_id).fetch_one(&mut **tx).await?; + let mut outcome: Value = job.get::, _>("result").ok_or_else(mismatch)?; + outcome + .as_object_mut() + .ok_or_else(mismatch)? + .remove("grant_id"); + outcome["state"] = json!(job.get::("state")); + let job_bytes: Vec = job.get("payload"); + let payload: JobPayload = serde_json::from_slice(&job_bytes)?; + if job_bytes != probe.job_payload_bytes + || !scope.matches_job(&payload) + || job.get::("payload_hash") != scope.job_payload_hash + || !successful_outcome(&outcome) + { + return Err(mismatch()); + } + let extra: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT FROM jobs WHERE tenant_id=$1 AND agent_id=$2 AND job_id!=$3)", + ) + .bind(TENANT) + .bind(AGENT) + .bind(scope.job_id) + .fetch_one(&mut **tx) + .await?; + let existing = + sqlx::query("SELECT payload,signature FROM windows_echo_completions WHERE tenant_id=$1") + .bind(TENANT) + .fetch_optional(&mut **tx) + .await?; + // Only the first transition requires the original single-job inventory. + if extra && existing.is_none() { + return Err(mismatch()); + } + let grant=sqlx::query("SELECT grant_id,payload,signature FROM execution_permits WHERE tenant_id=$1 AND job_id=$2 AND attempt_id=$3") + .bind(TENANT).bind(scope.job_id).bind(scope.attempt_id).fetch_one(&mut **tx).await?; + let graw: Vec = grant.get("payload"); + let gsig: Vec = grant.get("signature"); + verify(s, &graw, &gsig)?; + let g: ExecutionPermitPayload = serde_json::from_slice(&graw)?; + if g.domain != "rmm.execution-permit" + || g.schema_version != 1 + || g.action != "run_script" + || g.agent_update_plan_id.is_some() + || (g.enrollment_generation, g.assignment_version) + != (scope.enrollment_generation, scope.assignment_version) + || g.max_runtime_seconds != scope.max_runtime_seconds + || g.not_before < scope.not_before + || g.start_before > scope.start_before + || g.not_before >= g.start_before + || g.start_before - g.not_before > Duration::seconds(60) + || g.grant_id != grant.get::("grant_id") + || g.job_id != scope.job_id + || g.attempt_id != scope.attempt_id + || g.plan_hash != scope.plan_hash + || g.job_payload_hash != scope.job_payload_hash + || g.agent_id != AGENT + || g.tenant_id != TENANT + || g.asset_id != ASSET + || g.execution_identity != "agent_service" + || g.key_id != s.job_signer.key_id + || job.get::, _>("result").unwrap_or_default()["grant_id"] + != g.grant_id.to_string() + { + return Err(mismatch()); + } + let authorized:bool=sqlx::query_scalar("SELECT EXISTS(SELECT FROM authorizations WHERE tenant_id=$1 AND authorization_id=$2 AND operation_id=$3 AND plan_id=$4 AND plan_hash=$5 AND principal=$6 AND approval_origin='dev_test_browser_simulation' AND testsimulation AND revoked_at IS NULL)") + .bind(TENANT).bind(g.authorization_id).bind(scope.operation_id).bind(scope.plan_id).bind(&scope.plan_hash).bind(TEST_PRINCIPAL).fetch_one(&mut **tx).await?; + if !authorized { + return Err(mismatch()); + } + let boot: Uuid = serde_json::from_value(expected["boot_id"].clone())?; + if dev.get::, _>("connection_boot_id") != Some(boot) { + return Err(mismatch()); + } + let witness = Witness { + scope: scope.clone(), + probe_receipt_id: probe.receipt_id, + probe_receipt_sha256: hash(&raw), + probe_signature_sha256: hash(&sig), + grant_id: g.grant_id, + grant_payload_sha256: hash(&graw), + grant_signature_sha256: hash(&gsig), + outcome_sha256: inventory_sha256(&outcome)?, + boot_id: boot, + }; + let existing = existing.map(|r| SignedReceipt { + payload: r.get("payload"), + signature: r.get("signature"), + }); + if let Some(signed) = &existing { + verify(s, &signed.payload, &signed.signature)?; + let r: Receipt = serde_json::from_slice(&signed.payload)?; + if !r.valid(r.issued_at) || r.witness != witness || r.key_id != s.job_signer.key_id { + return Err(mismatch()); + } + } + Ok(Review { witness, existing }) +} +async fn read( + State(s): State, + Path(t): Path, + h: HeaderMap, +) -> Result> { + let p = access(&s, &h, t, false).await?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; + crate::permissions::require_principal(&mut tx, &p, "operations:read").await?; + let result = review(&mut tx, &s).await?.view(); + tx.commit().await?; + Ok(Json(result)) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Confirmation { + reviewed: bool, + witness_sha256: String, +} +async fn confirm( + State(s): State, + Path(t): Path, + h: HeaderMap, + Json(input): Json, +) -> Result> { + let p = access(&s, &h, t, true).await?; + confirm_review(&s, &p, input, &case_witness()).await +} +async fn confirm_review( + s: &crate::State, + p: &Principal, + input: Confirmation, + expected: &Value, +) -> Result> { + let t = p.tenant; + let session = browser(p)?; + if !input.reviewed { + return Err(Error(StatusCode::BAD_REQUEST, "REVIEW_REQUIRED")); + } + let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; + let allowed: bool = sqlx::query_scalar("SELECT lock_windows_echo_probe_reviewer()") + .fetch_one(&mut *tx) + .await?; + if !allowed { + return Err(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED")); + } + let mut r = review_for(&mut tx, s, expected).await?; + if r.witness.digest().as_deref() != Some(input.witness_sha256.as_str()) { + return Err(mismatch()); + } + if r.existing.is_none() { + // SQLx binds PostgreSQL timestamps at microsecond precision. Normalize + // before signing so JSON's parser cannot round a nanosecond differently. + let now = Utc::now().trunc_subsecs(6); + let receipt = Receipt { + domain: DOMAIN.into(), + schema_version: 1, + receipt_id: Uuid::new_v4(), + witness: r.witness.clone(), + witness_sha256: input.witness_sha256, + key_id: s.job_signer.key_id.clone(), + issued_at: now, + valid_until: now + Duration::minutes(10), + confirmed_by: p.name.clone(), + approval_origin: p.approval_origin().into(), + testsimulation: true, + ready: false, + helper_ready: false, + unlock: false, + }; + if !receipt.valid(now) { + return Err(mismatch()); + } + let raw = serde_json::to_vec(&receipt)?; + let signature = s.job_signer.sign(&raw)?; + sqlx::query("INSERT INTO windows_echo_completions(tenant_id,receipt_id,witness_sha256,payload,signature,confirmed_by,session_hash,issued_at,valid_until) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)") + .bind(t).bind(receipt.receipt_id).bind(&receipt.witness_sha256).bind(&raw).bind(&signature).bind(&p.name).bind(session).bind(now).bind(receipt.valid_until).execute(&mut *tx).await?; + sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_echo_scope_completed',$4)") + .bind(t).bind(receipt.receipt_id).bind(&p.name).bind(json!({"witness":receipt.witness,"witness_sha256":receipt.witness_sha256, + "receipt_sha256":hash(&raw),"approval_origin":receipt.approval_origin,"testsimulation":true,"ready":false,"helper_ready":false,"unlock":false})).execute(&mut *tx).await?; + r.existing = Some(SignedReceipt { + payload: raw, + signature, + }); + } + tx.commit().await?; + Ok(Json(r.view())) +} +async fn download( + State(s): State, + Path(t): Path, + h: HeaderMap, +) -> Result> { + let p = access(&s, &h, t, false).await?; + browser(&p)?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; + crate::permissions::require_principal(&mut tx, &p, "plans:approve").await?; + let signed = review(&mut tx, &s) + .await? + .existing + .ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?; + let r: Receipt = serde_json::from_slice(&signed.payload)?; + if !r.valid(Utc::now()) { + return Err(Error( + StatusCode::CONFLICT, + "WINDOWS_ECHO_COMPLETION_EXPIRED", + )); + } + tx.commit().await?; + Ok(Json(signed)) +} + +#[cfg(test)] +pub(super) async fn test_completed_echo( + admin: &sqlx::PgPool, + s: &crate::State, + p: &Principal, + expected: &Value, +) { + let nanosecond = chrono::DateTime::from_timestamp(1794820000, 123456789).unwrap(); + let compare = |t: chrono::DateTime| { + sqlx::query_scalar::<_, bool>("SELECT $1::timestamptz=$2::text::timestamptz") + .bind(t) + .bind(t.to_rfc3339()) + }; + assert!(!compare(nanosecond).fetch_one(admin).await.unwrap()); + assert!( + compare(nanosecond.trunc_subsecs(6)) + .fetch_one(admin) + .await + .unwrap() + ); + let row = + sqlx::query("SELECT job_id,attempt_id,grant_id FROM execution_permits WHERE tenant_id=$1") + .bind(TENANT) + .fetch_one(admin) + .await + .unwrap(); + let grant: Uuid = row.get("grant_id"); + let job: Uuid = row.get("job_id"); + let original_counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs),(SELECT count(*) FROM authorizations),(SELECT count(*) FROM execution_permits)").fetch_one(admin).await.unwrap(); + let confirm = |digest: String| Confirmation { + reviewed: true, + witness_sha256: digest, + }; + assert!( + confirm_review(s, p, confirm("0".repeat(64)), expected) + .await + .is_err() + ); + let mut no_browser = p.clone(); + no_browser.session_hash = None; + assert_eq!( + confirm_review(s, &no_browser, confirm("0".repeat(64)), expected) + .await + .unwrap_err() + .0, + StatusCode::FORBIDDEN + ); + let outcome = json!({"exit_code":0,"stdout":rmm_domain::windows_echo_probe::OUTPUT.as_bytes(),"stderr":[],"error_code":"","output_truncated":false,"reboot_required":false, + "evidence":{"execution_sid":"S-1-5-19","execution_policy_scope":"process","execution_policy_requested":"RemoteSigned","postconditions_passed":true, + "script_sha256":hash(rmm_domain::windows_echo_probe::SCRIPT.as_bytes())},"grant_id":grant}); + sqlx::query("UPDATE jobs SET state='succeeded',result=$2 WHERE job_id=$1") + .bind(job) + .bind(outcome) + .execute(admin) + .await + .unwrap(); + sqlx::query("UPDATE agent_installations SET restore_blocked=false WHERE agent_id=$1") + .bind(AGENT) + .execute(admin) + .await + .unwrap(); + let mut tx = rmm_persistence::tenant_tx(&s.pool, TENANT).await.unwrap(); + let r = review_for(&mut tx, s, expected).await.unwrap(); + tx.rollback().await.unwrap(); + let digest = r.witness.digest().unwrap(); + assert!( + confirm_review(s, p, confirm("0".repeat(64)), expected) + .await + .is_err() + ); + let first = confirm_review(s, p, confirm(digest.clone()), expected) + .await + .unwrap() + .0; + assert_eq!(first["receipt"]["ready"], false); + assert_eq!(first["receipt"]["helper_ready"], false); + assert_eq!(first["receipt"]["unlock"], false); + assert_eq!(first["receipt"]["testsimulation"], true); + assert_eq!( + confirm_review(s, p, confirm(digest), expected) + .await + .unwrap() + .0, + first + ); + let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs),(SELECT count(*) FROM authorizations),(SELECT count(*) FROM execution_permits)").fetch_one(admin).await.unwrap(); + assert_eq!(counts, original_counts); + assert!( + sqlx::query("DELETE FROM windows_echo_completions") + .execute(admin) + .await + .is_err() + ); + assert!( + sqlx::query("UPDATE windows_echo_completions SET witness_sha256=repeat('0',64)") + .execute(admin) + .await + .is_err() + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM windows_echo_probe_scopes") + .fetch_one(admin) + .await + .unwrap(), + 1 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM audit_events WHERE event_type='windows_echo_scope_completed'" + ) + .fetch_one(admin) + .await + .unwrap(), + 1 + ); +} diff --git a/crates/server/src/windows_echo_probe.rs b/crates/server/src/windows_echo_probe.rs index ffeed98..6c34f61 100644 --- a/crates/server/src/windows_echo_probe.rs +++ b/crates/server/src/windows_echo_probe.rs @@ -515,4 +515,5 @@ pub(super) async fn test_fixed_echo( tx.rollback().await.unwrap(); } } + crate::windows_echo_completion::test_completed_echo(admin,s,&p,&w).await; } diff --git a/crates/updater-handoff/src/lib.rs b/crates/updater-handoff/src/lib.rs index c9328e2..9cd1e0c 100644 --- a/crates/updater-handoff/src/lib.rs +++ b/crates/updater-handoff/src/lib.rs @@ -67,6 +67,7 @@ pub enum PinTransition { UnchangedLinuxGeneralV1, LinuxGeneralFullV1, WindowsCodePairV1, + WindowsCodePairClockV1, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -78,6 +79,7 @@ pub enum FileRole { LinuxFullPin, WindowsSettings, WindowsPin, + WindowsTimeProfile, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -197,6 +199,13 @@ impl Handoff { FileRole::WindowsSettings, FileRole::WindowsPin, ], + PinTransition::WindowsCodePairClockV1 => vec![ + FileRole::AgentBinary, + FileRole::HelperBinary, + FileRole::WindowsSettings, + FileRole::WindowsPin, + FileRole::WindowsTimeProfile, + ], }; ensure!(roles == expected_roles, "HANDOFF_FILE_SET"); for file in &self.files { @@ -210,7 +219,7 @@ impl Handoff { && self.files[1].new_sha256 == self.target.helper_sha256, "HANDOFF_FILE_IMAGE_BINDING" ); - if self.files.len() == 4 { + if self.files.len() >= 4 { ensure!( self.files[3].old_sha256 == self.predecessor.pin_sha256 && self.files[3].new_sha256 == self.target.pin_sha256, @@ -250,7 +259,7 @@ impl Handoff { ], "HANDOFF_UNSUPPORTED_SERVICE_SET" ), - PinTransition::WindowsCodePairV1 => ensure!( + PinTransition::WindowsCodePairV1 | PinTransition::WindowsCodePairClockV1 => ensure!( self.stop_set == [Service::WindowsAgent, Service::WindowsHelper], "HANDOFF_UNSUPPORTED_SERVICE_SET" ), diff --git a/crates/updater-handoff/tests/handoff_contract.rs b/crates/updater-handoff/tests/handoff_contract.rs index c3eacb7..ff3ffbd 100644 --- a/crates/updater-handoff/tests/handoff_contract.rs +++ b/crates/updater-handoff/tests/handoff_contract.rs @@ -96,6 +96,31 @@ fn handoff() -> Handoff { fn key() -> SigningKey { SigningKey::from_bytes(&[73; 32]) } +#[test] +fn windows_clock_transition_keeps_historical_four_file_shape_and_requires_exact_new_fifth_role() { + let mut value = handoff(); + value.pin_transition = PinTransition::WindowsCodePairV1; + value.stop_set = vec![Service::WindowsAgent, Service::WindowsHelper]; + value.files[2].role = FileRole::WindowsSettings; + value.files[3].role = FileRole::WindowsPin; + value.validate().unwrap(); + let old = value.bytes().unwrap(); + value.pin_transition = PinTransition::WindowsCodePairClockV1; + assert!(value.validate().is_err()); + value.files.push(FileTransition { + role: FileRole::WindowsTimeProfile, + old_sha256: h(23), + new_sha256: h(24), + }); + value.validate().unwrap(); + value.files[3].new_sha256 = h(25); + assert!(value.validate().is_err()); + value.files[3].new_sha256 = value.target.pin_sha256.clone(); + value.files.swap(3, 4); + assert!(value.validate().is_err()); + let historical: Handoff = serde_json::from_slice(&old).unwrap(); + assert_eq!(historical.bytes().unwrap(), old); +} fn open(handoff: &Handoff) -> Journal { Journal::open(&handoff.bytes().unwrap(), key().verifying_key().to_bytes()).unwrap() } diff --git a/crates/updater-worker/src/history.rs b/crates/updater-worker/src/history.rs index 52a9cbe..2470dd1 100644 --- a/crates/updater-worker/src/history.rs +++ b/crates/updater-worker/src/history.rs @@ -614,6 +614,9 @@ fn complete_native_history( F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, }; matches!(head.evidence,Evidence::ReplaceIntent{role} if role==expected) } @@ -682,6 +685,9 @@ fn complete_native_history( F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, }; time(&|e| matches!(e,Evidence::Replaced{role,..} if *role==expected))? } diff --git a/crates/updater-worker/src/ledger.rs b/crates/updater-worker/src/ledger.rs index 9400324..db770f0 100644 --- a/crates/updater-worker/src/ledger.rs +++ b/crates/updater-worker/src/ledger.rs @@ -37,6 +37,9 @@ fn file_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole { NativeFileRole::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, NativeFileRole::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, NativeFileRole::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + NativeFileRole::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + NativeFileRole::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + NativeFileRole::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, } } @@ -189,6 +192,10 @@ impl<'a, 'stopped> OwnedLedger<'a, 'stopped> { update_handoff::NativeService::Full => { rmm_updater_linux::services::Service::Full } + update_handoff::NativeService::WindowsAgent + | update_handoff::NativeService::WindowsHelper => { + anyhow::bail!("UPDATE_WINDOWS_SERVICE_ON_LINUX") + } }; let proof = self .guard @@ -463,6 +470,9 @@ impl UpdateParticipantGuard for OwnedGuard<'_, '_> { NativeFileRole::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, NativeFileRole::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, NativeFileRole::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + NativeFileRole::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + NativeFileRole::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + NativeFileRole::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, }; match (effect, stage) { (NativeEffect::StopService { .. }, NativeEffectStage::Observe) => { diff --git a/deploy/windows/Install-DevelopmentAgentSuccessor.ps1 b/deploy/windows/Install-DevelopmentAgentSuccessor.ps1 new file mode 100644 index 0000000..b828c52 --- /dev/null +++ b/deploy/windows/Install-DevelopmentAgentSuccessor.ps1 @@ -0,0 +1,159 @@ +#requires -Version 5.1 +#requires -RunAsAdministrator +[CmdletBinding()] +param( + [Parameter(Mandatory)][ValidateSet('Prepare','InstallPassive','PrepareProfile','PublishProfile','Read')][string]$Action, + [Parameter(Mandatory)][string]$ManifestSha256 +) +$ErrorActionPreference = 'Stop' +if ($ManifestSha256 -cnotmatch '^[0-9a-f]{64}$') { throw 'Expected exact development manifest digest.' } +$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap' +$manifestPath = Join-Path (Join-Path $bootstrap $ManifestSha256) 'successor.json' +if ((Get-FileHash -LiteralPath $manifestPath).Hash.ToLowerInvariant() -cne $ManifestSha256) { throw 'Manifest changed.' } +$m = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json +$fields = 'agent_build_sha256,case_id,linux_proof_sha256,new_agent_sha256,old_agent_sha256,old_pin_sha256,old_profile_sha256,old_settings_sha256,previous_publication_sha256,windows_proof_sha256' +if ((($m.PSObject.Properties.Name | Sort-Object) -join ',') -cne $fields -or + [guid]::ParseExact($m.case_id,'D').ToString() -cne $m.case_id) { throw 'Unexpected development manifest schema.' } +foreach ($p in $m.PSObject.Properties) { + if ($p.Name -cne 'case_id' -and $p.Value -cnotmatch '^[0-9a-f]{64}$') { throw 'Manifest digest format.' } +} +if ($m.old_agent_sha256 -ceq $m.new_agent_sha256) { throw 'No successor code.' } + +# Reuse the already qualified native file-ID/process/ACL and stop/swap/start +# implementation. Load declarations only, with exact original source checks. +$prior = Join-Path $bootstrap 'mvp-successor-prerequisites' +$common = Join-Path $prior 'Set-PassiveJobPair.ps1' +$publication = Join-Path $prior 'Publish-JobPairTimeProfile.ps1' +$commonExpected = 'b70313bfec6e2f055e0f9554d69a9a44acec4abc8afea457a059d33db3e5e410' +$publicationExpected = '6b6f64192d82f98c449ea3c36c5da0f8b179ecd5d6f944f36151969d645b9fb5' +if ((Get-FileHash -LiteralPath $common).Hash.ToLowerInvariant() -cne $commonExpected -or + (Get-FileHash -LiteralPath $publication).Hash.ToLowerInvariant() -cne $publicationExpected) { throw 'Original native controllers changed.' } +$text = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($common)) +$first = "`n`$originalCase = " +$last = "`nif (`$Mode -eq 'Read') {" +$i = $text.IndexOf($first,[StringComparison]::Ordinal) +$j = $text.IndexOf($last,[StringComparison]::Ordinal) +if ($i -lt 0 -or $j -le $i -or $i -ne $text.LastIndexOf($first,[StringComparison]::Ordinal) -or + $j -ne $text.LastIndexOf($last,[StringComparison]::Ordinal)) { throw 'Native declaration boundary.' } +$EchoPassive = $false +$Mode = 'Read' +. ([scriptblock]::Create($text.Substring($i,$j-$i))) + +CheckControl $bootstrap $true +CheckControl (Split-Path $manifestPath) $true +CheckControl $manifestPath $false +$previousCase = Join-Path $bootstrap 'job-passive-pair-c62d698d-d044-4815-acbe-3eeb383d44d5' +$previousPublication = Join-Path $previousCase 'profile-published.json' +CheckControl $previousCase $true +CheckControl $previousPublication $false +if ((Hash $previousPublication) -cne $m.previous_publication_sha256) { throw 'Previous publication changed.' } +$previous = Get-Content -LiteralPath $previousPublication -Raw | ConvertFrom-Json +if ($previous.successor_revision -ne 4 -or $previous.configuration.sha256 -cne $m.old_profile_sha256 -or + $previous.agent.image_file.sha256 -cne $m.old_agent_sha256) { throw 'Expected actual revision 4 predecessor.' } +$id = $m.case_id +$work = Join-Path $bootstrap ('job-passive-pair-' + $id) +$oldHashes = [ordered]@{agent=$m.old_agent_sha256;settings=$m.old_settings_sha256;pin=$m.old_pin_sha256} +$newHashes = [ordered]@{agent=$m.new_agent_sha256} +$source = Join-Path (Join-Path $bootstrap $newHashes.agent) 'rmm-agent-windows.exe' +$profileHash = $m.old_profile_sha256 +$previousRevision = 4 +$previousPublicationHash = $m.previous_publication_sha256 +$platformArchive = Join-Path $previousCase 'profile-platform.json' +$roleArchive = Join-Path $previousCase 'profile-role-{0}.json' +$agentBuildHash = $m.agent_build_sha256 +$linuxProofHash = $m.linux_proof_sha256 +$unitHash = $m.windows_proof_sha256 +$unitProof = Join-Path (Split-Path $manifestPath) 'windows-proof.json' +foreach ($entry in @(@('windows-proof.json',$unitHash),@('linux-proof.json',$linuxProofHash),@('agent-build.json',$agentBuildHash))) { + $path = Join-Path (Split-Path $manifestPath) $entry[0] + CheckControl $path $false + if ((Hash $path) -cne $entry[1]) { throw 'Successor qualification evidence changed.' } +} +# The fixture receipts must explicitly report a successful native run. Their +# detailed source/artifact bindings are reviewed in the local build manifest. +foreach ($name in @('windows-proof.json','linux-proof.json')) { + $proof = Get-Content -LiteralPath (Join-Path (Split-Path $manifestPath) $name) -Raw | ConvertFrom-Json + if ($proof.verified -ne $true) { throw 'Native prerequisite did not pass.' } +} +foreach ($name in @('settings','pin')) { + $baseline = $locations[$name] + if (Test-Path -LiteralPath (Join-Path $work ('old-'+$name))) { $baseline = Join-Path $work ('old-'+$name) } + $sha = [Security.Cryptography.SHA256]::Create() + try { $newHashes[$name] = [BitConverter]::ToString($sha.ComputeHash((Get-SuccessorPinBytes $name $baseline))).Replace('-','').ToLowerInvariant() } + finally { $sha.Dispose() } +} +$EchoPassive = $true # include stable journal file IDs in preservation evidence +$pubText = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($publication)) +$i = $pubText.IndexOf('function RequireNewPassivePair {',[StringComparison]::Ordinal) +$j = $pubText.IndexOf("`nif (`$Action -ceq 'Read') {",[StringComparison]::Ordinal) +if ($i -lt 0 -or $j -le $i) { throw 'Publication declaration boundary.' } +. ([scriptblock]::Create($pubText.Substring($i,$j-$i))) + +if ($Action -ceq 'Read') { + [ordered]@{id=$id;files=(CurrentFiles);device=(PreservedDevice);agent=(Service 'agent');helper=(Service 'helper');markers=@(Get-ChildItem -LiteralPath $work -File -Filter '*.json' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name)} | ConvertTo-Json -Depth 12 -Compress + return +} +if ($Action -ceq 'Prepare') { + VerifyPassiveContext + VerifyFiles (CurrentFiles) $oldHashes + if (Test-Path -LiteralPath $work) { throw 'Existing case: read only.' } + [RmmTimeProfileCase]::CreatePrivateOnce($work) + $before = CurrentFiles + $device = PreservedDevice + $agent = LiveRole 'agent' $oldHashes.agent + $helper = LiveRole 'helper' $helperHash + PrepareFiles $before + Record 'prepared' ([ordered]@{id=$id;manifest_sha256=$ManifestSha256;files=$before;device=$device;agent=$agent;helper=$helper}) + Write-Output "Prepared passive successor $id" + return +} +$preparedPair = LoadRecord 'prepared' +if ($preparedPair.id -cne $id -or $preparedPair.manifest_sha256 -cne $ManifestSha256) { throw 'Different prepared successor.' } +if ($Action -ceq 'InstallPassive') { + VerifyPassiveContext + if (Test-Path -LiteralPath (Marker 'install-intent')) { throw 'Existing transition: read only.' } + if (!(JsonEqual $preparedPair.files (CurrentFiles)) -or !(JsonEqual $preparedPair.device (PreservedDevice)) -or + !(JsonEqual $preparedPair.agent (LiveRole 'agent' $oldHashes.agent)) -or + !(JsonEqual $preparedPair.helper (LiveRole 'helper' $helperHash))) { throw 'Prepared predecessor changed.' } + Record 'install-intent' @{id=$id;manifest_sha256=$ManifestSha256} + StopKnownRole 'agent' $agentName $preparedPair.agent 'install' + StopKnownRole 'helper' $helperName $preparedPair.helper 'install' + foreach ($name in $locations.Keys) { + $inputPath = Join-Path $work ('new-'+$name) + if ($name -ceq 'agent') { $inputPath=$source } + SwapFile $name $inputPath $preparedPair.files.$name $newHashes.$name 'install' + } + if (!(JsonEqual $preparedPair.device (PreservedDevice))) { throw 'Device or history file identities changed.' } + StartKnownRole 'helper' $helperName $helperHash 'install' + StartKnownRole 'agent' $agentName $newHashes.agent 'install' + Record 'installed' ([ordered]@{id=$id;files=(CurrentFiles);device=(PreservedDevice);agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $helperHash);job_mode=$false;clock_qualified=$false}) + Write-Output "Installed passive successor $id" + return +} +RequireNewPassivePair +$installed = LoadRecord 'installed' +if ($installed.id -cne $id -or $installed.job_mode -ne $false -or $installed.clock_qualified -ne $false) { throw 'Expected passive installation.' } +$activation = Marker 'profile-publish-intent' +$ready = Marker 'profile-prepared' +$success = Marker 'profile-published' +if ($Action -ceq 'PrepareProfile') { + VerifyPassiveContext + if (Test-Path -LiteralPath $ready) { throw 'Profile already prepared: read only.' } + BuildSuccessor + Write-Output "Prepared successor profile $id" + return +} +$prepared = LoadRecord 'profile-prepared' +CheckPrepared +VerifyPassiveContext +$held = LoadRecord 'profile-independent-native-read' +if (!(JsonEqual $held.agent (LiveRole 'agent' $newHashes.agent)) -or + !(JsonEqual $held.helper (LiveRole 'helper' $helperHash)) -or + !(JsonEqual $held.device (PreservedDevice))) { throw 'Actual passive role observations changed.' } +Record 'profile-publish-intent' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');prepared_sha256=(Hash $ready)}) +StopKnownRole 'agent' $agentName $held.agent 'time' +StopKnownRole 'helper' $helperName $held.helper 'time' +$locations.Add('time',$target) +SwapFile 'time' (Join-Path $work 'new-time-profile') $prepared.predecessor $prepared.successor_sha256 'time' +$locations.Remove('time') +FinishPublication diff --git a/docs/development.md b/docs/development.md index 7505d1d..3dbf613 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Linux-first-Entwicklung und reale VM-Abnahme -Stand: 2026-11-15 · Spezifikation 1.25. Das begrenzte Linux-MVP ist inzwischen +Stand: 2026-11-16 · Spezifikation 1.26. 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,16 @@ 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. +## Fortsetzung Windows-MVP (Version 1.26) + +Die weitere Windows-Abnahme ist ausdrücklich beauftragt, möglichst parallel. +Root koordiniert die eine Test-VM, Dienstwechsel und Browsergenehmigungen; +unabhängige Quellarbeiten laufen getrennt. Die bisherige zusätzliche +Echo-Einschränkung wird ausschließlich durch einen gesonderten interaktiven +Abschluss mit Originalnachweisen beendet. Keine Bereitschaft oder Jobfreigabe +entsteht daraus. Quellen-/Build-/native VM-Ergebnisse bleiben getrennt; +[aktuelles Protokoll](windows-mvp-completion.md). + ## Aktuelle MVP-Anmeldung über SSH-Tunnel (Version 1.25) WebUI und MCP bleiben an Server-Loopback gebunden. Für den aktuellen MVP diff --git a/docs/project-decisions.md b/docs/project-decisions.md index 6683a4a..42f43e9 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,23 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-15**, Spezifikation **1.25** (`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-16**, Spezifikation **1.26** (`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. + +## Windows-MVP vollständig fortsetzen (Version 1.26) + +Der Betreiber beauftragt die verbleibenden Windows-MVP-Arbeiten möglichst +parallel. Der vorhandene dev/test-Login und die ausdrücklich gekennzeichnete +simulierte WebUI-Bedienung reichen auch für die folgenden festen Abnahmepläne; +OIDC wird keine neue MVP-Voraussetzung. Die zusätzliche Einschränkung auf den +bereits erfolgreich ausgeführten Echoauftrag darf nur durch einen eigenen +interaktiven administrativen Abschluss mit unabhängig geprüften Originalen +und append-only Nachweisen historienerhaltend beendet werden. Keine direkte +API-/DB-Jobgenehmigung, keine Journal- oder Identitätsrücksetzung. Der Abschluss +verleiht weder Bereitschaft noch eine Jobgenehmigung. Regulärer unabhängiger +SignedSync beider Rollen und jeder feste WebUI-genehmigte Job bleiben nötig. + +Die parallelen Quellarbeiten und tatsächlichen nativen Abnahmen werden in +[windows-mvp-completion.md](windows-mvp-completion.md) getrennt protokolliert. +Ein Updater-OS-Port oder ein Build ist kein durchgeführtes Selbstupdate. ## MVP-Verwaltung über SSH-Tunnel ohne OIDC (Version 1.25) diff --git a/docs/windows-certificate-runtime-acceptance.md b/docs/windows-certificate-runtime-acceptance.md new file mode 100644 index 0000000..b292eec --- /dev/null +++ b/docs/windows-certificate-runtime-acceptance.md @@ -0,0 +1,92 @@ +# Native Windows-Zertifikatserneuerung: vorbereitete Abnahme + +Stand 2026-11-16. **Vorbereitet, noch nicht nativ ausgeführt.** Dieser Ablauf +ergänzt [die bisherigen Zertifikatsnachweise](windows-certificate-renewal.md) +um tatsächliches LocalService-Datei-I/O und echte Serverantworten. Er ist kein +Nachweis einer bereits erfolgten Erneuerung des permanenten Agentzertifikats. + +Das Beispiel `windows_certificate_acceptance` verwendet die unveränderten +Produktimplementierungen `RotationStore`, `ProtectedKeyFiles` und `Journal`. +Es akzeptiert ausschließlich den bestehenden LocalService-Prozesstoken ohne +Administratorrechte oder Threadimpersonation. Deshalb wird das geprüfte Binary +als Kind eines einzeln WebUI-genehmigten LocalService-PowerShell-Auftrags +gestartet; eine Administrator-Konsole ersetzt diesen Rollenbeleg nicht. + +## Vorbereitung und Grenzen + +Der Bootstrap legt einen neuen zufälligen Fall unter +`C:\ProgramData\RustDiscovery\certificate-acceptance\` an. Nur SYSTEM, +Administratoren und die bestehende Agent-Service-SID erhalten geerbte Rechte. +Die beiden Eingabedateien sind `ca.pem` mit der öffentlichen Projekt-CA und +`enrollment-token` mit einem neuen, einmaligen Enrollmentnachweis ausschließlich +für eine **separate Testidentität**. Den Token weder in den Plan noch in +Jobausgabe, Dokumentation oder Repository aufnehmen. Das geprüfte Binary wird +vom Bootstrap geschützt und mit seinem exakten Hash im Testplan festgehalten. + +Die Probe liest niemals State, private Schlüssel oder Zertifikat der permanenten +Installation. Ein Startmarker verhindert Wiederholung des Enrollment-/Renewal- +Ablaufs bei erneutem Aufruf. Fehler werden nur als fester Fehlercode und Phase +ausgegeben; der isolierte Fall bleibt zur Nachprüfung erhalten. Es gibt keine +automatische Neuregistrierung, Geheimnisausgabe oder Löschung fremder Dateien. + +## Geplanter tatsächlicher Ablauf + +1. Fester MCP-Antrag für `windows_certificate_acceptance.exe renew ` im + LocalService-Skript. Vor dem WebUI-Klick keine ausführbaren Jobs oder Grants. +2. Enrollment mit eigener lokaler Schlüsselerzeugung, neue Testidentität, + geschützte Schlüssel-/Identitätsdateien und journalisierter Selektor. +3. Tatsächliches mTLS-Hello und Heartbeat mit dem ursprünglichen Testzertifikat. +4. Produktpfad `prepare`, echte Erneuerungsantwort empfangen und absichtlich + **nicht installieren**. SQLite- und KeyFiles-Handles vollständig schließen. +5. Neu öffnen, exakt denselben gespeicherten CSR nachweisen, denselben Request + mit dem noch gültigen alten Testzertifikat erneut senden und byteidentische + Serverantwort prüfen. Das bleibt innerhalb des bestehenden 300s-Overlap. +6. Produktpfad `install`, erneut schließen/öffnen, neues Zertifikat und neue + mTLS-Verbindung mit höherer Verbindungsgeneration samt Heartbeat-ACK prüfen. + Ursprüngliche Testschlüssel-/Zertifikatsdateien müssen unverändert sein. +7. Öffentliche Quittung `renewal-result.json` unabhängig mit Serverbestand und + späterem MCP-Gerätestand vergleichen. Die Probe beweist einen kontrollierten + Erneuerungsaufruf unter LocalService, **nicht** den automatischen 20-Tage- + Schedulertrigger oder einen Betriebssystem-Prozessabsturz. +8. Ausschließlich diese Testidentität über die WebUI widerrufen. Ein neuer, + eigener WebUI-genehmigter Probeauftrag + `windows_certificate_acceptance.exe revoked-read ` verwendet weiter + das erneuerte Testzertifikat. Nur ein tatsächliches HTTP401 nach gültigem + TLS wird als Widerrufsbeleg anerkannt; Netzwerk-/TLS-Fehler genügen nicht. +9. `revocation-result.json` und Serveraudit unabhängig nachlesen. Permanente + Geräteidentität und deren passive Heartbeats müssen erhalten sein. + +Beide Probeausführungen sind eigenständige feste Jobs mit Planhash, simuliertem +Testprincipal und `approval_origin`/`testsimulation` im Audit. Der vorbereitete +Dateipfad oder ein erfolgreicher Crossbuild autorisiert keine Ausführung. + +## Aktive Erneuerung im Quellstand, native Abnahme offen + +Die bisher installierte Version erneuert ausschließlich mit +`enable_jobs=false`. Der neue Quellstand erlaubt zusätzlich automatische +Erneuerung im aktiven **Leerlauf**: kein offener/akzeptierter/unbekannter Auftrag, +keine unvollständigen Verbrauchs-/Start-/Ergebniszeugen, keine offene Helper- +Delegation oder Kontrollantwort, keine ausstehenden Ergebnis-/Inventarereignisse. +Ein frischer regulärer signierter Sync mit qualifizierter Uhr ist vor der +Zulassung erforderlich; ein konfigurierter Helper muss unabhängig bestätigt sein. + +Vor der Netzwerkanfrage schließen die Startgates und die bisherigen Zeitworker. +Ein kleines öffentliches Idlezeugnis wird in **derselben SQLite-Transaktion** +wie der neue CSR und Pendingselektor gespeichert. Es bindet Gerät, Boot, +Originaljournal-/Ledgerdateikennungen, festen Bindinghash, vollständigen +Kontrollhead und die erhaltenen Versuche/Verbrauchs-/Start-/Ergebnisbytes sowie +Helperpin und vorherigen unabhängigen Helperanker. Die Zeile ist append-only. + +Bei Antwortverlust darf ausschließlich derselbe Pendingrequest fortgesetzt +werden, solange alle gebundenen lokalen Zustände exakt erhalten und wirkungslos +sind. Das gespeicherte Zeugnis stellt **keine** Bereitschaft wieder her. Nach +Zertifikatswahl werden authentisierter Kontakt und der normale unabhängige +Agent-/Helpersync erneut benötigt. Ein altes passives Pending ohne dieses +Zeugnis darf nicht durch einen Konfigurationswechsel zum aktiven Request werden. +Ein veränderter Boot, Head, Pin, File-ID oder Ledger verweigert diesen Retry; +keine Legacyidentität, kein Reset und keine nachträgliche Heilung von Unknown. + +Die isolierte Renewalprobe oben verwendet bewusst keine künstlich gealterte +Uhr. Der echte Schedulertrigger und die neue aktive Leerlaufzulassung bleiben +gesonderte native Gates. Quellen-/Crossbuild-/Unitbelege werden nicht als +Dienstabnahme ausgegeben. diff --git a/docs/windows-msi-fixture.md b/docs/windows-msi-fixture.md index 4faaf00..0cbacf3 100644 --- a/docs/windows-msi-fixture.md +++ b/docs/windows-msi-fixture.md @@ -4,7 +4,7 @@ Windows-VM gebaut, unabhängig zurückgelesen und heruntergeladen/gehasht. Eine dabei belegte falsche Annahme über die Tabellenreihenfolge ist im Builder korrigiert; alle Zeileninhalte bleiben strikt geprüft. Noch keine Installation. -[Aktuelle Ergebnisse](windows-mvp-completion.md). +[Aktuelle Ergebnisse](windows-mvp-completion.md). Stand 2026-11-14. Der feste Builder [`Build-MsiFixture.ps1`](../deploy/windows/Build-MsiFixture.ps1) hat auf der diff --git a/docs/windows-mvp-completion.md b/docs/windows-mvp-completion.md index 0a33f81..a3fb12f 100644 --- a/docs/windows-mvp-completion.md +++ b/docs/windows-mvp-completion.md @@ -72,3 +72,63 @@ kein Upgrade des installierten Agenten und kein erfolgreicher MSI-Ausführungsjo Installation 1.0, Noop, Upgrade 1.1 und dessen Noop brauchen jeweils ihren eigenen WebUI-genehmigten Plan. Private Originalberichte einschließlich des fehlgeschlagenen Falls: `devstate/windows-client/mvp-closeout-20261116/`. + +## Zertifikatsschutz und Abschlussvertrag: native Vertragsprüfungen + +Die aktive Zertifikatserneuerung wurde im Quellstand um eine Leerlaufprüfung +erweitert. Offene oder unklare Aufträge, fehlende Wirkungsbelege und laufende +Helperübergaben verhindern die Erneuerung. Der ursprüngliche CSR und der +belegte Leerlaufkontext werden gemeinsam gespeichert. Eine erneute Anfrage +nach Antwortverlust darf nur denselben erhaltenen Kontext nutzen; anschließend +ist ein neuer regulärer signierter Abgleich erforderlich. + +Sieben gezielte Zertifikatstests bestanden zuerst auf der Cloud-Linux-VM +als UID 65534 ohne Netzwerk und mit `no_new_privs`, danach auf Windows 11 +im separaten Administrator-Bootstrapfall. Linux: 7 bestanden, 0 Fehler, +19 gefiltert. Windows: 7 bestanden, 0 Fehler, ein ausdrücklich ignorierter +Administrator-Dateitest, 45 gefiltert. Der ignorierte Fall wird nicht als +bestanden gezählt. Bereitstellungsbinary Windows: +`e64a1506343f19687431cc7dbc6323328dd09e403d177a2dcd119f76ced0974e`. +Dies sind native Vertragsprüfungen; die echte Online-Erneuerung einer +separaten Identität unter LocalService ist weiterhin ein eigener offener Test. + +Der historienerhaltende Abschluss des zusätzlichen Echo-Scopes bestand +ebenfalls zuerst auf der Cloud-Linux-VM und danach nativ auf Windows: +jeweils 1 bestandener gezielter Test, 0 Fehler. Er prüft Originalsignaturen, +exakten erfolgreichen Verbrauch, unveränderte Historie und unveränderliche +Abschlusszeilen. Windows-Binary: +`a902c17334a1ca26fe1caac1863f1ba42b1d74ef56ee7abda2bd71d7df961bf9`. +Die separate PostgreSQL-Vertragsprüfung bestand mit 3 Fällen, einschließlich +fehlender Browserbestätigung, unverändertem Job-/Grantbestand, Idempotenz und +unveränderlichen alten Scopes. Ein dabei reproduzierter Unterschied zwischen +Nanosekunden in JSON und PostgreSQL-Mikrosekunden ist vor der Signatur durch +einheitliche Mikrosekundenpräzision behoben. + +## Serverbereitstellung für den Abschlussdialog + +Der eingefrorene Quellstand mit 249 Inputs und die WebUI bestanden +Windows-GNU-Clippy mit `-D warnings`, Releasebuild und alle **62 WebUI-Tests**. +Der Server wurde auf dem permanenten Cloudserver nativ für ARM64 offline +gebaut. Image `c4c869114a60292c666f2077a77ffeaf968f7f49f8f54417192960affaf682de`, +Serverbinary `aa93af099225af204b913e6737aa595fce0e86b8e0a7eca325839f422cb89f45`. +Quellmanifest: +`aa7bf5b63081b29269712eb565d7519b886e6ce206f27a992c5af27a97ebde96`. + +Migration 19 wurde angewandt und ausschließlich die API mit diesem Image +neu gestartet, am 16. November um **10:18:59 MEZ**. Die zugehörige WebUI ist +bereitgestellt. Gateway- und Datenbankcontainer blieben unverändert. +Job-, Grant- und Autorisierungsbestände blieben bei der Bereitstellung erhalten; +es wurde kein Auftrag angelegt oder genehmigt. + +Die erste Nachprüfung des Entwicklungsrunners stoppte wegen unterschiedlicher +Reihenfolgen der Docker-Mountlisten, später auch der geordneten Konfigurations- +darstellung beim Containerwechsel. Die tatsächliche Konfiguration wurde gegen +den bereits vor diesem Schritt erhaltenen normalisierten Releasebeleg separat +vollständig verglichen: identisch. Originalbelege bleiben erhalten. Weder +Migration noch Containerwechsel wurden zur Korrektur blind wiederholt. + +Für weitere Compose-Aufrufe zu den bestehenden Overlays zuletzt +`/opt/rust-discovery/devstate/windows-mvp-7560235e1adc/mvp-images.compose.yaml` +hinzufügen. Der Abschlussdialog ist damit implementiert und bereitgestellt; +die tatsächliche interaktive Bestätigung und native Anwendung auf die +Windows-Historie sind noch gesondert auszuführen. diff --git a/migrations/0019_windows_echo_completion.sql b/migrations/0019_windows_echo_completion.sql new file mode 100644 index 0000000..d75b63d --- /dev/null +++ b/migrations/0019_windows_echo_completion.sql @@ -0,0 +1,103 @@ +-- No existing scope is retired by this migration. A separate interactive +-- dev/test WebUI decision and a matching native receipt application are needed. +CREATE TABLE windows_echo_completions ( + tenant_id uuid PRIMARY KEY REFERENCES windows_echo_probe_scopes(tenant_id), + receipt_id uuid NOT NULL UNIQUE, witness_sha256 text NOT NULL CHECK(witness_sha256 ~ '^[0-9a-f]{64}$'), + payload bytea NOT NULL, signature bytea NOT NULL CHECK(octet_length(signature)=64), + confirmed_by text NOT NULL CHECK(confirmed_by='simulated-testprincipal-a'), + session_hash text NOT NULL CHECK(session_hash ~ '^[0-9a-f]{64}$'), + issued_at timestamptz NOT NULL, valid_until timestamptz NOT NULL + CHECK(valid_until>issued_at AND valid_until<=issued_at+interval '10 minutes') +); +ALTER TABLE windows_echo_completions ENABLE ROW LEVEL SECURITY; +ALTER TABLE windows_echo_completions FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON windows_echo_completions USING(tenant_id::text=current_setting('app.tenant_id',true)) + WITH CHECK(tenant_id::text=current_setting('app.tenant_id',true)); +GRANT SELECT,INSERT ON windows_echo_completions TO rmm_app; +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON windows_echo_completions + FOR EACH ROW EXECUTE FUNCTION immutable_plan(); + +CREATE FUNCTION check_windows_echo_completion() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE s windows_echo_probe_scopes%ROWTYPE; j jobs%ROWTYPE; p execution_permits%ROWTYPE; r jsonb; w jsonb; +BEGIN + SELECT * INTO STRICT s FROM windows_echo_probe_scopes WHERE tenant_id=NEW.tenant_id; + SELECT * INTO STRICT j FROM jobs WHERE tenant_id=s.tenant_id AND job_id=s.job_id AND attempt_id=s.attempt_id FOR SHARE; + SELECT * INTO STRICT p FROM execution_permits WHERE tenant_id=j.tenant_id AND job_id=j.job_id AND attempt_id=j.attempt_id; + r=convert_from(NEW.payload,'UTF8')::jsonb; w=r->'witness'; + IF r->>'domain' IS DISTINCT FROM 'rmm.dev.windows-echo-completion.v1' OR r->>'schema_version' IS DISTINCT FROM '1' + OR r->>'receipt_id' IS DISTINCT FROM NEW.receipt_id::text + OR r->>'witness_sha256' IS DISTINCT FROM NEW.witness_sha256 + OR r->>'confirmed_by' IS DISTINCT FROM NEW.confirmed_by + OR r->>'approval_origin' IS DISTINCT FROM 'dev_test_browser_simulation' OR r->'testsimulation' IS DISTINCT FROM 'true'::jsonb + OR r->'ready' IS DISTINCT FROM 'false'::jsonb OR r->'helper_ready' IS DISTINCT FROM 'false'::jsonb OR r->'unlock' IS DISTINCT FROM 'false'::jsonb + OR (r->>'issued_at')::timestamptz IS DISTINCT FROM NEW.issued_at OR (r->>'valid_until')::timestamptz IS DISTINCT FROM NEW.valid_until + OR w->'scope' IS DISTINCT FROM convert_from(s.receipt,'UTF8')::jsonb->'scope' + OR w->>'probe_receipt_id' IS DISTINCT FROM s.receipt_id::text + OR w->>'probe_receipt_sha256' IS DISTINCT FROM encode(sha256(s.receipt),'hex') + OR w->>'probe_signature_sha256' IS DISTINCT FROM encode(sha256(s.signature),'hex') + OR w->>'grant_id' IS DISTINCT FROM p.grant_id::text + OR w->>'grant_payload_sha256' IS DISTINCT FROM encode(sha256(p.payload),'hex') + OR w->>'grant_signature_sha256' IS DISTINCT FROM encode(sha256(p.signature),'hex') + OR j.state!='succeeded' OR j.result->>'exit_code' IS DISTINCT FROM '0' + OR j.result->'stdout' IS DISTINCT FROM '[90,101,105,116,112,114,111,102,105,108,45,84,101,115,116,13,10]'::jsonb + OR j.result->'stderr' IS DISTINCT FROM '[]'::jsonb OR j.result->'output_truncated' IS DISTINCT FROM 'false'::jsonb + OR j.result->'reboot_required' IS DISTINCT FROM 'false'::jsonb OR j.result->>'error_code' IS DISTINCT FROM '' + OR j.result#>>'{evidence,execution_sid}' IS DISTINCT FROM 'S-1-5-19' + OR j.result->>'grant_id' IS DISTINCT FROM p.grant_id::text + OR EXISTS(SELECT FROM jobs WHERE tenant_id=s.tenant_id AND agent_id=s.agent_id AND job_id!=s.job_id) + THEN RAISE EXCEPTION 'WINDOWS_ECHO_COMPLETION_MISMATCH'; END IF; + RETURN NEW; +END $$; +CREATE TRIGGER validate_windows_echo_completion BEFORE INSERT ON windows_echo_completions + FOR EACH ROW EXECUTE FUNCTION check_windows_echo_completion(); + +CREATE OR REPLACE FUNCTION restrict_windows_echo_probe_job() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE s windows_echo_probe_scopes%ROWTYPE; +BEGIN + IF NEW.tenant_id='11111111-1111-4111-8111-111111111111' AND + (NEW.agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3' OR NEW.asset_id='a176520e-8a91-4e93-a78b-8e7620f430e0') THEN + SELECT * INTO s FROM windows_echo_probe_scopes WHERE tenant_id=NEW.tenant_id; + IF FOUND AND NOT EXISTS(SELECT FROM windows_echo_completions WHERE tenant_id=NEW.tenant_id) + AND (s.operation_id,s.job_id,s.attempt_id,s.agent_id,s.asset_id,s.job_hash,s.job_bytes) + IS DISTINCT FROM (NEW.operation_id,NEW.job_id,NEW.attempt_id,NEW.agent_id,NEW.asset_id,NEW.payload_hash,NEW.payload) + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + END IF; + RETURN NEW; +END $$; + +CREATE OR REPLACE FUNCTION restrict_windows_echo_delivery() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE s windows_echo_probe_scopes%ROWTYPE; j jobs%ROWTYPE; approval authorizations%ROWTYPE; g jsonb; payload jsonb; +BEGIN + IF NEW.tenant_id!='11111111-1111-4111-8111-111111111111' + OR EXISTS(SELECT FROM windows_echo_completions WHERE tenant_id=NEW.tenant_id) THEN RETURN NEW; END IF; + SELECT * INTO s FROM windows_echo_probe_scopes WHERE tenant_id=NEW.tenant_id; + IF NOT FOUND THEN RETURN NEW; END IF; + SELECT * INTO STRICT j FROM jobs WHERE tenant_id=NEW.tenant_id AND job_id=NEW.job_id AND attempt_id=NEW.attempt_id; + IF j.agent_id!=s.agent_id AND j.asset_id!=s.asset_id THEN RETURN NEW; END IF; + SELECT * INTO STRICT approval FROM authorizations WHERE tenant_id=NEW.tenant_id AND operation_id=s.operation_id; + IF (s.operation_id,s.job_id,s.attempt_id,s.agent_id,s.asset_id,s.job_hash,s.job_bytes) + IS DISTINCT FROM (j.operation_id,j.job_id,j.attempt_id,j.agent_id,j.asset_id,j.payload_hash,j.payload) + OR (approval.plan_hash,approval.plan_id,approval.principal,approval.approval_origin,approval.testsimulation) + IS DISTINCT FROM (s.plan_hash,s.plan_id,'simulated-testprincipal-a'::text,'dev_test_browser_simulation'::text,true) + OR approval.revoked_at IS NOT NULL + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + IF TG_TABLE_NAME='execution_permits' THEN + g=convert_from(NEW.payload,'UTF8')::jsonb; + payload=convert_from(j.payload,'UTF8')::jsonb; + IF (g->>'grant_id',g->>'job_id',g->>'attempt_id',g->>'agent_id',g->>'asset_id',g->>'tenant_id',g->>'plan_hash',g->>'job_payload_hash',g->>'authorization_id') + IS DISTINCT FROM (NEW.grant_id::text,s.job_id::text,s.attempt_id::text,s.agent_id::text,s.asset_id::text,s.tenant_id::text,s.plan_hash,s.job_hash,approval.authorization_id::text) + OR g->>'domain' IS DISTINCT FROM 'rmm.execution-permit' OR g->>'schema_version' IS DISTINCT FROM '1' + OR g->>'action' IS DISTINCT FROM 'run_script' OR g->>'execution_identity' IS DISTINCT FROM 'agent_service' + OR g->>'enrollment_generation' IS DISTINCT FROM '1' OR g->>'assignment_version' IS DISTINCT FROM '1' + OR g->>'max_runtime_seconds' IS DISTINCT FROM '60' OR g->>'not_before' IS NULL OR g->>'start_before' IS NULL + OR (g->>'not_before')::timestamptz < (payload->>'not_before')::timestamptz + OR (g->>'start_before')::timestamptz > (payload->>'start_before')::timestamptz + OR (g->>'start_before')::timestamptz <= (g->>'not_before')::timestamptz + OR (g->>'start_before')::timestamptz > (g->>'not_before')::timestamptz + interval '60 seconds' + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + END IF; + RETURN NEW; +END $$; diff --git a/web/src/agent-updates.test.tsx b/web/src/agent-updates.test.tsx index 8f117d2..f7d9114 100644 --- a/web/src/agent-updates.test.tsx +++ b/web/src/agent-updates.test.tsx @@ -4,11 +4,22 @@ import { renderToStaticMarkup } from 'react-dom/server'; import { PlanInput, record, RecordValue, Session, validateInput } from './api'; import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety'; import { verifyScriptPlan } from './script-console'; -import { agentUpdateApprovalBlockers, agentUpdatePlanJobs, verifyAgentUpdatePlan, uploadAgentUpdateArtifact } from './agent-updates'; +import { agentUpdateApprovalBlockers, agentUpdatePlanJobs, verifyAgentUpdatePlan, uploadAgentUpdateArtifact, validateAgentUpdateAction } from './agent-updates'; vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) })); // Actual rmm-domain serde/codec output; synthetic signatures are NOT update trust. const golden = JSON.parse(readFileSync(new URL('../../tests/agent_update/codec-golden.json', import.meta.url), 'utf8')) as Record; const fixture = (name = 'linux_full') => structuredClone(golden[name]!) as RecordValue; +it('retains the exact optional Windows clock transition before approval and rejects null or changed shape', () => { + const action = record(record(record((record(fixture('windows_pair').payload).jobs as unknown[])[0]).payload).action); + const transition = record(record(action.update).peer_pin_transition); + transition.time_profile = { schema_version: 1, old_time_profile_sha256: '21'.repeat(32), new_time_profile_sha256: '22'.repeat(32), agent_qualification_sha256: '23'.repeat(32), helper_qualification_sha256: '24'.repeat(32) }; + const projected = validateAgentUpdateAction(action, 'system'); + expect(record(record(projected.update).peer_pin_transition).time_profile).toEqual(transition.time_profile); + for (const value of [null, {}, { ...record(transition.time_profile), ready: true }, { ...record(transition.time_profile), schema_version: 2 }, { ...record(transition.time_profile), new_time_profile_sha256: '21'.repeat(32) }]) { + const changed = structuredClone(action); record(record(changed.update).peer_pin_transition).time_profile = value; + expect(() => validateAgentUpdateAction(changed, 'system')).toThrow(); + } +}); async function rehashed(change: (raw: RecordValue) => void): Promise { const p = fixture(), raw = record(p.payload); change(raw); const bytes = new TextEncoder().encode(JSON.stringify(raw)); p.plan_payload_bytes = Array.from(bytes); p.plan_hash = await sha256(bytes); diff --git a/web/src/agent-updates.ts b/web/src/agent-updates.ts index a3798a9..0bbec9e 100644 --- a/web/src/agent-updates.ts +++ b/web/src/agent-updates.ts @@ -72,9 +72,16 @@ export function validateAgentUpdateAction(value: unknown, identity: unknown): Re if (full.old_helper_sha256 !== predecessor.helper_sha256 || full.new_helper_sha256 !== record((release.manifest.artifacts as unknown[])[1]).sha256 || full.old_config_sha256 === full.new_config_sha256 || full.old_pin_sha256 === full.new_pin_sha256) throw new Error('Agentupdate: Fullpin-Codepaarbindung fehlt'); transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256), full }; } else if (p.profile === 'windows_code_pair_v1') { - exact(p, ['profile', 'old_settings_sha256', 'new_settings_sha256', 'old_pin_sha256', 'new_pin_sha256']); if (linux) throw new Error('Agentupdate: Windows-Pinprofil auf Linux'); + const hasTime = Object.prototype.hasOwnProperty.call(p, 'time_profile'); + exact(p, ['profile', 'old_settings_sha256', 'new_settings_sha256', 'old_pin_sha256', 'new_pin_sha256', ...(hasTime ? ['time_profile'] : [])]); if (linux) throw new Error('Agentupdate: Windows-Pinprofil auf Linux'); transition = { profile: p.profile, old_settings_sha256: digest(p.old_settings_sha256), new_settings_sha256: digest(p.new_settings_sha256), old_pin_sha256: digest(p.old_pin_sha256), new_pin_sha256: digest(p.new_pin_sha256) }; if (transition.old_settings_sha256 === transition.new_settings_sha256 || transition.old_pin_sha256 === transition.new_pin_sha256) throw new Error('Agentupdate: unveränderte Windows-Pinübergabe'); + if (hasTime) { + const t = record(p.time_profile); exact(t, ['schema_version', 'old_time_profile_sha256', 'new_time_profile_sha256', 'agent_qualification_sha256', 'helper_qualification_sha256']); + if (t.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Windows-Zeitprofilschema'); + transition.time_profile = { schema_version: 1, old_time_profile_sha256: digest(t.old_time_profile_sha256), new_time_profile_sha256: digest(t.new_time_profile_sha256), agent_qualification_sha256: digest(t.agent_qualification_sha256), helper_qualification_sha256: digest(t.helper_qualification_sha256) }; + if (t.old_time_profile_sha256 === t.new_time_profile_sha256) throw new Error('Agentupdate: unverändertes Windows-Zeitprofil'); + } } else throw new Error('Agentupdate: unbekannter Peerpinübergang'); return { action: 'update_agent', update: { schema_version: 1, profile: 'fixed_code_pair_v1', release_envelope: release.envelope, release_envelope_sha256: digest(u.release_envelope_sha256), manifest_sha256: digest(u.manifest_sha256), predecessor, updater, peer_pin_transition: transition, recovery: 'restore_exact_predecessor_once', health_profile: 'mtls_inventory_sync_v1', health_timeout_seconds: 180, no_reboot: true } }; } diff --git a/web/src/echo-completion-review.test.ts b/web/src/echo-completion-review.test.ts new file mode 100644 index 0000000..1311129 --- /dev/null +++ b/web/src/echo-completion-review.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from 'vitest'; +import { canonicalJson } from './api'; +import { sha256 } from './safety'; +import { completionReview } from './echo-completion-review'; + +it('prüft Abschlussbindung und verweigert Bereitschaft oder eine als echt behauptete Freigabe', async () => { + const witness = { scope: { tenant_id: '11111111-1111-4111-8111-111111111111', asset_id: 'a176520e-8a91-4e93-a78b-8e7620f430e0', + agent_id: '63ea15b2-0643-403d-b5b4-cba1288dbea3', execution_identity: 'agent_service', + script_sha256: await sha256(new TextEncoder().encode("Write-Output 'Zeitprofil-Test'\r\n")) }, + probe_receipt_sha256: '1'.repeat(64), probe_signature_sha256: '2'.repeat(64), grant_payload_sha256: '3'.repeat(64), + grant_signature_sha256: '4'.repeat(64), outcome_sha256: '5'.repeat(64) }; + const digest = await sha256(new TextEncoder().encode(canonicalJson(witness))); + const receipt = { domain: 'rmm.dev.windows-echo-completion.v1', schema_version: 1, witness, witness_sha256: digest, + confirmed_by: 'simulated-testprincipal-a', approval_origin: 'dev_test_browser_simulation', testsimulation: true, + ready: false, helper_ready: false, unlock: false }; + expect((await completionReview({ witness, witness_sha256: digest, receipt })).witness_sha256).toBe(digest); + for (const changed of [{ ...receipt, ready: true }, { ...receipt, helper_ready: true }, { ...receipt, unlock: true }, + { ...receipt, testsimulation: false }, { ...receipt, confirmed_by: 'Administrator' }, + { ...receipt, witness: { ...witness, grant_payload_sha256: '0'.repeat(64) } }]) { + await expect(completionReview({ witness, witness_sha256: digest, receipt: changed })).rejects.toThrow(); + } +}); diff --git a/web/src/echo-completion-review.tsx b/web/src/echo-completion-review.tsx new file mode 100644 index 0000000..e7202f8 --- /dev/null +++ b/web/src/echo-completion-review.tsx @@ -0,0 +1,61 @@ +import React, { useState } from 'react'; +import { canonicalJson, pretty, record, RecordValue, request, Session, tenantPath } from './api'; +import { allowed, sha256 } from './safety'; + +const tenant = '11111111-1111-4111-8111-111111111111'; +const asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'; +const agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'; +interface Review { witness: RecordValue; witness_sha256: string; receipt: RecordValue | null } +export async function completionReview(value: unknown): Promise { + const r = record(value), w = record(r.witness), s = record(w.scope); + if (s.tenant_id !== tenant || s.asset_id !== asset || s.agent_id !== agent || s.execution_identity !== 'agent_service' || + s.script_sha256 !== await sha256(new TextEncoder().encode("Write-Output 'Zeitprofil-Test'\r\n")) || + typeof r.witness_sha256 !== 'string' || await sha256(new TextEncoder().encode(canonicalJson(w))) !== r.witness_sha256 || + !['probe_receipt_sha256', 'probe_signature_sha256', 'grant_payload_sha256', 'grant_signature_sha256', 'outcome_sha256'].every(k => typeof w[k] === 'string' && /^[a-f0-9]{64}$/.test(w[k] as string)) || + !(r.receipt === null || (typeof r.receipt === 'object' && !Array.isArray(r.receipt)))) { + throw new Error('Der Abschlussbeleg ist ungültig.'); + } + if (r.receipt !== null) { + const receipt = record(r.receipt); + if (receipt.domain !== 'rmm.dev.windows-echo-completion.v1' || receipt.schema_version !== 1 || receipt.testsimulation !== true || + receipt.approval_origin !== 'dev_test_browser_simulation' || receipt.confirmed_by !== 'simulated-testprincipal-a' || + receipt.ready !== false || receipt.helper_ready !== false || receipt.unlock !== false || + receipt.witness_sha256 !== r.witness_sha256 || canonicalJson(receipt.witness) !== canonicalJson(w)) { + throw new Error('Die Quittung passt nicht zum geprüften Abschluss.'); + } + } + return r as unknown as Review; +} +export function EchoCompletionReview({ auth }: { auth: Session }) { + const [review, setReview] = useState(null), [checked, setChecked] = useState(false); + const [busy, setBusy] = useState(false), [error, setError] = useState(''); + const eligible = auth.principal.simulated && auth.principal.id === 'simulated-testprincipal-a' && !!auth.csrf_token && allowed(auth, 'plans:approve'); + const path = tenantPath(tenant, '/windows-echo-completion'); + async function load() { + setBusy(true); setError(''); setChecked(false); setReview(null); + try { setReview(await completionReview(await request(path))); } + catch (e) { setError(String(e)); } finally { setBusy(false); } + } + async function confirm() { + if (!eligible || !checked || !review || busy) return; + setBusy(true); setError(''); setChecked(false); + try { setReview(await completionReview(await request(path + '/confirm', { csrf: auth.csrf_token, + body: { reviewed: true, witness_sha256: review.witness_sha256 } }))); } + catch (e) { setReview(null); setError(String(e)); } finally { setBusy(false); } + } + return
+

Abschluss des festen PowerShell-Testbetriebs

+

Nach dem nachgewiesenen einzelnen Test kann die zusätzliche Beschränkung auf diesen Auftrag beendet werden. Identität, alte Begrenzung, Quittungen und Journale bleiben erhalten. Jeder weitere Auftrag braucht weiterhin einen eigenen unveränderlichen Plan und seine WebUI-Genehmigung; dieser Schritt erteilt keine Jobfreigabe oder Ausführungsbereitschaft.

+ + {error &&

{error}

} + {review && <> +
{pretty(review)}
+ {!review.receipt && eligible && <> + + + } + {review.receipt && eligible && Signierte Abschlussquittung herunterladen} + } +
; +} diff --git a/web/src/main.tsx b/web/src/main.tsx index 93c7cff..2bf83fd 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -7,6 +7,7 @@ import { AdminControl, Catalog, TenantControls } from './management'; import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety'; import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review'; import { EchoProbeReview } from './echo-probe-review'; +import { EchoCompletionReview } from './echo-completion-review'; import { Login } from './login'; import { ConsoleOutput, outputText } from './console-output'; import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console'; @@ -102,7 +103,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string;

Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}

{asset &&

Inventardetail {asset}

{detail.data && <>}
} {tenantId === recoveryTenant && asset === recoveryAsset && allowed(auth, 'inventory:read') && - <>} + <>} ; } const initialParameters: Record = {