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

1272 lines
47 KiB
Rust

//! Unwired fixture-only MSI provider. This module confers no authorization.
//! Caller must authenticate its SYSTEM helper, validate signed job/grant+local
//! recipe policy, hold the device/package conflict lock and durably consume the
//! attempt before start(). Cache population is a separate verified RMM artifact
//! operation: this module has no network, URL, UNC, transform or free arguments.
//!
//! Only fixed1.0 first install/noop and fixed1.0→1.1 major-upgrade/noop.
//! No fresh1.1, downgrade, repair, arbitrary predecessor, or EXE mode.
//! MSI metadata APIs are synchronous. The caller owns the outer observation
//! deadline; a poll timeout is not a promise that Windows Installer stopped.
//! Do not put this controller in a kill-on-close process-tree executor.
//! https://learn.microsoft.com/en-us/windows/win32/api/msi/nf-msi-msigetproductinfoexw
//! https://learn.microsoft.com/en-us/windows/win32/msi/standard-installer-command-line-options
//! https://learn.microsoft.com/en-us/windows/win32/msi/reboot
//! https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
#[cfg(windows)]
use anyhow::{Result, ensure};
#[cfg(any(windows, test))]
use rmm_domain::windows_execution::{ResolvedWindowsMsi, valid_package_code};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub product_code: String,
pub package_code: Option<String>,
pub related_products: Vec<String>,
pub predecessor_state: Option<String>,
pub predecessor_version: Option<String>,
pub predecessor_package_code: Option<String>,
pub product_state: Option<String>,
pub product_version: Option<String>,
pub payload_sha256: Option<String>,
pub payload_bytes: Option<u64>,
}
impl Snapshot {
#[cfg(any(windows, test))]
pub(crate) fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
let p = &r.recipe.postcondition;
self.product_code == p.product_code
&& self.related_products == [p.product_code.clone()]
&& self.predecessor_state.is_none()
&& self.predecessor_version.is_none()
&& self.predecessor_package_code.is_none()
&& r.recipe
.package_code
.as_ref()
.is_none_or(|code| self.package_code.as_ref() == Some(code))
&& self.product_state.as_deref() == Some("5")
&& self.product_version.as_deref() == Some(&p.product_version)
&& self.payload_sha256.as_deref() == Some(&p.payload_sha256)
&& self.payload_bytes == Some(p.payload_bytes)
}
#[cfg(any(windows, test))]
fn absent(&self) -> bool {
self.related_products.is_empty()
&& self.package_code.is_none()
&& self.predecessor_state.is_none()
&& self.predecessor_version.is_none()
&& self.predecessor_package_code.is_none()
&& self.product_state.is_none()
&& self.product_version.is_none()
&& self.payload_sha256.is_none()
&& self.payload_bytes.is_none()
}
#[cfg(any(windows, test))]
fn predecessor(&self, r: &ResolvedWindowsMsi) -> bool {
let Some(old) = &r.recipe.predecessor else {
return false;
};
self.product_code == r.recipe.postcondition.product_code
&& self.related_products == [old.product_code.clone()]
&& self.product_state.is_none()
&& self.product_version.is_none()
&& self.package_code.is_none()
&& self.predecessor_state.as_deref() == Some("5")
&& self.predecessor_version.as_ref() == Some(&old.product_version)
&& self.predecessor_package_code.as_ref().is_some_and(|code| {
valid_package_code(code) && Some(code) != r.recipe.package_code.as_ref()
})
&& self.payload_sha256.as_ref() == Some(&old.payload_sha256)
&& self.payload_bytes == Some(old.payload_bytes)
}
#[cfg(any(windows, test))]
fn baseline_allowed(&self, r: &ResolvedWindowsMsi) -> bool {
self.desired(r)
|| if r.recipe.predecessor.is_some() {
self.predecessor(r)
} else {
self.absent()
}
}
}
#[derive(Debug, Serialize)]
pub struct Observation {
pub recipe_sha256: String,
pub artifact_sha256: String,
pub process_id: Option<u32>,
pub state: &'static str,
pub code: &'static str,
pub exit_code: Option<u32>,
pub postconditions_passed: bool,
pub already_desired: bool,
pub installer_process_started: bool,
/// None when no transaction-level observation exists; spawning msiexec is
/// not itself evidence that the Windows Installer service began a change.
pub transaction_started: Option<bool>,
/// Only the installer's own exit semantics; ambient host reboot state is
/// not inferred from an MSI process exit or from an exact no-op.
pub installer_reboot_required: Option<bool>,
pub reboot_initiated: bool,
pub before: Snapshot,
pub after: Option<Snapshot>,
pub automatic_retry: bool,
}
#[cfg(any(windows, test))]
fn classification(
exit: u32,
postconditions: bool,
) -> (&'static str, &'static str, Option<bool>, bool) {
match exit {
0 | 3010 if postconditions => (
"succeeded",
"MSI_POSTCONDITIONS_VERIFIED",
Some(exit == 3010),
false,
),
0 | 3010 => (
"failed",
"MSI_POSTCONDITIONS_FAILED",
Some(exit == 3010),
false,
),
1641 => (
"unknown",
"MSI_UNEXPECTED_REBOOT_INITIATED",
Some(true),
true,
),
1618 => ("failed", "MSI_ANOTHER_INSTALLATION_RUNNING", None, false),
_ => ("unknown", "MSI_FAILURE_EFFECT_UNRESOLVED", None, false),
}
}
#[cfg(any(windows, test))]
fn within_budget(began: std::time::Instant, timeout: std::time::Duration) -> bool {
began.elapsed() < timeout
}
/// Classify only evidence actually observed inside the original budget. An
/// installer may already have changed the machine when a late poll sees exit0;
/// late evidence cannot retroactively turn that timed-out attempt into success.
#[cfg(any(windows, test))]
fn observed_classification(
exit: u32,
postconditions: bool,
within_deadline: bool,
) -> (&'static str, &'static str, Option<bool>, bool) {
let result = classification(exit, postconditions);
if within_deadline {
result
} else {
(
"unknown",
"MSI_TIMEOUT_EFFECT_UNRESOLVED",
result.2,
result.3,
)
}
}
#[cfg(any(windows, test))]
fn expected_upgrade_rows() -> Vec<Vec<Option<String>>> {
use rmm_domain::windows_execution::*;
let row = |min: &str, max: Option<&str>, attributes: &str, property: &str| {
vec![
Some(MSI_UPGRADE_CODE.into()),
Some(min.into()),
max.map(str::to_owned),
None,
Some(attributes.into()),
Some("ALL".into()),
Some(property.into()),
]
};
// Both lists must contain exactly the one approved ProductCode in the
// LaunchCondition. OnlyDetect never removes an unexpected family member.
vec![
row("0.0.0", None, "258", MSI_ALL_PRODUCTS),
row(MSI_VERSION, Some(MSI_VERSION), "768", MSI_OLD_PRODUCTS),
]
}
#[cfg(any(windows, test))]
fn expected_sequence_rows(upgrade: bool) -> Vec<Vec<Option<String>>> {
let mut rows = vec![
("LaunchConditions", 100),
("CostInitialize", 800),
("FileCost", 900),
("CostFinalize", 1000),
("InstallValidate", 1400),
("InstallInitialize", 1500),
("ProcessComponents", 1600),
("UnpublishFeatures", 1800),
("RemoveFiles", 3500),
("RemoveFolders", 3600),
("CreateFolders", 3700),
("InstallFiles", 4000),
("RegisterUser", 6000),
("RegisterProduct", 6100),
("PublishFeatures", 6300),
("PublishProduct", 6400),
("InstallFinalize", 6600),
];
if upgrade {
rows.extend([
("FindRelatedProducts", 25),
("RemoveExistingProducts", 1550),
]);
}
rows.sort_by_key(|r| r.1);
rows.into_iter()
.map(|(action, seq)| {
vec![
Some(action.into()),
if action == "RemoveExistingProducts" {
Some("NOT Installed".into())
} else {
None
},
Some(seq.to_string()),
]
})
.collect()
}
/// Contract and locally protected policy must agree, independently of the job.
/// The policy hash must come from the helper's protected settings, never a field
/// copied back out of the job being checked.
#[cfg(windows)]
fn validate(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<()> {
ensure!(
r.validate() && r.recipe_sha256 == allowed_recipe_sha256,
"MSI_RECIPE_NOT_ALLOWED"
);
Ok(())
}
#[cfg(windows)]
mod windows {
use super::*;
use rmm_domain::windows_execution::*;
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom},
mem::{size_of, zeroed},
os::windows::{
ffi::OsStrExt,
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
process::{Child, Command, Stdio},
ptr,
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::*,
Security::{Authorization::*, *},
Storage::FileSystem::*,
System::{
ApplicationInstallationAndServicing::*, SystemInformation::GetSystemWindowsDirectoryW,
},
};
const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
const FIXTURES: &str = r"C:\Program Files\RustDiscoveryFixtures";
const TRUSTED_INSTALLER: &str =
"S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
fn wide(s: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
s.as_ref().encode_wide().chain(Some(0)).collect()
}
fn sid(sid: PSID) -> Result<String> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
"MSI_SID"
);
let result = (|| {
let mut n = 0;
while n < 192 && unsafe { *raw.add(n) } != 0 {
n += 1
}
ensure!(n < 192, "MSI_SID_LIMIT");
Ok(String::from_utf16(unsafe {
std::slice::from_raw_parts(raw, n)
})?)
})();
unsafe {
LocalFree(raw.cast());
}
result
}
fn acl(file: &File, system_binary: bool) -> Result<()> {
let mut owner = ptr::null_mut();
let mut dacl = ptr::null_mut();
let mut descriptor = ptr::null_mut();
ensure!(
unsafe {
GetSecurityInfo(
file.as_raw_handle(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&mut owner,
ptr::null_mut(),
&mut dacl,
ptr::null_mut(),
&mut descriptor,
)
} == 0,
"MSI_FILE_ACL"
);
let result = (|| {
ensure!(
!owner.is_null() && !dacl.is_null() && unsafe { (*dacl).AceCount } > 0,
"MSI_NULL_DACL"
);
let privileged = |s: &str| {
s == "S-1-5-18" || s == "S-1-5-32-544" || (system_binary && s == TRUSTED_INSTALLER)
};
ensure!(privileged(&sid(owner)?), "MSI_FILE_OWNER");
for i in 0..unsafe { (*dacl).AceCount } {
let mut raw = ptr::null_mut();
ensure!(
unsafe { GetAce(dacl, i.into(), &mut raw) } != 0,
"MSI_FILE_ACE"
);
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& ace.Header.AceSize as usize >= size_of::<ACCESS_ALLOWED_ACE>(),
"MSI_ACE_TYPE"
);
if ace.Header.AceFlags & INHERIT_ONLY_ACE as u8 != 0 {
continue;
}
let who = sid(ptr::addr_of!(ace.SidStart).cast_mut().cast())?;
ensure!(
privileged(&who)
|| ace.Mask & !(0x0012_00a9 | GENERIC_READ | GENERIC_EXECUTE) == 0,
"MSI_WRITABLE_BY_UNTRUSTED_PRINCIPAL"
);
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
result
}
fn information(file: &File, directory: bool) -> Result<BY_HANDLE_FILE_INFORMATION> {
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,
"MSI_REGULAR_PATH"
);
Ok(i)
}
fn id(i: &BY_HANDLE_FILE_INFORMATION) -> (u32, u32, u32) {
(i.dwVolumeSerialNumber, i.nFileIndexHigh, i.nFileIndexLow)
}
struct Held {
file: File,
path: PathBuf,
identity: (u32, u32, u32),
_ancestors: Vec<File>,
system_binary: bool,
}
impl Held {
fn open(path: &Path, system_binary: bool) -> Result<Self> {
ensure!(
path.is_absolute()
&& !path.to_string_lossy().starts_with(r"\\")
&& !path.to_string_lossy().contains(".."),
"MSI_LOCAL_PATH"
);
let mut ancestors = Vec::new();
for parent in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
wide(parent).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_ANCESTOR_OPEN");
let file = unsafe { File::from_raw_handle(raw) };
information(&file, true)?;
ancestors.push(file);
}
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let i = information(&file, false)?;
ensure!(system_binary || i.nNumberOfLinks == 1, "MSI_HARDLINK");
acl(&file, system_binary)?;
Ok(Self {
file,
path: path.into(),
identity: id(&i),
_ancestors: ancestors,
system_binary,
})
}
fn check(&self) -> Result<()> {
ensure!(
id(&information(&self.file, false)?) == self.identity,
"MSI_HELD_ID"
);
acl(&self.file, self.system_binary)?;
let again = Self::open(&self.path, self.system_binary)?;
ensure!(again.identity == self.identity, "MSI_PATH_REPLACED");
Ok(())
}
fn hash(&mut self, max: u64) -> Result<(String, u64)> {
self.check()?;
let len = self.file.metadata()?.len();
ensure!(len > 0 && len <= max, "MSI_FILE_LENGTH");
self.file.seek(SeekFrom::Start(0))?;
let mut sha = Sha256::new();
let mut count = 0u64;
let mut buffer = [0u8; 8192];
loop {
let n = self.file.read(&mut buffer)?;
if n == 0 {
break;
}
count += n as u64;
ensure!(count <= max, "MSI_FILE_GROWTH");
sha.update(&buffer[..n]);
}
ensure!(count == len, "MSI_FILE_CHANGED");
self.check()?;
Ok((format!("{:x}", sha.finalize()), count))
}
}
struct Msi(u32);
impl Drop for Msi {
fn drop(&mut self) {
if self.0 != 0 {
unsafe {
MsiCloseHandle(self.0);
}
}
}
}
fn msi_text(db: u32, query: &str) -> Result<String> {
let mut view = 0;
ensure!(
unsafe { MsiDatabaseOpenViewW(db, wide(query).as_ptr(), &mut view) } == 0,
"MSI_DATABASE_VIEW"
);
let view = Msi(view);
ensure!(
unsafe { MsiViewExecute(view.0, 0) } == 0,
"MSI_DATABASE_EXECUTE"
);
let mut record = 0;
ensure!(
unsafe { MsiViewFetch(view.0, &mut record) } == 0,
"MSI_DATABASE_ROW"
);
let record = Msi(record);
let mut text = [0u16; 256];
let mut len = 255;
ensure!(
unsafe { MsiRecordGetStringW(record.0, 1, text.as_mut_ptr(), &mut len) } == 0
&& len < 256,
"MSI_DATABASE_STRING"
);
let mut extra = 0;
let code = unsafe { MsiViewFetch(view.0, &mut extra) };
let _extra = Msi(extra);
ensure!(code == ERROR_NO_MORE_ITEMS, "MSI_DATABASE_NOT_UNIQUE");
Ok(String::from_utf16(&text[..len as usize])?)
}
fn msi_rows(db: u32, query: &str, fields: u32) -> Result<Vec<Vec<Option<String>>>> {
let mut view = 0;
ensure!(
unsafe { MsiDatabaseOpenViewW(db, wide(query).as_ptr(), &mut view) } == 0,
"MSI_ROWS_VIEW"
);
let view = Msi(view);
ensure!(
unsafe { MsiViewExecute(view.0, 0) } == 0,
"MSI_ROWS_EXECUTE"
);
let mut rows = Vec::new();
loop {
let mut record = 0;
let code = unsafe { MsiViewFetch(view.0, &mut record) };
let record = Msi(record);
if code == ERROR_NO_MORE_ITEMS {
return Ok(rows);
}
ensure!(
code == 0
&& rows.len() < 64
&& unsafe { MsiRecordGetFieldCount(record.0) } == fields,
"MSI_ROWS_BOUND"
);
let mut row = Vec::new();
for field in 1..=fields {
if unsafe { MsiRecordIsNull(record.0, field) } != 0 {
row.push(None);
continue;
}
let mut text = [0u16; 256];
let mut count = 255;
ensure!(
unsafe { MsiRecordGetStringW(record.0, field, text.as_mut_ptr(), &mut count) }
== 0
&& count < 256,
"MSI_ROW_STRING"
);
row.push(Some(String::from_utf16(&text[..count as usize])?));
}
rows.push(row);
}
}
fn inspect_upgrade(db: u32, r: &ResolvedWindowsMsi) -> Result<()> {
let upgrade = r.recipe.predecessor.is_some();
let tables = msi_rows(db, "SELECT `Name` FROM `_Tables` WHERE `Name`='Upgrade'", 1)?;
if upgrade {
ensure!(
tables == vec![vec![Some("Upgrade".into())]],
"MSI_UPGRADE_TABLE_REQUIRED"
);
ensure!(
msi_rows(
db,
"SELECT `UpgradeCode`,`VersionMin`,`VersionMax`,`Language`,`Attributes`,`Remove`,`ActionProperty` FROM `Upgrade` ORDER BY `ActionProperty`",
7
)? == expected_upgrade_rows(),
"MSI_EXACT_UPGRADE_TABLE_REQUIRED"
);
ensure!(
msi_text(
db,
"SELECT `Value` FROM `Property` WHERE `Property`='SecureCustomProperties'"
)? == format!("{MSI_ALL_PRODUCTS};{MSI_OLD_PRODUCTS}"),
"MSI_SECURE_UPGRADE_PROPERTIES"
);
ensure!(
msi_rows(
db,
"SELECT `Condition`,`Description` FROM `LaunchCondition` ORDER BY `Condition`",
2
)? == vec![
vec![
Some(MSI_UPGRADE_CONDITION.into()),
Some(
"Only the exact approved fixture1.0 predecessor may be upgraded."
.into()
)
],
vec![
Some("VersionNT64".into()),
Some("This fixture requires 64-bit Windows.".into())
]
],
"MSI_EXACT_UPGRADE_LAUNCH_CONDITIONS"
);
} else {
ensure!(tables.is_empty(), "MSI_UNEXPECTED_UPGRADE_TABLE");
}
ensure!(
msi_rows(
db,
"SELECT `Action`,`Condition`,`Sequence` FROM `InstallExecuteSequence` ORDER BY `Sequence`",
3
)? == expected_sequence_rows(upgrade),
"MSI_EXACT_EXECUTE_SEQUENCE_REQUIRED"
);
Ok(())
}
fn no_custom_actions(db: u32) -> Result<()> {
let mut view = 0;
ensure!(
unsafe {
MsiDatabaseOpenViewW(
db,
wide("SELECT `Name` FROM `_Tables` WHERE `Name`='CustomAction'").as_ptr(),
&mut view,
)
} == 0,
"MSI_TABLE_LIST"
);
let view = Msi(view);
ensure!(unsafe { MsiViewExecute(view.0, 0) } == 0, "MSI_TABLE_QUERY");
let mut record = 0;
let code = unsafe { MsiViewFetch(view.0, &mut record) };
let _record = Msi(record);
if code == ERROR_NO_MORE_ITEMS {
return Ok(());
}
ensure!(code == 0, "MSI_TABLE_FETCH");
let mut actions = 0;
ensure!(
unsafe {
MsiDatabaseOpenViewW(
db,
wide("SELECT `Action` FROM `CustomAction`").as_ptr(),
&mut actions,
)
} == 0,
"MSI_CUSTOM_ACTION_QUERY"
);
let actions = Msi(actions);
ensure!(
unsafe { MsiViewExecute(actions.0, 0) } == 0,
"MSI_CUSTOM_ACTION_EXECUTE"
);
let mut action = 0;
let code = unsafe { MsiViewFetch(actions.0, &mut action) };
let _action = Msi(action);
ensure!(code == ERROR_NO_MORE_ITEMS, "MSI_CUSTOM_ACTIONS_DENIED");
Ok(())
}
fn inspect_archive(file: &mut Held, r: &ResolvedWindowsMsi) -> Result<()> {
let (sha, len) = file.hash(262144)?;
ensure!(
sha == r.recipe.artifact.sha256 && len == r.recipe.artifact.bytes,
"MSI_ARTIFACT_HASH"
);
let mut db = 0;
ensure!(
unsafe { MsiOpenDatabaseW(wide(&file.path).as_ptr(), MSIDBOPEN_READONLY, &mut db) }
== 0,
"MSI_DATABASE_OPEN"
);
let db = Msi(db);
no_custom_actions(db.0)?;
inspect_upgrade(db.0, r)?;
let cabinet = msi_text(db.0, "SELECT `Cabinet` FROM `Media`")?;
ensure!(
cabinet.starts_with('#')
&& cabinet.len() > 1
&& cabinet.len() <= 128
&& cabinet[1..]
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)),
"MSI_EMBEDDED_CABINET_REQUIRED"
);
for (field, value) in [
("ProductCode", r.recipe.postcondition.product_code.as_str()),
(
"ProductVersion",
r.recipe.postcondition.product_version.as_str(),
),
("ALLUSERS", "1"),
("UpgradeCode", r.recipe.upgrade_code.as_str()),
] {
ensure!(
msi_text(
db.0,
&format!("SELECT `Value` FROM `Property` WHERE `Property`='{field}'")
)? == value,
"MSI_DATABASE_PROPERTY"
);
}
let mut summary = 0;
ensure!(
unsafe { MsiGetSummaryInformationW(db.0, ptr::null(), 0, &mut summary) } == 0,
"MSI_SUMMARY"
);
let summary = Msi(summary);
let mut kind = 0;
let mut value = 0;
let mut time: FILETIME = unsafe { zeroed() };
let mut text = [0u16; 256];
let mut len = 255;
ensure!(
unsafe {
MsiSummaryInfoGetPropertyW(
summary.0,
7,
&mut kind,
&mut value,
&mut time,
text.as_mut_ptr(),
&mut len,
)
} == 0
&& kind == 30
&& len < 256,
"MSI_ARCHITECTURE_SUMMARY"
);
ensure!(
String::from_utf16(&text[..len as usize])?.starts_with("x64;"),
"MSI_NOT_X64"
);
let mut len = 255;
ensure!(
unsafe {
MsiSummaryInfoGetPropertyW(
summary.0,
9,
&mut kind,
&mut value,
&mut time,
text.as_mut_ptr(),
&mut len,
)
} == 0
&& kind == 30
&& len < 256,
"MSI_PACKAGE_SUMMARY"
);
let package_code = String::from_utf16(&text[..len as usize])?;
ensure!(
valid_package_code(&package_code)
&& r.recipe
.package_code
.as_ref()
.is_none_or(|code| code == &package_code),
"MSI_PACKAGE_CODE_BINDING"
);
file.check()?;
Ok(())
}
fn property(product: &str, name: &str) -> Result<Option<String>> {
let mut value = [0u16; 256];
let mut len = 255;
let code = unsafe {
MsiGetProductInfoExW(
wide(product).as_ptr(),
ptr::null(),
MSIINSTALLCONTEXT_MACHINE,
wide(name).as_ptr(),
value.as_mut_ptr(),
&mut len,
)
};
if code == ERROR_UNKNOWN_PRODUCT {
return Ok(None);
}
ensure!(code == 0 && len < 256, "MSI_MACHINE_PRODUCT_QUERY");
Ok(Some(String::from_utf16(&value[..len as usize])?))
}
fn snapshot_product(product: &str, predecessor: Option<&str>) -> Result<Snapshot> {
let product_state = property(product, "State")?;
let product_version = if product_state.as_deref() == Some("5") {
property(product, "VersionString")?
} else {
None
};
let package_code = if product_state.as_deref() == Some("5") {
property(product, "PackageCode")?
} else {
None
};
let predecessor_state = predecessor
.map(|p| property(p, "State"))
.transpose()?
.flatten();
let predecessor_version = if predecessor_state.as_deref() == Some("5") {
property(predecessor.unwrap(), "VersionString")?
} else {
None
};
let predecessor_package_code = if predecessor_state.as_deref() == Some("5") {
property(predecessor.unwrap(), "PackageCode")?
} else {
None
};
let mut related_products = Vec::new();
for index in 0..=16 {
let mut code = [0u16; 39];
let status = unsafe {
MsiEnumRelatedProductsW(
wide(MSI_UPGRADE_CODE).as_ptr(),
0,
index,
code.as_mut_ptr(),
)
};
if status == ERROR_NO_MORE_ITEMS {
break;
}
ensure!(
status == ERROR_SUCCESS && index < 16 && code[38] == 0,
"MSI_RELATED_PRODUCT_QUERY"
);
let code = String::from_utf16(&code[..38])?;
ensure!(
!related_products.contains(&code),
"MSI_DUPLICATE_RELATED_PRODUCT"
);
related_products.push(code);
}
related_products.sort();
let (payload_sha256, payload_bytes) = match std::fs::symlink_metadata(MSI_PAYLOAD) {
Ok(_) => {
let mut file = Held::open(Path::new(MSI_PAYLOAD), false)?;
let (sha, len) = file.hash(65536)?;
(Some(sha), Some(len))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
Err(e) => return Err(e.into()),
};
Ok(Snapshot {
product_code: product.into(),
package_code,
related_products,
predecessor_state,
predecessor_version,
predecessor_package_code,
product_state,
product_version,
payload_sha256,
payload_bytes,
})
}
/// Retained1.0 read-only witness. No implicit choice of upgrade recipe.
pub fn snapshot() -> Result<Snapshot> {
snapshot_product(MSI_PRODUCT_CODE, None)
}
pub fn snapshot_for(r: &ResolvedWindowsMsi) -> Result<Snapshot> {
ensure!(r.validate(), "MSI_RECIPE_INVALID");
snapshot_product(
&r.recipe.postcondition.product_code,
r.recipe
.predecessor
.as_ref()
.map(|old| old.product_code.as_str()),
)
}
fn system_root() -> Result<PathBuf> {
let mut value = [0u16; 32768];
let len = unsafe { GetSystemWindowsDirectoryW(value.as_mut_ptr(), value.len() as u32) };
ensure!(len > 0 && (len as usize) < value.len(), "MSI_SYSTEM_ROOT");
Ok(PathBuf::from(String::from_utf16(&value[..len as usize])?))
}
pub struct Prepared {
recipe: ResolvedWindowsMsi,
archive: Held,
msiexec: Held,
_roots: Vec<File>,
before: Snapshot,
system_root: PathBuf,
}
impl Prepared {
pub fn prepare(
r: &ResolvedWindowsMsi,
allowed_recipe_sha256: &str,
began: Instant,
timeout: Duration,
) -> Result<Self> {
validate(r, allowed_recipe_sha256)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let mut roots = Vec::new();
for path in [CACHE, FIXTURES] {
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
information(&file, true)?;
acl(&file, false)?;
roots.push(file);
}
let mut archive = Held::open(
&Path::new(CACHE).join(format!("{}.msi", r.recipe.artifact.sha256)),
false,
)?;
inspect_archive(&mut archive, r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let system_root = system_root()?;
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
let before = snapshot_for(r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
ensure!(
before.baseline_allowed(r),
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
);
Ok(Self {
recipe: r.clone(),
archive,
msiexec,
_roots: roots,
before,
system_root,
})
}
fn verification_timeout(&self, after: Option<Snapshot>) -> Run {
Run::Noop(Box::new(Observation {
recipe_sha256: self.recipe.recipe_sha256.clone(),
artifact_sha256: self.recipe.recipe.artifact.sha256.clone(),
process_id: None,
state: "unknown",
code: "MSI_VERIFICATION_TIMEOUT_NO_INSTALLER_START",
exit_code: None,
postconditions_passed: false,
already_desired: false,
installer_process_started: false,
transaction_started: Some(false),
installer_reboot_required: None,
reboot_initiated: false,
before: self.before.clone(),
after,
automatic_retry: false,
}))
}
/// Called only after durable original-grant consumption. No change of
/// config, privilege, policy, clock, reboot or foreign process occurs.
pub fn start(
mut self,
began: Instant,
timeout: Duration,
cancelled: &AtomicBool,
check_effect_fence: impl FnOnce() -> Result<()>,
) -> Result<Run> {
ensure!(
timeout >= Duration::from_secs(1)
&& timeout <= Duration::from_secs(300)
&& !cancelled.load(Ordering::SeqCst),
"MSI_START_LIMIT_OR_CANCELLED"
);
// One original budget includes all synchronous verification and
// the eventual installer. A late Noop is not retroactive success.
let archive = inspect_archive(&mut self.archive, &self.recipe);
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(None));
}
archive?;
let executable = self.msiexec.check();
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(None));
}
executable?;
let observation = snapshot_for(&self.recipe);
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(observation.ok()));
}
let before = observation?;
ensure!(before == self.before, "MSI_BASELINE_CHANGED");
// Both a Noop and an installer decision require a fresh caller
// authorization fence; no bypass for the already-desired branch.
check_effect_fence()?;
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(Some(before)));
}
ensure!(
!cancelled.load(Ordering::SeqCst),
"MSI_CANCELLED_BEFORE_START"
);
if before.desired(&self.recipe) {
return Ok(Run::Noop(Box::new(Observation {
recipe_sha256: self.recipe.recipe_sha256.clone(),
artifact_sha256: self.recipe.recipe.artifact.sha256.clone(),
process_id: None,
state: "succeeded",
code: "MSI_ALREADY_DESIRED",
exit_code: None,
postconditions_passed: true,
already_desired: true,
installer_process_started: false,
transaction_started: Some(false),
installer_reboot_required: None,
reboot_initiated: false,
before: before.clone(),
after: Some(before),
automatic_retry: false,
})));
}
ensure!(
before.baseline_allowed(&self.recipe),
"MSI_INSTALL_BASELINE_CONFLICT"
);
use std::os::windows::process::CommandExt;
let child = Command::new(&self.msiexec.path)
.args([
std::ffi::OsStr::new("/i"),
self.archive.path.as_os_str(),
std::ffi::OsStr::new("/qn"),
std::ffi::OsStr::new("/norestart"),
std::ffi::OsStr::new("REBOOT=ReallySuppress"),
std::ffi::OsStr::new("ALLUSERS=1"),
])
.env_clear()
.env("SystemRoot", &self.system_root)
.current_dir(CACHE)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(0x08000000)
.spawn()?;
Ok(Run::Installer(Box::new(Installer {
prepared: self,
child,
began,
timeout,
})))
}
}
pub enum Run {
Noop(Box<Observation>),
Installer(Box<Installer>),
}
pub struct Installer {
prepared: Prepared,
child: Child,
began: Instant,
timeout: Duration,
}
impl Installer {
/// Observe only this retained process handle. Never adopt a PID, kill,
/// restart, or revise an already persisted timeout outcome.
pub fn process_exited(&mut self) -> Result<bool> {
Ok(self.child.try_wait()?.is_some())
}
pub fn process_id(&self) -> u32 {
self.child.id()
}
/// Poll the SAME process only. Timeout/cancel neither kills msiexec nor
/// the system installer service. Caller retains/fences this attempt;
/// another poll is evidence gathering, never a second start.
pub fn poll(&mut self, cancelled: &AtomicBool) -> Result<Option<Observation>> {
let exit = self.child.try_wait()?;
let code = if let Some(status) = exit {
status.code().map(|n| n as u32)
} else {
None
};
if exit.is_none()
&& !cancelled.load(Ordering::SeqCst)
&& within_budget(self.began, self.timeout)
{
return Ok(None);
}
let mut after = None;
let (state, error, reboot, initiated) = if let Some(code) = code {
// No extra synchronous MSI query once the original budget has
// expired. try_wait and snapshot can themselves return late.
if within_budget(self.began, self.timeout) {
after = snapshot_for(&self.prepared.recipe).ok();
}
let within_deadline = within_budget(self.began, self.timeout);
if !within_deadline {
observed_classification(code, false, false)
} else if after.is_none() && matches!(code, 0 | 3010) {
(
"unknown",
"MSI_POSTCONDITION_QUERY_FAILED",
Some(code == 3010),
false,
)
} else {
observed_classification(
code,
after
.as_ref()
.is_some_and(|s| s.desired(&self.prepared.recipe)),
within_deadline,
)
}
} else {
(
"unknown",
if cancelled.load(Ordering::SeqCst) {
"MSI_CANCELLED_EFFECT_UNRESOLVED"
} else {
"MSI_TIMEOUT_EFFECT_UNRESOLVED"
},
None,
false,
)
};
Ok(Some(Observation {
recipe_sha256: self.prepared.recipe.recipe_sha256.clone(),
artifact_sha256: self.prepared.recipe.recipe.artifact.sha256.clone(),
process_id: Some(self.child.id()),
state,
code: error,
exit_code: code,
postconditions_passed: state == "succeeded",
already_desired: false,
installer_process_started: true,
transaction_started: if code == Some(1618) {
Some(false)
} else {
None
},
installer_reboot_required: reboot,
reboot_initiated: initiated,
before: self.prepared.before.clone(),
after,
automatic_retry: false,
}))
}
}
}
#[cfg(windows)]
pub use windows::{Installer, Prepared, Run, snapshot, snapshot_for};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upgrade_and_noop_need_independent_exact_products_family_and_payload() {
use rmm_domain::windows_execution::*;
let recipe = WindowsMsiRecipe {
schema_version: 1,
recipe_id: MSI_UPGRADE_RECIPE_ID.into(),
recipe_version: "1".into(),
platform: "windows".into(),
upgrade_code: MSI_UPGRADE_CODE.into(),
architecture: Architecture::X64,
context: InstallContext::Machine,
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
artifact: MsiArtifact {
artifact_id: uuid::Uuid::new_v4(),
sha256: "ab".repeat(32),
bytes: 20480,
},
postcondition: MsiPostcondition {
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
product_version: MSI_UPGRADE_VERSION.into(),
payload_path: MSI_PAYLOAD.into(),
payload_sha256: MSI_PAYLOAD_11_SHA256.into(),
payload_bytes: MSI_PAYLOAD_BYTES,
},
no_reboot: true,
package_code: Some("{8475C4D1-6EE2-4C3A-B41D-D834A20F4135}".into()),
predecessor: Some(MsiPostcondition {
product_code: MSI_PRODUCT_CODE.into(),
product_version: MSI_VERSION.into(),
payload_path: MSI_PAYLOAD.into(),
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
payload_bytes: MSI_PAYLOAD_BYTES,
}),
};
let r = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe,
};
assert!(r.validate());
let mut before = Snapshot {
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
related_products: vec![MSI_PRODUCT_CODE.into()],
predecessor_state: Some("5".into()),
predecessor_version: Some(MSI_VERSION.into()),
predecessor_package_code: Some("{D1C4ECE2-7025-4E16-A842-A20F320CE783}".into()),
payload_sha256: Some(MSI_PAYLOAD_10_SHA256.into()),
payload_bytes: Some(MSI_PAYLOAD_BYTES),
..Snapshot::default()
};
assert!(before.predecessor(&r));
assert!(before.baseline_allowed(&r));
assert!(!before.desired(&r));
assert!(!Snapshot::default().baseline_allowed(&r)); // no fresh1.1 fallback
before
.related_products
.push("{11111111-1111-4111-8111-111111111111}".into());
assert!(!before.baseline_allowed(&r));
let mut after = Snapshot {
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
package_code: r.recipe.package_code.clone(),
related_products: vec![MSI_UPGRADE_PRODUCT_CODE.into()],
product_state: Some("5".into()),
product_version: Some(MSI_UPGRADE_VERSION.into()),
payload_sha256: Some(MSI_PAYLOAD_11_SHA256.into()),
payload_bytes: Some(MSI_PAYLOAD_BYTES),
..Snapshot::default()
};
assert!(after.desired(&r));
after.predecessor_state = Some("5".into());
assert!(!after.desired(&r));
after.predecessor_state = None;
after.payload_sha256 = Some(MSI_PAYLOAD_10_SHA256.into());
assert!(!after.desired(&r));
let table = expected_upgrade_rows();
assert_eq!(table.len(), 2);
assert_eq!(table[0][4].as_deref(), Some("258"));
assert_eq!(table[1][4].as_deref(), Some("768"));
let sequence = expected_sequence_rows(true);
let position = |name: &str| {
sequence
.iter()
.position(|r| r[0].as_deref() == Some(name))
.unwrap()
};
assert!(position("FindRelatedProducts") < position("LaunchConditions"));
assert!(position("InstallInitialize") < position("RemoveExistingProducts"));
assert!(position("RemoveExistingProducts") < position("ProcessComponents"));
}
#[test]
fn late_exit_or_postcondition_cannot_retroactively_succeed_or_retry() {
use std::time::{Duration, Instant};
let original = Instant::now().checked_sub(Duration::from_secs(2)).unwrap();
let timely = within_budget(Instant::now(), Duration::from_secs(60));
let late = within_budget(original, Duration::from_secs(1));
assert!(timely);
assert!(!late);
// This same budget gates the Noop decision and the installer poll;
// metadata returning late does not receive a fresh timer.
assert_eq!(observed_classification(0, true, late).0, "unknown");
for exit in [0, 3010, 1618, 1603, 1641] {
let late = observed_classification(exit, true, false);
assert_eq!(
(late.0, late.1),
("unknown", "MSI_TIMEOUT_EFFECT_UNRESOLVED")
);
assert_eq!(
(late.2, late.3),
(classification(exit, true).2, classification(exit, true).3)
);
}
assert_eq!(observed_classification(0, true, true).0, "succeeded");
assert_eq!(observed_classification(0, false, true).0, "failed");
}
#[test]
fn exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority() {
assert_eq!(
classification(0, true),
(
"succeeded",
"MSI_POSTCONDITIONS_VERIFIED",
Some(false),
false
)
);
assert_eq!(classification(3010, true).2, Some(true));
assert_eq!(classification(0, false).0, "failed");
assert_eq!(
classification(1641, true),
(
"unknown",
"MSI_UNEXPECTED_REBOOT_INITIATED",
Some(true),
true
)
);
assert_eq!(
classification(1618, false).1,
"MSI_ANOTHER_INSTALLATION_RUNNING"
);
assert_eq!(classification(1603, false).0, "unknown");
let advertised = Snapshot {
product_state: Some("1".into()),
product_version: None,
payload_sha256: None,
payload_bytes: None,
..Snapshot::default()
};
assert!(!advertised.absent());
}
}