diff --git a/crates/agent-windows/src/bin/rmm-helper-windows.rs b/crates/agent-windows/src/bin/rmm-helper-windows.rs index 5635313..0be7955 100644 --- a/crates/agent-windows/src/bin/rmm-helper-windows.rs +++ b/crates/agent-windows/src/bin/rmm-helper-windows.rs @@ -1,6 +1,13 @@ //! Separate SCM binary. The network agent always remains LocalService. #[cfg(windows)] fn main() -> anyhow::Result<()> { + if std::env::args().skip(1).eq(["--prepare-enrolled-windows-update"]) { + return rmm_agent_windows::windows_update_setup::render(); + } + if std::env::args().skip(1).eq(["--windows-update-scope-version"]) { + println!("enrolled-windows-update/1"); + return Ok(()); + } rmm_agent_windows::helper_system::dispatch() } #[cfg(not(windows))] diff --git a/crates/agent-windows/src/helper_ipc.rs b/crates/agent-windows/src/helper_ipc.rs index db21a97..f7b5c02 100644 --- a/crates/agent-windows/src/helper_ipc.rs +++ b/crates/agent-windows/src/helper_ipc.rs @@ -243,15 +243,16 @@ impl PeerPin { self.service_sid == service_sid(name)? && digest(&self.binary_sha256), "HELPER_PEER_PIN" ); - ensure!( - self.binary - == Path::new(if helper { - r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe" - } else { - r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" - }), - "HELPER_FIXED_IMAGE" - ); + // The byte pin and SCM command still have to match the running image. + let root = Path::new(r"C:\Program Files\RustDiscovery"); + let name = if helper { "rmm-helper-windows.exe" } else { "rmm-agent-windows.exe" }; + let published = self.binary.parent().and_then(|dir| { + let id = dir.file_name()?.to_str()?; + let release = Uuid::parse_str(id).ok()?; + Some(!release.is_nil() && id == release.to_string() + && self.binary == root.join("releases").join(id).join(name)) + }).unwrap_or(false); + ensure!(self.binary == root.join(name) || published, "HELPER_FIXED_IMAGE"); Ok(()) } fn command(&self) -> String { diff --git a/crates/agent-windows/src/helper_system.rs b/crates/agent-windows/src/helper_system.rs index 6371f19..cc1eb9c 100644 --- a/crates/agent-windows/src/helper_system.rs +++ b/crates/agent-windows/src/helper_system.rs @@ -106,6 +106,11 @@ impl Settings { .is_some_and(|h| h.contains(&m.recipe_sha256)) }) } + pub(crate) fn windows_update_only(&self) -> bool { + self.schema_version >= 3 && self.enable_effects && self.windows_update_max_runtime_seconds.is_some() + && self.allowed_script_profiles.is_none() && self.allowed_services.is_empty() + && self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30 + } fn permits_script(&self, job: &JobPayload) -> bool { self.schema_version >= 3 && job.execution_identity == "system" @@ -118,7 +123,7 @@ impl Settings { && job.max_runtime_seconds <= job.action.windows_system_runtime_limit(self.max_runtime_seconds, self.windows_update_max_runtime_seconds) && (self.allowed_script_profiles.as_deref() == Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]) - || (self.windows_update_max_runtime_seconds.is_some() && job.action.is_windows_update_template())) + || (self.windows_update_max_runtime_seconds.is_some() && job.action.windows_update_or_identity_probe())) } fn permits_reboot(&self, job: &JobPayload) -> bool { self.schema_version == 4 @@ -886,7 +891,9 @@ impl SystemHelper { let pin = settings.pin()?; ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?; let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?; - let clock = RuntimeClock::new(rmm_time_attestation::Role::SystemHelper).for_generation(0); + let clock = if settings.windows_update_only() { + RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone()) + } else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0); let boot = WindowsBoot::capture()?; let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock) .ok() diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs index 3b8fc37..064fa40 100644 --- a/crates/agent-windows/src/lib.rs +++ b/crates/agent-windows/src/lib.rs @@ -20,6 +20,8 @@ pub mod helper_ipc; pub mod helper_runtime; #[cfg(all(windows, feature = "system-helper"))] pub mod helper_system; +#[cfg(all(windows, feature = "system-helper"))] +pub mod windows_update_setup; #[cfg(windows)] pub mod inventory; #[cfg(windows)] diff --git a/crates/agent-windows/src/release_service.rs b/crates/agent-windows/src/release_service.rs index 1025d29..fd11d1e 100644 --- a/crates/agent-windows/src/release_service.rs +++ b/crates/agent-windows/src/release_service.rs @@ -95,8 +95,55 @@ fn protected(path: &Path, limit: usize) -> Result> { ); Ok(fs::read(path)?) } +// The active agent pins its trust/configuration directory. Windows permits +// creating a child there, but rejects a rename into this pinned directory. +// Keep all transactional records in their own administrator-controlled child. +fn journal_dir() -> PathBuf { + data("release-state") +} +fn record_path(name: &str) -> PathBuf { + journal_dir().join(name) +} +fn prepare_journal() -> Result<()> { + job_binding::check_admin_readonly(&data("config.json"))?; + let dir = journal_dir(); + if !dir.try_exists()? { + fs::create_dir(&dir)?; + } + native::private_path(&dir, true)?; + // Copy original protected bytes once, preserving any interrupted transition. + // Record selection thereafter uses only the new directory. + for name in [ + ACTIVE, + INTENT, + "rejected-release.json", + "release-status.json", + ] { + let previous = data(name); + let current = record_path(name); + if !current.try_exists()? && previous.try_exists()? { + let bytes = protected(&previous, 8192)?; + let temporary = dir.join(format!(".migrate-{}", Uuid::new_v4())); + write_new(&temporary, &bytes)?; + let moved = fs::rename(&temporary, current); + if moved.is_err() { + let _ = fs::remove_file(&temporary); + } + moved?; + } + // ACTIVE doubles as the immutable baseline for older installers. An + // old intent must never be resurrected once its recovery is complete. + if name != ACTIVE && previous.try_exists()? && record_path(name).try_exists()? { + fs::remove_file(previous)?; + } + } + Ok(()) +} fn read_record(name: &str) -> Result { - Ok(serde_json::from_slice(&protected(&data(name), 8192)?)?) + Ok(serde_json::from_slice(&protected( + &record_path(name), + 8192, + )?)?) } fn write_new(path: &Path, bytes: &[u8]) -> Result<()> { let mut file = fs::File::create_new(path)?; @@ -108,11 +155,11 @@ fn write_record(name: &str, value: &T) -> Result<()> { use windows_sys::Win32::Storage::FileSystem::{ MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, }; - let tmp = data(&format!(".release-{}", Uuid::new_v4())); + let tmp = record_path(&format!(".release-{}", Uuid::new_v4())); let wide = |p: &OsStr| p.encode_wide().chain(Some(0)).collect::>(); let result = (|| -> Result<()> { write_new(&tmp, &serde_json::to_vec(value)?)?; - let (from, to) = (wide(tmp.as_os_str()), wide(data(name).as_os_str())); + let (from, to) = (wide(tmp.as_os_str()), wide(record_path(name).as_os_str())); if unsafe { MoveFileExW( from.as_ptr(), @@ -294,7 +341,7 @@ async fn rollback(t: &Transition) -> Result<()> { local_manifest(&t.old)?; select(t.new.release_id, t.old.release_id)?; write_record("rejected-release.json", &t.new)?; - fs::remove_file(data(INTENT))?; + fs::remove_file(record_path(INTENT))?; Ok(()) } @@ -371,7 +418,7 @@ async fn cycle() -> Result<()> { || config.localservice_time_policy.as_ref() == Some(&data("job-time.json")), "job-enabled pair requires coordinated helper handoff" ); - if data(INTENT).try_exists()? { + if record_path(INTENT).try_exists()? { let _job_gate = if config.enable_jobs { let Some(file) = exclusive_job_gate()? else { return Ok(()); @@ -383,7 +430,7 @@ async fn cycle() -> Result<()> { let t: Transition = read_record(INTENT)?; if active.release_id == t.new.release_id { - fs::remove_file(data(INTENT))?; + fs::remove_file(record_path(INTENT))?; } else { ensure!( active.release_id == t.old.release_id, @@ -422,7 +469,7 @@ async fn cycle() -> Result<()> { ); return Ok(()); } - if data("rejected-release.json").try_exists()? { + if record_path("rejected-release.json").try_exists()? { let rejected: Installed = read_record("rejected-release.json")?; ensure!( candidate.release_sequence > rejected.release_sequence, @@ -456,7 +503,7 @@ async fn cycle() -> Result<()> { && h.last_contact_at.is_some_and(|v| v >= start) { write_record(ACTIVE, &t.new)?; - fs::remove_file(data(INTENT))?; + fs::remove_file(record_path(INTENT))?; return Ok(()); } tokio::time::sleep(Duration::from_secs(5)).await; @@ -472,13 +519,21 @@ pub fn dispatch() -> Result<()> { fn run(stop: &'static AtomicBool) -> Result<()> { let runtime = tokio::runtime::Runtime::new()?; while !stop.load(Ordering::SeqCst) { - let result = runtime.block_on(cycle()); - write_record( + let result = prepare_journal().and_then(|()| runtime.block_on(cycle())); + let succeeded = result.is_ok(); + let status_saved = write_record( "release-status.json", &serde_json::json!({"observed_at": chrono::Utc::now(), "status": if result.is_ok() { "ok" } else { "error" }, "detail": result.err().map(|e| e.to_string())}), - )?; - for _ in 0..300 { + ); + // A temporary file lock during status publication must not terminate + // the SCM service. A bounded retry also covers enrollment startup. + let retry_seconds = if succeeded && status_saved.is_ok() { + 300 + } else { + 15 + }; + for _ in 0..retry_seconds { if stop.load(Ordering::SeqCst) { break; } diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index dd97444..2ee5ead 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -38,6 +38,8 @@ struct Config { job_binding_file: Option, #[serde(default)] localservice_time_policy: Option, + #[serde(default)] + windows_update_helper: bool, // Explicit protected opt-in only; this flag never qualifies a clock or pins. #[serde(default)] enable_jobs: bool, @@ -97,6 +99,9 @@ impl Config { fn read(path: &Path) -> Result { let raw = protected_read(path, 32768)?; let config: Self = serde_json::from_slice(&raw)?; + if config.windows_update_helper { + ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED"); + } if let Some(policy) = &config.localservice_time_policy { let parent = path.parent().context("CONFIG_PARENT")?; ensure!(policy == &parent.join("job-time.json") @@ -812,7 +817,7 @@ impl Agent { &identity.certificate_pem, &identity.private_key_pem, )?; - let helper = if self.config.localservice_time_policy.is_some() { + let helper = if self.config.localservice_time_policy.is_some() && !self.config.windows_update_helper { None } else { rmm_agent_windows::helper_runtime::Client::discover( &self.identity.agent_id, @@ -1400,7 +1405,8 @@ impl Agent { Ok(()) } fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool { - if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service" { + if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service" + && !(self.config.windows_update_helper && job.execution_identity == "system" && job.action.windows_update_or_identity_probe()) { return false; } if self.config.windows_echo_probe_only diff --git a/crates/agent-windows/src/signed_clock.rs b/crates/agent-windows/src/signed_clock.rs index 8d99992..ac50cd6 100644 --- a/crates/agent-windows/src/signed_clock.rs +++ b/crates/agent-windows/src/signed_clock.rs @@ -957,16 +957,24 @@ mod installed { failure_fence.armed = false; Ok(value) } - /// An enrolled LocalService never supplies time evidence for a helper. - /// Its public broker pins and job binding are installed by the HTTPS - /// bootstrap; every usable reading still needs a current signed challenge. + /// Each enrolled process obtains its own signed challenge. The SYSTEM + /// helper additionally authenticates its exact running SCM peer/image. async fn open_local_service( generation: u64, binding: &rmm_agent_core::auth::Binding, policy_file: &Path, + helper: Option<&ipc::PeerPin>, ) -> Result { let mut failure_fence = ConstructorFailureFence { armed: true }; - crate::native::require_local_service()?; + let (owner, role) = if let Some(pin) = helper { + pin.validate(true)?; + ipc::require_self(pin)?; + let proof = PeerProof::for_service(pin, unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessId() })?; + (ClockOwner::Service(Box::new(proof)), Role::SystemHelper) + } else { + crate::native::require_local_service()?; + (ClockOwner::EnrolledLocalService, Role::Agent) + }; let readers = [crate::native::service_sid()?]; let parent = PinnedFile::open( policy_file.parent().context("TIME_POLICY_PARENT")?, @@ -1009,15 +1017,15 @@ mod installed { connection_generation: generation, windows_boot_id: boot_id, verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4), - role: Role::Agent, + role, binding_schema: 1, - helper_image_sha256: None, + helper_image_sha256: helper.map(|pin| pin.binary_sha256.clone()), updater_image_sha256: None, }; let hash = hash(&raw); let mut clock = Self { verifier: Verifier::new(context, pins)?, - owner: ClockOwner::EnrolledLocalService, + owner, files: vec![parent, config_file], config_sha256: hash.clone(), boot_id, @@ -1385,6 +1393,7 @@ mod installed { #[derive(Clone)] pub struct RuntimeClock { role: Role, + enrolled_helper: Option, local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>, state: Arc>>, } @@ -1397,6 +1406,7 @@ mod installed { pub fn new(role: Role) -> Self { Self { role, + enrolled_helper: None, local_policy: None, state: Arc::new(Mutex::new(None)), } @@ -1409,6 +1419,12 @@ mod installed { value.local_policy = Some((binding, policy)); value } + pub fn enrolled_windows_update_helper(binding: rmm_agent_core::auth::Binding, helper: ipc::PeerPin) -> Self { + let mut value = Self::new(Role::SystemHelper); + value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json"))); + value.enrolled_helper = Some(helper); + value + } pub fn for_generation(&self, generation: u64) -> BoundClock { BoundClock { source: self.clone(), @@ -1425,7 +1441,7 @@ mod installed { self.close()?; let clock = match &self.local_policy { Some((binding, policy)) => { - SignedClock::open_local_service(generation, binding, policy).await? + SignedClock::open_local_service(generation, binding, policy, self.enrolled_helper.as_ref()).await? } None => SignedClock::open(self.role, generation).await?, }; diff --git a/crates/agent-windows/src/system_capabilities.rs b/crates/agent-windows/src/system_capabilities.rs index a73f4bc..4baea1b 100644 --- a/crates/agent-windows/src/system_capabilities.rs +++ b/crates/agent-windows/src/system_capabilities.rs @@ -40,6 +40,15 @@ pub fn qualified( return Ok(vec![]); } pin.validate()?; + let (settings, _handles) = helper_system::read_settings()?; + ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin"); + if settings.windows_update_only() { + // The caller has verified an independent helper-role clock and the live + // peer. Only the two built-in scripts pass both local and server gates. + return Ok(vec!["helper.system.v1".into(), format!("helper.binary.sha256:{}",pin.helper.binary_sha256), + format!("helper.policy.sha256:{}",pin.policy_sha256), "system:run_script".into(), + rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()]); + } let ordinary = load_ordinary(pin); let (q, result_bytes) = match ordinary { Ok(sources) => sources, @@ -66,7 +75,6 @@ pub fn qualified( && 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, diff --git a/crates/agent-windows/src/windows_update_setup.rs b/crates/agent-windows/src/windows_update_setup.rs new file mode 100644 index 0000000..7ebd792 --- /dev/null +++ b/crates/agent-windows/src/windows_update_setup.rs @@ -0,0 +1,79 @@ +//! Render the two public configuration files for the narrowly scoped, enrolled +//! development helper. The operator installs them after reviewing the live pair. +use crate::{ + helper_ipc::{self as ipc, PeerPin}, + helper_system::Settings, +}; +use anyhow::{Result, ensure}; +use serde::Deserialize; +use std::{ + io::{Read, Write}, + path::PathBuf, +}; +use uuid::Uuid; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Input { + binding: rmm_agent_core::auth::Binding, + release_id: Uuid, + agent_sha256: String, + helper_sha256: String, + max_runtime_seconds: u32, +} + +pub fn render() -> Result<()> { + let mut raw = Vec::new(); + std::io::stdin().take(8193).read_to_end(&mut raw)?; + ensure!(raw.len() <= 8192, "UPDATE_SCOPE_INPUT_SIZE"); + let data: Input = serde_json::from_slice(&raw)?; + ensure!( + !data.release_id.is_nil() && (121..=3600).contains(&data.max_runtime_seconds), + "UPDATE_SCOPE_BOUNDS" + ); + let dir = + PathBuf::from(r"C:\Program Files\RustDiscovery\releases").join(data.release_id.to_string()); + let role = |name: &str, user: &str, exe: &str, digest: String| -> Result { + let file = dir.join(exe); + ensure!( + rmm_domain::jobs::hash(&std::fs::read(&file)?) == digest, + "UPDATE_SCOPE_IMAGE_MISMATCH" + ); + Ok(PeerPin { + service_name: name.into(), + service_sid: ipc::service_sid(name)?, + user_sid: user.into(), + binary: file, + binary_sha256: digest, + }) + }; + let settings = Settings { + schema_version: 3, + binding: data.binding, + agent: role( + crate::SERVICE_NAME, + "S-1-5-19", + "rmm-agent-windows.exe", + data.agent_sha256, + )?, + helper: role( + ipc::HELPER_SERVICE, + "S-1-5-18", + "rmm-helper-windows.exe", + data.helper_sha256, + )?, + allowed_services: vec![], + max_runtime_seconds: 30, + enable_effects: true, + allow_reboot: false, + allowed_msi_recipe_sha256: None, + allowed_script_profiles: None, + windows_update_max_runtime_seconds: Some(data.max_runtime_seconds), + }; + settings.validate()?; + let pin = settings.pin()?; + let result = serde_json::json!({"helper_settings":serde_json::to_string(&settings)?, + "agent_pin":serde_json::to_string(&pin)?,"helper_policy_sha256":pin.policy_sha256}); + std::io::stdout().write_all(&serde_json::to_vec(&result)?)?; + Ok(()) +}