Qualify Windows IPC client runtime and prepare bounded native providers
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,758 @@
|
||||
//! 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 first install/exact noop of v1.0.0 is implemented. Upgrade and EXE are
|
||||
//! separate deliveries, not guessed modes of this MSI executor.
|
||||
//! 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(windows)]
|
||||
use rmm_domain::windows_execution::ResolvedWindowsMsi;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Snapshot {
|
||||
pub product_state: Option<String>,
|
||||
pub product_version: Option<String>,
|
||||
pub payload_sha256: Option<String>,
|
||||
pub payload_bytes: Option<u64>,
|
||||
}
|
||||
impl Snapshot {
|
||||
#[cfg(windows)]
|
||||
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
let p = &r.recipe.postcondition;
|
||||
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.product_state.is_none()
|
||||
&& self.product_version.is_none()
|
||||
&& self.payload_sha256.is_none()
|
||||
&& self.payload_bytes.is_none()
|
||||
}
|
||||
}
|
||||
#[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),
|
||||
}
|
||||
}
|
||||
/// 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::{MSI_PAYLOAD, MSI_PRODUCT_CODE};
|
||||
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 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)?;
|
||||
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", MSI_PRODUCT_CODE),
|
||||
(
|
||||
"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"
|
||||
);
|
||||
file.check()?;
|
||||
Ok(())
|
||||
}
|
||||
fn property(name: &str) -> Result<Option<String>> {
|
||||
let mut value = [0u16; 256];
|
||||
let mut len = 255;
|
||||
let code = unsafe {
|
||||
MsiGetProductInfoExW(
|
||||
wide(MSI_PRODUCT_CODE).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])?))
|
||||
}
|
||||
pub fn snapshot() -> Result<Snapshot> {
|
||||
let product_state = property("State")?;
|
||||
let product_version = if product_state.as_deref() == Some("5") {
|
||||
property("VersionString")?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
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_state,
|
||||
product_version,
|
||||
payload_sha256,
|
||||
payload_bytes,
|
||||
})
|
||||
}
|
||||
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) -> Result<Self> {
|
||||
validate(r, allowed_recipe_sha256)?;
|
||||
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)?;
|
||||
let system_root = system_root()?;
|
||||
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
|
||||
let before = snapshot()?;
|
||||
ensure!(
|
||||
before.absent() || before.desired(r),
|
||||
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
|
||||
);
|
||||
Ok(Self {
|
||||
recipe: r.clone(),
|
||||
archive,
|
||||
msiexec,
|
||||
_roots: roots,
|
||||
before,
|
||||
system_root,
|
||||
})
|
||||
}
|
||||
/// Called only after durable original-grant consumption. No change of
|
||||
/// config, privilege, policy, clock, reboot or foreign process occurs.
|
||||
pub fn start(
|
||||
mut self,
|
||||
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"
|
||||
);
|
||||
inspect_archive(&mut self.archive, &self.recipe)?;
|
||||
self.msiexec.check()?;
|
||||
let before = snapshot()?;
|
||||
ensure!(before == self.before, "MSI_BASELINE_CHANGED");
|
||||
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.absent(), "MSI_INSTALL_BASELINE_CONFLICT");
|
||||
use std::os::windows::process::CommandExt;
|
||||
check_effect_fence()?;
|
||||
ensure!(
|
||||
!cancelled.load(Ordering::SeqCst),
|
||||
"MSI_CANCELLED_BEFORE_START"
|
||||
);
|
||||
let began = Instant::now();
|
||||
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 {
|
||||
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)
|
||||
&& self.began.elapsed() < self.timeout
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut after = None;
|
||||
let (state, error, reboot, initiated) = if let Some(code) = code {
|
||||
after = snapshot().ok();
|
||||
if after.is_none() && matches!(code, 0 | 3010) {
|
||||
(
|
||||
"unknown",
|
||||
"MSI_POSTCONDITION_QUERY_FAILED",
|
||||
Some(code == 3010),
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
classification(
|
||||
code,
|
||||
after
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.desired(&self.prepared.recipe)),
|
||||
)
|
||||
}
|
||||
} 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};
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[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,
|
||||
};
|
||||
assert!(!advertised.absent());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user