Files
rust-discovery/crates/agent-windows/examples/windows_closed_alignment.rs
T
2026-11-16 13:33:26 +01:00

484 lines
18 KiB
Rust

//! 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_sync_alignment::{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_sync_alignment::{BOOT, FILE_ROLES, NativeFile},
};
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::<Vec<_>>();
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::<rusqlite::Error>() {
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::<serde_json::Error>() {
data["codec"] = serde_json::json!({"code":"JSON_CODEC","line":codec.line(),"column":codec.column()});
}
if let Some(io) = cause.downcast_ref::<std::io::Error>() {
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 RECEIPT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\windows-sync-alignment-205.json";
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::<Vec<_>>();
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::<SERVICE_STATUS_PROCESS>() as u32,
&mut size,
)
} != 0
&& status.dwCurrentState == SERVICE_STOPPED
&& status.dwProcessId == 0,
"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<File> {
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<Vec<u8>> {
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<Held>,
_locks: Vec<File>,
_settings: RefCell<Vec<PinnedFile>>,
_public: RefCell<Vec<PinnedFile>>,
boot: Uuid,
intents: RefCell<intent::Store>,
}
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<Uuid> {
Ok(self.boot)
}
}
struct Db {
db: Connection,
_held: Vec<File>,
}
impl Db {
fn open(path: &str, write: bool) -> Result<Self> {
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::<Vec<_>>();
ensure!(
args.len() == 1
&& matches!(
args[0].as_str(),
"--witness" | "--apply-reviewed-receipt" | "--verify-applied"
),
"ALIGN_FIXED_ARGUMENTS"
);
let apply = args[0] == "--apply-reviewed-receipt";
let verify_applied = args[0] == "--verify-applied";
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,
"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_empty_history_snapshot()?),
};
guard.check()?;
phase(9);
let a = Db::open(PATHS[0], false).context("ALIGN_OPEN_TELEMETRY_RO")?;
let c = Db::open(PATHS[1], false).context("ALIGN_OPEN_CONSUMPTION_RO")?;
let mut 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<u8> = intents.db.query_row(
"SELECT file_identity FROM system_intent_meta WHERE id=1",
[],
|r| r.get(0),
)?;
ensure!(
serde_json::from_slice::<ipc::FileIdentity>(&intents_identity)? == guard.held[5].id,
"ALIGN_ORIGINAL_INTENT_JOURNAL_IDENTITY"
);
let (ledger, lock, identity): (Vec<u8>, Vec<u8>, 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::<ipc::FileIdentity>(&ledger)? == guard.held[3].id
&& serde_json::from_slice::<ipc::FileIdentity>(&lock)? == guard.held[4].id
&& identity == ipc::binding_hash(&settings.binding)?,
"ALIGN_HELPER_ORIGINAL_LEDGER_LOCK_IDENTITY"
);
phase(11);
if apply || verify_applied {
let receipt = PinnedFile::open(Path::new(RECEIPT), false, &[], &[], false)?;
let raw = bytes(&receipt.file, 4 * 1024 * 1024)?;
let helper_read = Db::open(PATHS[3], false)?;
let local = Local {
agent: &a.db,
consumption: &c.db,
helper: &helper_read.db,
intents: &intents.db,
binding: &binding,
helper_binding: &settings.binding,
};
if verify_applied {
println!("{}", recovery::verify_applied(&local, &guard, &raw)?);
} else {
recovery::apply(&local, &mut h.db, &guard, &raw, chrono::Utc::now())?;
println!(
"{}",
serde_json::json!({"schema_version":1,"closed_admin_alignment_applied":true,"actual_applied_at":chrono::Utc::now(),"ready":false,"helper_ready":false,"unlock":false,"fresh_normal_signed_sync_required":true})
);
}
} else {
let local = Local {
agent: &a.db,
consumption: &c.db,
helper: &h.db,
intents: &intents.db,
binding: &binding,
helper_binding: &settings.binding,
};
let witness = recovery::witness(&local, &guard)?;
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);
}