Files
rust-discovery/crates/agent-windows/src/msi_cache.rs
T

179 lines
6.7 KiB
Rust

//! Fixed public-byte staging and independent SYSTEM cache import. No IPC path,
//! URL or byte-array authority. Directories must be provisioned separately;
//! this module never installs/repairs an ACL, directory, policy or service.
use crate::helper_ipc::{self as ipc, PinnedFile};
use anyhow::{Context, Result, ensure};
use rmm_domain::windows_execution::ResolvedWindowsMsi;
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const AGENT_STATE: &str = r"C:\ProgramData\RustDiscovery\state";
pub const STAGE: &str = r"C:\ProgramData\RustDiscovery\state\msi-stage";
pub const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
fn name(m: &ResolvedWindowsMsi) -> Result<String> {
ensure!(m.validate(), "MSI_CACHE_MANIFEST");
Ok(format!("{}.msi", m.recipe.artifact.sha256))
}
fn regular(file: &File, directory: bool) -> Result<()> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
&& (directory || i.nNumberOfLinks == 1),
"MSI_CACHE_NONREGULAR"
);
Ok(())
}
/// Keep every actual parent open without DELETE sharing throughout the copy.
/// Source data/ACL is untrusted; only the original signed digest authorizes bytes.
fn parents(path: &Path) -> Result<Vec<File>> {
let mut held = Vec::new();
for p in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
ipc::wide(p).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,
"MSI_CACHE_PARENT_NOT_CONFIGURED"
);
let file = unsafe { File::from_raw_handle(raw) };
regular(&file, true)?;
held.push(file);
}
Ok(held)
}
fn checked_bytes(path: &Path, m: &ResolvedWindowsMsi) -> Result<Vec<u8>> {
let _parents = parents(path)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
.context("MSI_STAGE_NOT_CONFIGURED")?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
ensure!(
file.metadata()?.len() == m.recipe.artifact.bytes && m.recipe.artifact.bytes <= 262144,
"MSI_CACHE_LENGTH"
);
let mut bytes = Vec::new();
(&mut file).take(262145).read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(&bytes)) == m.recipe.artifact.sha256,
"MSI_CACHE_DIGEST"
);
let again = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
regular(&again, false)?;
ensure!(ipc::file_identity(&again)? == id, "MSI_CACHE_FILE_REPLACED");
Ok(bytes)
}
pub fn stage_configured() -> bool {
crate::native::private_path(Path::new(STAGE), true).is_ok()
}
/// Called by LocalService only for the already approved original job/attempt.
pub fn stage(m: &ResolvedWindowsMsi, bytes: &[u8]) -> Result<()> {
crate::native::require_local_service()?;
let path = Path::new(STAGE).join(name(m)?);
let _parents = parents(&path)?;
crate::native::private_path(Path::new(STAGE), true)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(bytes)) == m.recipe.artifact.sha256,
"MSI_DOWNLOAD_DIGEST"
);
if path.try_exists()? {
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
return Ok(());
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&path)?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
file.write_all(bytes)?;
file.sync_all()?;
ensure!(ipc::file_identity(&file)? == id, "MSI_STAGE_FILE_CHANGED");
drop(file);
crate::native::private_path(&path, false)?;
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
Ok(())
}
/// Called ONLY after full independent helper authorization and durable consume.
/// Publish to the fixed SYS/Admin cache without replacing any existing entry.
/// Returned guards pin the copied archive until the provider holds its own.
pub fn import(m: &ResolvedWindowsMsi, grant: Uuid) -> Result<Vec<PinnedFile>> {
let file_name = name(m)?;
ensure!(!grant.is_nil(), "MSI_CACHE_GRANT");
let destination = Path::new(CACHE).join(file_name);
let _parents = parents(&destination)?;
let root = PinnedFile::open(Path::new(CACHE), true, &[], &[], false)
.context("MSI_CACHE_NOT_CONFIGURED")?;
if destination.try_exists()? {
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
return Ok(vec![root, archive]);
}
let source: PathBuf = Path::new(STAGE).join(name(m)?);
let bytes = checked_bytes(&source, m)?; // Never trust actor ownership/data.
let pending = Path::new(CACHE).join(format!("{}.{}.pending", m.recipe.artifact.sha256, grant));
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&pending)?;
regular(&file, false)?;
file.write_all(&bytes)?;
file.sync_all()?;
drop(file);
// Cache directory was already independently validated SYS/Admin-only. New
// SYSTEM-created files inherit that boundary; no ACL repair is performed.
let copied = PinnedFile::open(&pending, false, &[], &[], false)?;
checked_bytes(&pending, m)?;
drop(copied);
ensure!(
unsafe {
MoveFileExW(
ipc::wide(&pending).as_ptr(),
ipc::wide(&destination).as_ptr(),
0,
)
} != 0,
"MSI_CACHE_CREATE_ONLY_PUBLICATION"
);
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
Ok(vec![root, archive])
}