//! Fixed read-only helper persistence witness for bootstrap preservation only. //! No keys, request/row values, jobs, migrations, IPC or clock queries are emitted. #[cfg(windows)] mod platform { use anyhow::{Result, ensure}; use rusqlite::{Connection, OpenFlags, types::ValueRef}; use serde::Serialize; use serde_json::json; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, fs::File, io::Read, mem::{size_of, zeroed}, os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, path::{Path, PathBuf}, ptr, time::Duration, }; use windows_sys::Win32::{ Foundation::*, Security::{Authorization::*, *}, Storage::FileSystem::*, System::Threading::*, }; const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem"; const STATE: &str = r"C:\ProgramData\RustDiscoverySystem\state"; const LEDGER: &str = r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite"; const LOCK: &str = r"C:\ProgramData\RustDiscoverySystem\state\executor.lock"; const ACTOR: &str = "S-1-5-80-2738667961-1084496008-3886777835-2738042298-1934696263"; const HELPER: &str = "S-1-5-80-1378800304-2783697212-3564778230-1646893514-1341434273"; const MAX_CELL: usize = 1024 * 1024; const MAX_ROWS: usize = 10000; const MAX_ROW_BYTES: usize = 32 * 1024 * 1024; const READ_MASK: u32 = 0x0012_00a9; fn wide(value: &Path) -> Vec { use std::os::windows::ffi::OsStrExt; value.as_os_str().encode_wide().chain(Some(0)).collect() } fn owned(raw: HANDLE) -> Result { ensure!( !raw.is_null() && raw != INVALID_HANDLE_VALUE, "STATE_HANDLE" ); // SAFETY: successful CreateFile/OpenToken returned a unique owned handle. Ok(unsafe { OwnedHandle::from_raw_handle(raw) }) } struct Local(*mut std::ffi::c_void); impl Drop for Local { fn drop(&mut self) { // SAFETY: this buffer was allocated by the security APIs for LocalFree. unsafe { LocalFree(self.0) }; } } fn sid_text(sid: PSID) -> Result { ensure!( !sid.is_null() && unsafe { IsValidSid(sid) } != 0, "STATE_SID" ); let mut text = ptr::null_mut(); ensure!( unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0, "STATE_SID" ); let _memory = Local(text.cast()); let mut count = 0; while count < 256 && unsafe { *text.add(count) } != 0 { count += 1; } ensure!((1..256).contains(&count), "STATE_SID_BOUND"); Ok(String::from_utf16(unsafe { std::slice::from_raw_parts(text, count) })?) } fn administrator() -> Result<()> { let mut thread = ptr::null_mut(); if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 { let _thread = owned(thread)?; anyhow::bail!("STATE_IMPERSONATION_FORBIDDEN"); } ensure!( unsafe { GetLastError() } == ERROR_NO_TOKEN, "STATE_THREAD_TOKEN" ); let mut storage = [0usize; 16]; let mut size = size_of::<[usize; 16]>() as u32; ensure!( unsafe { CreateWellKnownSid( WinBuiltinAdministratorsSid, ptr::null_mut(), storage.as_mut_ptr().cast(), &mut size, ) } != 0, "STATE_ADMIN_SID" ); let mut enabled = 0; ensure!( unsafe { CheckTokenMembership( ptr::null_mut(), storage.as_ptr().cast_mut().cast(), &mut enabled, ) } != 0 && enabled != 0, "STATE_ADMINISTRATOR_REQUIRED" ); Ok(()) } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] struct FileId { // Strings preserve every 64-bit digit through PowerShell JSON parsing. volume_serial: String, id_hex: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] struct Metadata { file_id: FileId, creation_filetime: String, bytes: u64, links: u32, attributes: u32, owner_sid: String, acl_sha256: String, } #[derive(Clone, Copy, PartialEq, Eq)] enum Role { Public, Private, IntentDirectory, IntentLeaf, } fn security(raw: HANDLE, role: Role, directory: bool) -> Result<(String, String)> { let mut owner = ptr::null_mut(); let mut acl = ptr::null_mut(); let mut descriptor = ptr::null_mut(); let parts = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; ensure!( unsafe { GetSecurityInfo( raw, SE_FILE_OBJECT, parts, &mut owner, ptr::null_mut(), &mut acl, ptr::null_mut(), &mut descriptor, ) } == 0, "STATE_FILE_SECURITY" ); let _descriptor = Local(descriptor); ensure!( !owner.is_null() && !acl.is_null() && !descriptor.is_null(), "STATE_NULL_DACL" ); let owner = sid_text(owner)?; ensure!( matches!(owner.as_str(), "S-1-5-18" | "S-1-5-32-544"), "STATE_OWNER" ); let mut control = 0; let mut revision = 0; ensure!( unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) } != 0 // The original helper creates ledger/lock with inherited ACEs. // Their protected parent remains held and checked by run(). && ((role == Role::Private && !directory) || control & SE_DACL_PROTECTED != 0) && unsafe { IsValidAcl(acl) } != 0, "STATE_PROTECTED_DACL" ); ensure!( unsafe { (*acl).AceCount } > 0 && unsafe { (*acl).AceCount } <= 16, "STATE_ACL_BOUND" ); let mut seen = BTreeSet::new(); for n in 0..unsafe { (*acl).AceCount } { let mut raw_ace = ptr::null_mut(); ensure!( unsafe { GetAce(acl, n.into(), &mut raw_ace) } != 0, "STATE_ACE" ); let ace = unsafe { &*raw_ace.cast::() }; ensure!( ace.Header.AceType == 0 && ace.Header.AceSize as usize >= size_of::() && u32::from(ace.Header.AceFlags) & INHERIT_ONLY_ACE == 0, "STATE_ACE_TYPE" ); let sid = ptr::addr_of!(ace.SidStart).cast_mut().cast(); let name = sid_text(sid)?; ensure!( unsafe { GetLengthSid(sid) } as usize + 8 <= ace.Header.AceSize as usize, "STATE_ACE_SID_SIZE" ); let writer = matches!(name.as_str(), "S-1-5-18" | "S-1-5-32-544") || (role == Role::Private && name == HELPER); let reader = (role == Role::Public && matches!(name.as_str(), ACTOR | HELPER)) || (role == Role::IntentDirectory && name == ACTOR); ensure!( if writer { ace.Mask == FILE_ALL_ACCESS } else if role == Role::IntentLeaf && name == ACTOR { ace.Mask == 0x0012_019f } else { reader && ace.Mask & !READ_MASK == 0 && ace.Mask & 0x0002_0089 == 0x0002_0089 }, "STATE_EXACT_FILE_ROLES" ); seen.insert(name); } ensure!( seen.contains("S-1-5-18") && seen.contains("S-1-5-32-544"), "STATE_REQUIRED_FILE_ROLES" ); if matches!(role, Role::Public | Role::Private) { ensure!(seen.contains(HELPER), "STATE_REQUIRED_HELPER_ROLE"); } if role != Role::Private { ensure!(seen.contains(ACTOR), "STATE_REQUIRED_AGENT_READER"); } let mut sddl = ptr::null_mut(); let mut size = 0; ensure!( unsafe { ConvertSecurityDescriptorToStringSecurityDescriptorW( descriptor, SDDL_REVISION_1, parts, &mut sddl, &mut size, ) } != 0, "STATE_SECURITY_ENCODING" ); let _sddl = Local(sddl.cast()); ensure!((1..=16384).contains(&size), "STATE_SECURITY_BOUND"); let text = unsafe { std::slice::from_raw_parts(sddl, size as usize) }; ensure!(text.last() == Some(&0), "STATE_SECURITY_TERMINATOR"); let text = String::from_utf16(&text[..text.len() - 1])?; Ok((owner, format!("{:x}", Sha256::digest(text.as_bytes())))) } fn metadata(raw: HANDLE, directory: bool, role: Role) -> Result { let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; let mut id: FILE_ID_INFO = unsafe { zeroed() }; ensure!( unsafe { GetFileInformationByHandle(raw, &mut info) } != 0 && unsafe { GetFileInformationByHandleEx( raw, FileIdInfo, (&mut id as *mut FILE_ID_INFO).cast(), size_of::() as u32, ) } != 0, "STATE_FILE_INFORMATION" ); ensure!( info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 && (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory && (directory || info.nNumberOfLinks == 1), "STATE_REGULAR_FILE" ); let bytes = (u64::from(info.nFileSizeHigh) << 32) | u64::from(info.nFileSizeLow); ensure!(directory || bytes <= 1024 * 1024 * 1024, "STATE_FILE_SIZE"); let (owner_sid, acl_sha256) = security(raw, role, directory)?; Ok(Metadata { file_id: FileId { volume_serial: id.VolumeSerialNumber.to_string(), id_hex: id .FileId .Identifier .iter() .map(|b| format!("{b:02x}")) .collect(), }, creation_filetime: ((u64::from(info.ftCreationTime.dwHighDateTime) << 32) | u64::from(info.ftCreationTime.dwLowDateTime)) .to_string(), bytes, links: info.nNumberOfLinks, attributes: info.dwFileAttributes, owner_sid, acl_sha256, }) } fn open(path: &Path, directory: bool, attributes_only: bool) -> Result { owned(unsafe { CreateFileW( wide(path).as_ptr(), if attributes_only { FILE_READ_ATTRIBUTES } else { GENERIC_READ }, FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null(), OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | if directory { FILE_FLAG_BACKUP_SEMANTICS } else { 0 }, ptr::null_mut(), ) }) } struct Held { file: File, path: PathBuf, directory: bool, role: Role, initial: Metadata, } impl Held { fn open(path: &Path, directory: bool, role: Role) -> Result { for ancestor in path.ancestors().skip(1) { let handle = open(ancestor, true, true)?; let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; ensure!( unsafe { GetFileInformationByHandle(handle.as_raw_handle(), &mut info) } != 0 && info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 && info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0, "STATE_ANCESTOR" ); } let file: File = open(path, directory, false)?.into(); let initial = metadata(file.as_raw_handle(), directory, role)?; Ok(Self { file, path: path.into(), directory, role, initial, }) } fn check(&self) -> Result<()> { ensure!( metadata(self.file.as_raw_handle(), self.directory, self.role)? == self.initial, "STATE_HELD_FILE_CHANGED" ); let current = open(&self.path, self.directory, false)?; ensure!( metadata(current.as_raw_handle(), self.directory, self.role)? == self.initial, "STATE_FILE_PATH_CHANGED" ); Ok(()) } } struct Table { name: &'static str, create: &'static str, query: &'static str, types: &'static [u8], } // Lowercase types allow NULL; uppercase types require a value. All query // identifiers/orderings are compile-time constants, never DB/user strings. const TABLES: &[Table] = &[ Table { name: "consumed", create: "CREATE TABLE consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL, job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt))", query: "SELECT grant_id,agent,generation,job,attempt,result FROM consumed INDEXED BY sqlite_autoindex_consumed_1 ORDER BY grant_id LIMIT 10001", types: b"TTITTb", }, Table { name: "execution_evidence", create: "CREATE TABLE execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB)", query: "SELECT grant_id,start,outcome FROM execution_evidence INDEXED BY sqlite_autoindex_execution_evidence_1 ORDER BY grant_id LIMIT 10001", types: b"TBb", }, Table { name: "windows_helper_files", create: "CREATE TABLE windows_helper_files(id INTEGER PRIMARY KEY CHECK(id=1),ledger BLOB NOT NULL,executor_lock BLOB NOT NULL,binding_sha256 TEXT NOT NULL)", query: "SELECT id,ledger,executor_lock,binding_sha256 FROM windows_helper_files ORDER BY id LIMIT 10001", types: b"IBBT", }, Table { name: "helper_sync_meta", create: "CREATE TABLE helper_sync_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,binding_sha256 TEXT NOT NULL,last_decision TEXT,fault TEXT,agent_journal_id TEXT,agent_checkpoint INTEGER NOT NULL DEFAULT 0)", query: "SELECT id,journal_id,checkpoint,generation,binding_sha256,last_decision,fault,agent_journal_id,agent_checkpoint FROM helper_sync_meta ORDER BY id LIMIT 10001", types: b"ITIITtttI", }, Table { name: "helper_sync_rows", create: "CREATE TABLE helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,fingerprint TEXT NOT NULL)", query: "SELECT grant_id,revision,fingerprint FROM helper_sync_rows INDEXED BY sqlite_autoindex_helper_sync_rows_1 ORDER BY grant_id LIMIT 10001", types: b"TIT", }, Table { name: "helper_sync_captures", create: "CREATE TABLE helper_sync_captures(checkpoint INTEGER PRIMARY KEY,snapshot BLOB NOT NULL,fingerprint TEXT NOT NULL,captured_at TEXT NOT NULL)", query: "SELECT checkpoint,snapshot,fingerprint,captured_at FROM helper_sync_captures ORDER BY checkpoint LIMIT 10001", types: b"IBTT", }, Table { name: "helper_sync_decisions", create: "CREATE TABLE helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL)", query: "SELECT decision_id,checkpoint,response,request,fingerprint FROM helper_sync_decisions INDEXED BY sqlite_autoindex_helper_sync_decisions_1 ORDER BY decision_id LIMIT 10001", types: b"TIBBT", }, ]; fn normalized(sql: &str) -> String { sql.chars() .filter(|c| !c.is_ascii_whitespace()) .collect::() .to_ascii_uppercase() .replace("IFNOTEXISTS", "") } fn schema(db: &Connection) -> Result<(BTreeSet, String)> { let mut entries = Vec::new(); let mut present = BTreeSet::new(); let mut indexes = BTreeSet::new(); // Bound and sort the catalog in Rust, never via a disk-backed SQL sort. let mut statement = db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master LIMIT 33")?; let mut rows = statement.query([])?; while let Some(row) = rows.next()? { ensure!(entries.len() < 32, "STATE_SCHEMA_BOUND"); let kind: String = row.get(0)?; let name: String = row.get(1)?; let parent: String = row.get(2)?; let sql: Option = row.get(3)?; ensure!( name.len() <= 96 && parent.len() <= 96 && sql.as_ref().is_none_or(|s| s.len() <= 4096), "STATE_SCHEMA_BOUND" ); if kind == "table" { let table = TABLES .iter() .find(|t| t.name == name) .ok_or_else(|| anyhow::anyhow!("STATE_UNEXPECTED_TABLE"))?; ensure!( parent == name && sql .as_ref() .is_some_and(|s| normalized(s) == normalized(table.create)), "STATE_TABLE_SCHEMA_CHANGED" ); present.insert(name.clone()); } else { ensure!( kind == "index" && sql.is_none() && TABLES.iter().any(|t| t.name == parent), "STATE_UNEXPECTED_SCHEMA_OBJECT" ); indexes.insert((parent.clone(), name.clone())); } entries.push((kind, name, parent, sql)); } ensure!( present.contains("consumed") && present.contains("execution_evidence") && present.contains("windows_helper_files"), "STATE_REQUIRED_SCHEMA" ); let sync = present .iter() .filter(|n| n.starts_with("helper_sync_")) .count(); ensure!(sync == 0 || sync == 4, "STATE_PARTIAL_SYNC_SCHEMA"); let expected: BTreeSet<_> = [ "consumed", "execution_evidence", "helper_sync_rows", "helper_sync_decisions", ] .into_iter() .filter(|n| present.contains(*n)) .flat_map(|name| { let mut names = vec![(name.to_string(), format!("sqlite_autoindex_{name}_1"))]; if name == "consumed" { names.push((name.to_string(), "sqlite_autoindex_consumed_2".into())); } names }) .collect(); ensure!(indexes == expected, "STATE_INDEX_SCHEMA_CHANGED"); entries.sort(); Ok(( present, format!("{:x}", Sha256::digest(serde_json::to_vec(&entries)?)), )) } fn table_rows( db: &Connection, table: &Table, remaining: &mut usize, ) -> Result { let mut hash = Sha256::new(); hash.update(b"rmm.bootstrap.helper-table.v1\0"); hash.update(table.name.as_bytes()); hash.update([0]); let mut count = 0usize; let mut statement = db.prepare(table.query)?; ensure!( statement.column_count() == table.types.len(), "STATE_ROW_COLUMNS" ); let mut rows = statement.query([])?; while let Some(row) = rows.next()? { ensure!(count < MAX_ROWS, "STATE_ROW_COUNT_BOUND"); hash.update(b"R"); for (column, expected) in table.types.iter().enumerate() { let value = row.get_ref(column)?; match value { ValueRef::Null => { ensure!(expected.is_ascii_lowercase(), "STATE_ROW_NULL"); hash.update(b"N"); } ValueRef::Integer(n) => { ensure!(expected.eq_ignore_ascii_case(&b'I'), "STATE_ROW_TYPE"); hash.update(b"I"); hash.update(n.to_le_bytes()); } ValueRef::Text(bytes) | ValueRef::Blob(bytes) => { let tag = if matches!(value, ValueRef::Text(_)) { b'T' } else { b'B' }; ensure!( expected.eq_ignore_ascii_case(&tag) && bytes.len() <= MAX_CELL && bytes.len() <= *remaining, "STATE_ROW_TYPE_OR_BOUND" ); if tag == b'T' { std::str::from_utf8(bytes)?; } *remaining -= bytes.len(); hash.update([tag]); hash.update((bytes.len() as u64).to_le_bytes()); hash.update(bytes); } ValueRef::Real(_) => anyhow::bail!("STATE_ROW_TYPE"), } } count += 1; } hash.update((count as u64).to_le_bytes()); Ok(json!({"rows":count,"rows_sha256":format!("{:x}",hash.finalize())})) } fn sqlite_handle(db: &Connection) -> Result { let mut handle: HANDLE = ptr::null_mut(); // SAFETY: same-thread live SQLite connection, documented native-handle // output operation only. Borrowed VFS handle is never closed or changed. let code = unsafe { rusqlite::ffi::sqlite3_file_control( db.handle(), c"main".as_ptr(), rusqlite::ffi::SQLITE_FCNTL_WIN32_GET_HANDLE, (&mut handle as *mut HANDLE).cast(), ) }; ensure!( code == rusqlite::ffi::SQLITE_OK && !handle.is_null() && handle != INVALID_HANDLE_VALUE, "STATE_SQLITE_NATIVE_HANDLE" ); ensure!( unsafe { rusqlite::ffi::sqlite3_db_readonly(db.handle(), c"main".as_ptr()) } == 1, "STATE_SQLITE_READONLY" ); Ok(handle) } fn absent(path: &Path) -> Result { match std::fs::symlink_metadata(path) { Ok(_) => Ok(false), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true), Err(_) => anyhow::bail!("STATE_PATH_QUERY_FAILED"), } } fn intent_metadata() -> Result<(Vec, serde_json::Value)> { let path = Path::new(ROOT).join("agent-intents"); if absent(&path)? { return Ok((Vec::new(), serde_json::Value::Null)); } let directory = Held::open(&path, true, Role::IntentDirectory)?; let names: BTreeSet<_> = std::fs::read_dir(&path)? .map(|entry| entry.map(|item| item.file_name())) .collect::>()?; let expected: BTreeSet<_> = ["system-intents.sqlite", "system-intents.sqlite-journal"] .into_iter() .map(std::ffi::OsString::from) .collect(); ensure!(names == expected, "STATE_ZERO_INTENT_LEAVES_ONLY"); let database = Held::open(&path.join("system-intents.sqlite"), false, Role::IntentLeaf)?; let journal = Held::open( &path.join("system-intents.sqlite-journal"), false, Role::IntentLeaf, )?; ensure!( database.initial.bytes == 0 && journal.initial.bytes == 0, "STATE_UNINITIALIZED_INTENT_ONLY" ); let value = json!({"directory":directory.initial,"leaves":{"database":database.initial,"journal":journal.initial},"sqlite_initialized":false}); Ok((vec![directory, database, journal], value)) } pub fn run() -> Result<()> { ensure!(std::env::args_os().len() == 1, "STATE_FIXED_NO_ARGUMENTS"); administrator()?; let roots = [ Held::open(Path::new(ROOT), true, Role::Public)?, Held::open(Path::new(STATE), true, Role::Private)?, ]; let ledger = Held::open(Path::new(LEDGER), false, Role::Private)?; let lock = Held::open(Path::new(LOCK), false, Role::Private)?; ensure!(lock.initial.bytes <= 4096, "STATE_LOCK_SIZE"); let settings = Held::open(&Path::new(ROOT).join("helper.json"), false, Role::Public)?; let pin = Held::open(&Path::new(ROOT).join("agent-pin.json"), false, Role::Public)?; let (intent_files, intent_store) = intent_metadata()?; ensure!( settings.initial.bytes <= 32768 && pin.initial.bytes <= 16384, "STATE_PUBLIC_FILE_SIZE" ); // Refuse every existing sidecar, including a possibly hot rollback // journal. Never ask an administrator-owned reader to recover it. Check // the real header before SQLite can consider WAL/shared-memory paths. for suffix in ["-journal", "-wal", "-shm"] { ensure!( absent(Path::new(&format!("{LEDGER}{suffix}")))?, "STATE_SIDECAR_PRESENT" ); } let mut header = [0u8; 100]; (&ledger.file).read_exact(&mut header)?; ensure!( &header[..16] == b"SQLite format 3\0" && header[16..20] == [16, 0, 1, 1], "STATE_ROLLBACK_HEADER_REQUIRED" ); // No URI/nolock/immutable shortcut: retain normal SQLite locking and // change detection. Read-only mode refuses a journal needing recovery. let db = Connection::open_with_flags(LEDGER, OpenFlags::SQLITE_OPEN_READ_ONLY)?; db.busy_timeout(Duration::from_millis(250))?; // Connection-only allocation limits, never PRAGMA or file mutations. unsafe { rusqlite::ffi::sqlite3_limit( db.handle(), rusqlite::ffi::SQLITE_LIMIT_LENGTH, MAX_CELL as i32, ); rusqlite::ffi::sqlite3_limit(db.handle(), rusqlite::ffi::SQLITE_LIMIT_SQL_LENGTH, 4096); rusqlite::ffi::sqlite3_limit(db.handle(), rusqlite::ffi::SQLITE_LIMIT_COLUMN, 32); rusqlite::ffi::sqlite3_limit(db.handle(), rusqlite::ffi::SQLITE_LIMIT_ATTACHED, 0); } db.execute_batch("BEGIN DEFERRED")?; ensure!( metadata(sqlite_handle(&db)?, false, Role::Private)? == ledger.initial, "STATE_CONNECTED_FILE_CHANGED" ); let integrity: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; ensure!(integrity == "ok", "STATE_HELPER_INTEGRITY"); let page_size: u64 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?; let page_count: u64 = db.query_row("PRAGMA page_count", [], |r| r.get(0))?; let journal_mode: String = db.query_row("PRAGMA journal_mode", [], |r| r.get(0))?; ensure!( page_size == 4096 && (1..=262144).contains(&page_count) && page_size * page_count == ledger.initial.bytes && journal_mode == "delete", "STATE_HELPER_STORAGE_PROFILE" ); let (present, schema_sha256) = schema(&db)?; let absent_tables: Vec<_> = TABLES .iter() .filter(|table| !present.contains(table.name)) .map(|table| table.name) .collect(); let mut tables = BTreeMap::new(); let mut remaining = MAX_ROW_BYTES; for table in TABLES.iter().filter(|t| present.contains(t.name)) { tables.insert(table.name, table_rows(&db, table, &mut remaining)?); } ensure!( metadata(sqlite_handle(&db)?, false, Role::Private)? == ledger.initial, "STATE_CONNECTED_FILE_CHANGED" ); for held in roots .iter() .chain([&ledger, &lock, &settings, &pin]) .chain(intent_files.iter()) { held.check()?; } if intent_files.is_empty() { ensure!( absent(&Path::new(ROOT).join("agent-intents"))?, "STATE_INTENT_STORE_APPEARED" ); } db.execute_batch("ROLLBACK")?; let value = json!({"schema_version":1,"type":"rmm.windows.system-state-witness","read_only":true,"bootstrap_administrator":true, "helper_ledger":{"file":ledger.initial,"integrity":"ok","page_size":page_size,"page_count":page_count,"journal_mode":journal_mode,"schema_sha256":schema_sha256,"tables":tables,"absent_tables":absent_tables,"connected_native_file_id_verified":true}, "executor_lock":lock.initial,"public_metadata":{"helper_settings":settings.initial,"agent_pin":pin.initial},"intent_store":intent_store, "private_key_read":false,"private_rows_returned":false,"clock_queried":false,"jobs_created":false}); let encoded = serde_json::to_string(&value)?; ensure!(encoded.len() <= 32768, "STATE_REPORT_BOUND"); println!("{encoded}"); Ok(()) } } fn main() { #[cfg(windows)] if platform::run().is_ok() { return; } // Never print SQLite/OS errors, paths, SQL or private row material. eprintln!("SYSTEM_STATE_WITNESS_REFUSED"); std::process::exit(2); }