//! Explicit G205 bootstrap operator. No service stop/start, job, enrollment, //! configuration rewrite, clock bootstrap or normal HelperSync::apply. #[cfg(all(windows, feature = "system-helper"))] mod platform { use anyhow::{Context, Result, ensure}; use fs2::FileExt; use rmm_agent_core::{ auth::Binding, windows_system_nonstart::{self as recovery, ClosedPairGuard, Local}, }; use rmm_agent_windows::{ SERVICE_NAME, helper_ipc::{self as ipc, PinnedFile}, helper_runtime::intent, helper_system, native, }; use rmm_domain::{ jobs::hash, windows_system_nonstart::{BOOT, FILE_ROLES, NativeFile, NonstartProof}, }; use rusqlite::{Connection, OpenFlags}; use std::{ cell::RefCell, fs::{File, OpenOptions}, io::{Read, Seek, SeekFrom}, os::windows::{fs::OpenOptionsExt, io::AsRawHandle}, path::{Path, PathBuf}, }; use uuid::Uuid; use windows_sys::Win32::{Security::*, Storage::FileSystem::*, System::Services::*}; static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); fn phase(value: usize) { PHASE.store(value, std::sync::atomic::Ordering::Relaxed); } pub fn diagnostic(error: &anyhow::Error) -> serde_json::Value { let phases = [ "arguments", "admin_and_stopped", "public_binding", "helper_settings", "lifetime_locks", "intent_acl", "held_file_ids", "boot_measurement", "intent_empty_snapshot", "journal_open", "original_identity_rows", "witness_or_apply", ]; let codes = error .chain() .filter_map(|cause| { let text = cause.to_string(); (text.len() <= 96 && !text.is_empty() && text .bytes() .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')) .then_some(text) }) .take(8) .collect::>(); let mut data = serde_json::json!({"schema_version":1,"diagnostic_only":true,"phase":phases.get(PHASE.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(&"unknown"),"codes":codes}); for cause in error.chain() { if let Some(sql) = cause.downcast_ref::() { data["sqlite"] = match sql { rusqlite::Error::SqliteFailure(code, _) => { serde_json::json!({"code":"SQLITE_FAILURE","sqlite_code":format!("{:?}",code.code),"extended_code":code.extended_code}) } rusqlite::Error::QueryReturnedNoRows => { serde_json::json!({"code":"SQLITE_NO_ROWS"}) } rusqlite::Error::InvalidColumnType(index, name, _) => { serde_json::json!({"code":"SQLITE_COLUMN_TYPE","index":index,"column":if name.len()<=48&&name.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_'){name.as_str()}else{"redacted"}}) } _ => serde_json::json!({"code":"SQLITE_READ_FAILED"}), }; break; } if let Some(codec) = cause.downcast_ref::() { data["codec"] = serde_json::json!({"code":"JSON_CODEC","line":codec.line(),"column":codec.column()}); } if let Some(io) = cause.downcast_ref::() { data["io"] = serde_json::json!({"kind":format!("{:?}",io.kind()),"os_code":io.raw_os_error()}); } } data } const ROOT: &str = r"C:\ProgramData\RustDiscovery"; const STATE: &str = r"C:\ProgramData\RustDiscovery\state"; const PATHS: [&str; 6] = [ r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite", r"C:\ProgramData\RustDiscovery\state\consumption.sqlite", r"C:\ProgramData\RustDiscovery\state\agent.lock", r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite", r"C:\ProgramData\RustDiscoverySystem\state\executor.lock", intent::DB, ]; struct Sc(SC_HANDLE); impl Drop for Sc { fn drop(&mut self) { unsafe { CloseServiceHandle(self.0) }; } } fn stopped(name: &str) -> Result<()> { let manager = Sc(unsafe { OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT) }); ensure!(!manager.0.is_null(), "ALIGN_SCM_MANAGER"); let wide = name.encode_utf16().chain(Some(0)).collect::>(); let service = Sc(unsafe { OpenServiceW(manager.0, wide.as_ptr(), SERVICE_QUERY_STATUS) }); ensure!(!service.0.is_null(), "ALIGN_SCM_SERVICE"); let mut status: SERVICE_STATUS_PROCESS = unsafe { std::mem::zeroed() }; let mut size = 0; ensure!( unsafe { QueryServiceStatusEx( service.0, SC_STATUS_PROCESS_INFO, (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), std::mem::size_of::() as u32, &mut size, ) } != 0 && status.dwCurrentState == SERVICE_STOPPED, "ALIGN_BOTH_SERVICES_MUST_BE_STOPPED" ); Ok(()) } fn both() -> Result<()> { stopped(SERVICE_NAME)?; stopped(ipc::HELPER_SERVICE) } fn admin() -> Result<()> { let mut sid = [0usize; 16]; let mut len = std::mem::size_of_val(&sid) as u32; let mut member = 0; ensure!( unsafe { CreateWellKnownSid( WinBuiltinAdministratorsSid, std::ptr::null_mut(), sid.as_mut_ptr().cast(), &mut len, ) } != 0 && unsafe { CheckTokenMembership(std::ptr::null_mut(), sid.as_mut_ptr().cast(), &mut member) } != 0 && member != 0, "ALIGN_ADMINISTRATOR_REQUIRED" ); Ok(()) } fn leaf(path: &Path) -> Result { for parent in path.ancestors() { ensure!( std::os::windows::fs::MetadataExt::file_attributes(&parent.symlink_metadata()?) & FILE_ATTRIBUTE_REPARSE_POINT == 0, "ALIGN_NO_REPARSE" ); } let file = OpenOptions::new() .read(true) .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) .open(path)?; native_id(&file)?; Ok(file) } fn native_id(file: &File) -> Result<[u32; 3]> { let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; ensure!( unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0 && i.nNumberOfLinks == 1 && i.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) == 0, "ALIGN_FILE_ID" ); Ok([i.dwVolumeSerialNumber, i.nFileIndexHigh, i.nFileIndexLow]) } fn bytes(mut file: &File, max: u64) -> Result> { ensure!(file.metadata()?.len() <= max, "ALIGN_FILE_LIMIT"); file.seek(SeekFrom::Start(0))?; let mut data = vec![]; file.take(max + 1).read_to_end(&mut data)?; ensure!(data.len() as u64 <= max, "ALIGN_FILE_CHANGED"); Ok(data) } struct Held { path: PathBuf, file: File, id: ipc::FileIdentity, legacy: [u32; 3], } struct Guard { held: Vec, _locks: Vec, _settings: RefCell>, _public: RefCell>, boot: Uuid, intents: RefCell, } impl ClosedPairGuard for Guard { fn check(&self) -> Result<()> { both()?; self.intents.borrow_mut().check()?; for file in self ._settings .borrow_mut() .iter_mut() .chain(self._public.borrow_mut().iter_mut()) { file.check()?; } ensure!( ipc::file_identity(&self._locks[0])? == self.held[2].id && ipc::file_identity(&self._locks[1])? == self.held[4].id, "ALIGN_ORIGINAL_LOCK_OWNER_HANDLES" ); for h in &self.held { ensure!( ipc::file_identity(&h.file)? == h.id && native_id(&h.file)? == h.legacy && ipc::file_identity(&leaf(&h.path)?)? == h.id, "ALIGN_ORIGINAL_FILE_REPLACED" ); } Ok(()) } fn files(&self) -> Result<[NativeFile; 6]> { self.check()?; let mut out = vec![]; for (index, (h, role)) in self.held.iter().zip(FILE_ROLES).enumerate() { // Read a lifetime lock ONLY through the original HANDLE that // owns its LockFileEx range; a second handle is correctly denied. let f = match index { 2 => &self._locks[0], 4 => &self._locks[1], _ => &h.file, }; out.push(NativeFile { role: role.into(), file_id: Some(h.legacy), sha256: Some(hash(&bytes(f, 256 * 1024 * 1024).context(match index { 0 => "ALIGN_HASH_TELEMETRY", 1 => "ALIGN_HASH_CONSUMPTION", 2 => "ALIGN_HASH_AGENT_LOCK", 3 => "ALIGN_HASH_HELPER_LEDGER", 4 => "ALIGN_HASH_HELPER_LOCK", _ => "ALIGN_HASH_SYSTEM_INTENTS", })?)), }); } out.try_into() .map_err(|_| anyhow::anyhow!("ALIGN_FILE_COUNT")) } fn boot(&self) -> Result { Ok(self.boot) } } struct Db { db: Connection, _held: Vec, } impl Db { fn open(path: &str, write: bool) -> Result { let mut file = leaf(Path::new(path))?; let mut header = [0; 20]; file.read_exact(&mut header)?; ensure!( header.starts_with(b"SQLite format 3\0") && header[18] == header[19] && matches!(header[18], 1 | 2), "ALIGN_SQLITE_HEADER" ); let mut held = vec![file]; let mut wal = false; let mut shm = false; let mut journal = false; for (suffix, present) in [ ("-wal", &mut wal), ("-shm", &mut shm), ("-journal", &mut journal), ] { let p = format!("{path}{suffix}"); if Path::new(&p).try_exists()? { held.push(leaf(Path::new(&p))?); *present = true; } } let flags = if write { OpenFlags::SQLITE_OPEN_READ_WRITE } else { OpenFlags::SQLITE_OPEN_READ_ONLY }; let db = if !write && header[18] == 2 && !(wal && shm) { ensure!(!wal && !shm && !journal, "ALIGN_ORIGINAL_WAL_INCOMPLETE"); Connection::open_with_flags( format!("file:///{}?mode=ro&immutable=1", path.replace('\\', "/")), flags | OpenFlags::SQLITE_OPEN_URI, )? } else { Connection::open_with_flags(path, flags)? }; db.busy_timeout(std::time::Duration::from_millis(500))?; Ok(Self { db, _held: held }) } } pub fn run() -> Result<()> { let args = std::env::args().skip(1).collect::>(); if args == ["--receipt-contract"] { let file = PinnedFile::open( Path::new( r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-receipt.json", ), false, &[], &[], false, )?; let event=PinnedFile::open(Path::new(r"C:\ProgramData\RustDiscoveryBootstrap\6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9\placeholder-envelope.pb"),false,&[],&[],false)?; println!("{}",serde_json::to_string(&recovery::receipt_contract(&bytes(&file.file,4*1024*1024)?,&bytes(&event.file,16384)?)?)?); return Ok(()); } let apply = args == ["--apply"]; let verify = args == ["--verify-applied"]; ensure!( apply || verify || args == ["--witness"], "ALIGN_FIXED_ARGUMENTS" ); phase(1); admin()?; both()?; phase(2); let readers = [ipc::service_sid(SERVICE_NAME)?]; let mut public = vec![PinnedFile::open( Path::new(ROOT), true, &readers, &[], false, )?]; let binding_file = PinnedFile::open( &Path::new(ROOT).join("binding.json"), false, &readers, &[], false, )?; let binding: Binding = serde_json::from_slice(&bytes(&binding_file.file, 8192)?)?; public.push(binding_file); phase(3); let (settings, pins) = helper_system::read_settings()?; ensure!( settings.enable_effects && !settings.allow_reboot && settings.schema_version == 3 && settings.pin()?.policy_sha256 == "cfd126d383ec0a948a73270a8362bd835d79341a079be05ce50088f0dbc5791c", "ALIGN_ORIGINAL_PASSIVE_HELPER_ONLY" ); phase(4); let mut locks = vec![]; for index in [2, 4] { let file = leaf(Path::new(PATHS[index]))?; file.try_lock_exclusive() .context("ALIGN_ORIGINAL_LIFETIME_LOCK_BUSY")?; locks.push(file); } both()?; native::private_path(Path::new(STATE), true)?; phase(5); let helper_writer = [ipc::service_sid(ipc::HELPER_SERVICE)?]; let agent_writer = [ipc::service_sid(SERVICE_NAME)?]; public.push(PinnedFile::open_read_shared( Path::new(intent::ROOT), true, &agent_writer, &[], )?); for path in [intent::DB, &format!("{}-journal", intent::DB)] { let proof = PinnedFile::open_read_shared(Path::new(path), false, &[], &agent_writer)?; public.push(proof); } phase(6); let mut held = vec![]; for (index, path) in PATHS.into_iter().enumerate() { if matches!(index, 3 | 4) { let _check = PinnedFile::open_read_shared(Path::new(path), false, &[], &helper_writer)?; } else if index != 5 { native::private_path(Path::new(path), false)?; } let file = leaf(Path::new(path))?; held.push(Held { path: PathBuf::from(path), id: ipc::file_identity(&file)?, legacy: native_id(&file)?, file, }); } phase(7); let boot = Uuid::parse_str( &tokio::runtime::Builder::new_current_thread() .enable_all() .build()? .block_on(native::boot_id())?, )?; ensure!(boot == BOOT, "ALIGN_ORIGINAL_BOOT_REQUIRED"); phase(8); let guard = Guard { held, _locks: locks, _settings: RefCell::new(pins), _public: RefCell::new(public), boot, intents: RefCell::new(intent::Store::open(false)?), }; guard.check()?; phase(9); let a = Db::open(PATHS[0], apply).context("ALIGN_OPEN_TELEMETRY_RO")?; let c = Db::open(PATHS[1], apply).context("ALIGN_OPEN_CONSUMPTION_RO")?; let h = Db::open(PATHS[3], apply).context("ALIGN_OPEN_HELPER_JOURNAL")?; let intents = Db::open(PATHS[5], false).context("ALIGN_OPEN_INTENTS_RO")?; phase(10); let intents_identity: Vec = intents.db.query_row( "SELECT file_identity FROM system_intent_meta WHERE id=1", [], |r| r.get(0), )?; ensure!( serde_json::from_slice::(&intents_identity)? == guard.held[5].id, "ALIGN_ORIGINAL_INTENT_JOURNAL_IDENTITY" ); let (ledger, lock, identity): (Vec, Vec, String) = h.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)? == guard.held[3].id && serde_json::from_slice::(&lock)? == guard.held[4].id && identity == ipc::binding_hash(&settings.binding)?, "ALIGN_HELPER_ORIGINAL_LEDGER_LOCK_IDENTITY" ); phase(11); let live_file = PinnedFile::open( Path::new( r"C:\ProgramData\RustDiscoveryBootstrap\1f18d4273d5d19bdc9d8b3bfe4ed49c7aaa0b7cc282c9a04024896f8db274b85\native-live-archive.json", ), false, &[], &[], false, )?; let live_raw = bytes(&live_file.file, 1024 * 1024)?; ensure!( hash(&live_raw) == "1f18d4273d5d19bdc9d8b3bfe4ed49c7aaa0b7cc282c9a04024896f8db274b85", "NONSTART_EXACT_LIVE_ARCHIVE" ); let archived: serde_json::Value = serde_json::from_slice(&live_raw)?; let live = &archived["live_archive"]; let stop_file = PinnedFile::open( Path::new( r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-stop\stopped.json", ), false, &[], &[], false, )?; let stop_raw = bytes(&stop_file.file, 32768)?; let stop: serde_json::Value = serde_json::from_slice(&stop_raw)?; ensure!( stop["both_stopped"] == true && stop["force_used"] == false && stop["original_held_process_exits_verified"] == true && stop["journal_rows_changed_by_bootstrap"] == false && stop["target_job_executed"] == false && stop["live_archive_sha256"] == hash(&live_raw), "NONSTART_ORIGINAL_HELD_EXIT_PROOF" ); ensure!( stop["original_services"]["RmmDiscoverySystemHelper"]["pid"] == 1304 && stop["original_services"]["RmmDiscoverySystemHelper"]["birth"] == "134393135436289391" && stop["original_services"]["RmmDiscoveryWindows"]["pid"] == 8688 && stop["original_services"]["RmmDiscoveryWindows"]["birth"] == "134393135446375865", "NONSTART_ORIGINAL_LIFETIMES" ); let nonstart = NonstartProof { helper_pid: 1304, helper_birth_filetime: live["helper_birth_filetime"] .as_str() .context("NONSTART_BIRTH")? .into(), helper_image_sha256: live["helper_image_sha256"] .as_str() .context("NONSTART_IMAGE")? .into(), system_script_source_sha256: live["system_script_source_sha256"] .as_str() .context("NONSTART_SOURCE")? .into(), read_share_error: serde_json::from_value(live["read_share_error"].clone())?, read_write_share_passed: live["read_write_share_passed"] == true, state_directory_file_id: serde_json::from_value( live["state_directory_file_id"].clone(), )?, evidence_sha256: vec![hash(&live_raw), hash(&stop_raw)], }; ensure!( nonstart.valid() && live["original_peer_verified_before_after"] == true, "NONSTART_ORIGINAL_LIVE_PROOF" ); let local = Local { agent: &a.db, consumption: &c.db, helper: &h.db, intents: &intents.db, binding: &binding, helper_binding: &settings.binding, }; if apply || verify { let file = PinnedFile::open( Path::new( r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-receipt.json", ), false, &[], &[], false, )?; let raw = bytes(&file.file, 4 * 1024 * 1024)?; if apply { recovery::apply(&local, &guard, &raw, chrono::Utc::now())?; } println!( "{}", serde_json::to_string(&recovery::verify_applied(&local, &guard, &raw)?)? ); return Ok(()); } let witness = recovery::witness(&local, &guard, nonstart)?; for (name, raw) in [ ("target_job_offer", &witness.target_job_offer), ("agent_start", &witness.agent_start), ("helper_start", &witness.helper_start), ("agent_outcome", &witness.agent_outcome), ("helper_outcome", &witness.helper_outcome), ("intent", &witness.intent), ] { ensure!( serde_json::from_value::>(live[name].clone())? == *raw, "NONSTART_LIVE_ARCHIVE_ORIGINAL_CHANGED" ); } for index in 0..2 { ensure!( serde_json::from_value::>(live["original_requests"][index].clone())? == witness.original_requests[index] && serde_json::from_value::( live["original_responses"][index].clone() )? == witness.original_responses[index], "NONSTART_LIVE_ORIGINAL_SYNCS_CHANGED" ); } guard.check()?; println!("{}", serde_json::to_string(&witness)?); Ok(()) } } #[cfg(all(windows, feature = "system-helper"))] fn main() { if let Err(error) = platform::run() { eprintln!("{}", platform::diagnostic(&error)); std::process::exit(1); } } #[cfg(not(all(windows, feature = "system-helper")))] fn main() { eprintln!("Windows system-helper only"); std::process::exit(1); }