2164 lines
89 KiB
Rust
2164 lines
89 KiB
Rust
//! SYSTEM service with an independent signed-sync gate and durable ledger.
|
|
//! Versioned policy independently admits fixed SCM/MSI actions or the explicit
|
|
//! full_maintenance_v1 SYSTEM script profile; none inherit another's authority.
|
|
//!
|
|
//! Bootstrap contract (not performed by this module): install exactly
|
|
//! `RmmDiscoverySystemHelper` as an OWN_PROCESS LocalSystem service with its
|
|
//! unrestricted service SID, image `"...\\rmm-helper-windows.exe" --service`.
|
|
//! Both peers keep their fixed names and binary hashes in `helper.json`.
|
|
//! The public root/settings are owned by SYSTEM or Administrators, grant only
|
|
//! those principals write access, and permit agent/helper service SIDs read.
|
|
//! `state` MUST have a separately protected SYSTEM/Administrators/helper-SID-only
|
|
//! ACL: no inherited agent reader. Files inherit that private ACL. This service
|
|
//! never installs itself, repairs ACLs, changes its account, resets a ledger, or
|
|
//! starts a fixture at bootstrap. `enable_effects=false`, `allow_reboot=false`
|
|
//! is the intended initial profile; clock qualification remains a separate gate.
|
|
//! A fixture is exactly OWN_PROCESS/LocalService with an unrestricted service
|
|
//! SID and a quoted argument-free pinned EXE. Dependencies/load-order groups
|
|
//! must be empty; recovery is empty/SC_ACTION_NONE with no command/reboot text.
|
|
//! These are read-only admission checks, never implicit configuration repairs.
|
|
use crate::{
|
|
helper_ipc::{self as ipc, Call, Operation, PeerPin, Pin, PinnedFile, Reply, ReplyBody},
|
|
signed_clock::{BoundClock, RuntimeClock},
|
|
};
|
|
use anyhow::{Context, Result, ensure};
|
|
use fs2::FileExt;
|
|
use rmm_agent_core::{
|
|
auth::{Binding, HelperIdentity, Outcome, Request},
|
|
crypto::DalekVerifier,
|
|
helper_reconcile::{
|
|
BootSource, ExecutorLedgerGuard, HelperSync, NoDispatchObservation, NoStartAnchor,
|
|
NoStartGuard,
|
|
},
|
|
ledger,
|
|
reconcile::SyncClock as _,
|
|
};
|
|
use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, hash};
|
|
use rusqlite::{Connection, OptionalExtension};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
fs::OpenOptions,
|
|
mem::{size_of, zeroed},
|
|
path::{Path, PathBuf},
|
|
ptr,
|
|
sync::{
|
|
OnceLock,
|
|
atomic::{AtomicBool, AtomicUsize, Ordering},
|
|
},
|
|
time::{Duration, Instant},
|
|
};
|
|
use uuid::Uuid;
|
|
use windows_sys::Win32::{Foundation::*, System::Services::*};
|
|
|
|
pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\helper.json";
|
|
pub const STATE_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\state";
|
|
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct ServiceRule {
|
|
pub name: String,
|
|
pub binary: PathBuf,
|
|
pub binary_sha256: String,
|
|
}
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Settings {
|
|
pub schema_version: u32,
|
|
pub binding: Binding,
|
|
pub agent: PeerPin,
|
|
pub helper: PeerPin,
|
|
pub allowed_services: Vec<ServiceRule>,
|
|
pub max_runtime_seconds: u32,
|
|
pub enable_effects: bool,
|
|
pub allow_reboot: bool,
|
|
#[serde(
|
|
default,
|
|
skip_serializing_if = "Option::is_none",
|
|
deserialize_with = "strict_recipe_hashes"
|
|
)]
|
|
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
|
|
#[serde(
|
|
default,
|
|
skip_serializing_if = "Option::is_none",
|
|
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
|
)]
|
|
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub windows_update_max_runtime_seconds: Option<u32>,
|
|
}
|
|
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
|
d: D,
|
|
) -> std::result::Result<Option<Vec<String>>, D::Error> {
|
|
Vec::<String>::deserialize(d).map(Some)
|
|
}
|
|
impl Settings {
|
|
fn permits_msi(&self, job: &JobPayload) -> bool {
|
|
self.schema_version >= 2
|
|
&& job.execution_identity == "system"
|
|
&& job.action.validate()
|
|
&& job
|
|
.action
|
|
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
|
&& job.max_runtime_seconds <= self.max_runtime_seconds
|
|
&& job.action.windows_msi().is_some_and(|m| {
|
|
self.allowed_msi_recipe_sha256
|
|
.as_ref()
|
|
.is_some_and(|h| h.contains(&m.recipe_sha256))
|
|
})
|
|
}
|
|
pub(crate) fn windows_update_only(&self) -> bool {
|
|
self.schema_version >= 3 && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
|
|
&& self.allowed_script_profiles.is_none() && self.allowed_services.is_empty()
|
|
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30
|
|
}
|
|
fn permits_script(&self, job: &JobPayload) -> bool {
|
|
self.schema_version >= 3
|
|
&& job.execution_identity == "system"
|
|
&& job.action.full_maintenance()
|
|
&& job.action.valid_execution_identity("system")
|
|
&& job.action.validate()
|
|
&& job
|
|
.action
|
|
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
|
&& job.max_runtime_seconds <= job.action.windows_system_runtime_limit(self.max_runtime_seconds, self.windows_update_max_runtime_seconds)
|
|
&& (self.allowed_script_profiles.as_deref()
|
|
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
|
|| (self.windows_update_max_runtime_seconds.is_some() && job.action.windows_update_or_identity_probe()))
|
|
}
|
|
fn permits_reboot(&self, job: &JobPayload) -> bool {
|
|
self.schema_version == 4
|
|
&& self.allow_reboot
|
|
&& rmm_domain::windows_reboot::supported(job)
|
|
&& job.max_runtime_seconds <= self.max_runtime_seconds
|
|
}
|
|
pub fn validate(&self) -> Result<()> {
|
|
ensure!(
|
|
matches!(self.schema_version, 1..=4)
|
|
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
|
|
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
|
|
&& self
|
|
.allowed_msi_recipe_sha256
|
|
.as_ref()
|
|
.is_none_or(|hashes| {
|
|
hashes.len() <= 2
|
|
&& hashes.iter().all(|h| ipc::digest(h))
|
|
&& hashes
|
|
.iter()
|
|
.collect::<std::collections::BTreeSet<_>>()
|
|
.len()
|
|
== hashes.len()
|
|
})
|
|
&& self.allowed_script_profiles.as_deref().is_none_or(
|
|
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
|
|
)
|
|
&& (self.schema_version == 4 || !self.allow_reboot)
|
|
&& (self.schema_version >= 3 || self.windows_update_max_runtime_seconds.is_none())
|
|
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
|
|
&& (1..=120).contains(&self.max_runtime_seconds)
|
|
&& self.allowed_services.len() <= 16,
|
|
"SYSTEM_POLICY_PROFILE"
|
|
);
|
|
self.agent.validate(false)?;
|
|
self.helper.validate(true)?;
|
|
ensure!(
|
|
!self.binding.tenant_id.is_nil()
|
|
&& !self.binding.agent_id.is_nil()
|
|
&& !self.binding.asset_id.is_nil()
|
|
&& self.binding.enrollment_generation > 0
|
|
&& self.binding.assignment_version > 0,
|
|
"SYSTEM_POLICY_BINDING"
|
|
);
|
|
use rmm_agent_core::crypto::Ed25519Verifier;
|
|
let raw = decode_key(&self.binding.public_key_hex)?;
|
|
ensure!(DalekVerifier.validate_key(&raw)?, "SYSTEM_SIGNING_KEY");
|
|
let mut names = std::collections::BTreeSet::new();
|
|
for rule in &self.allowed_services {
|
|
ensure!(
|
|
rule.name.starts_with("RmmDiscoveryFixture")
|
|
&& rule.name.len() <= 128
|
|
&& rule
|
|
.name
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
|
&& names.insert(rule.name.to_ascii_lowercase()),
|
|
"SYSTEM_SERVICE_ALLOWLIST"
|
|
);
|
|
ensure!(
|
|
!rule.name.eq_ignore_ascii_case(crate::SERVICE_NAME)
|
|
&& !rule.name.eq_ignore_ascii_case(ipc::HELPER_SERVICE),
|
|
"SYSTEM_SELF_CONTROL_DENIED"
|
|
);
|
|
ensure!(
|
|
rule.binary.parent() == Some(Path::new(r"C:\Program Files\RustDiscoveryFixtures"))
|
|
&& rule
|
|
.binary
|
|
.extension()
|
|
.is_some_and(|x| x.eq_ignore_ascii_case("exe"))
|
|
&& rule.binary.file_name().is_some_and(|n| n
|
|
.to_str()
|
|
.is_some_and(|n| n.len() <= 200
|
|
&& n.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))))
|
|
&& ipc::digest(&rule.binary_sha256),
|
|
"SYSTEM_FIXTURE_IMAGE"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn policy_sha256(&self) -> Result<String> {
|
|
Ok(hash(&serde_json::to_vec(self)?))
|
|
}
|
|
pub fn pin(&self) -> Result<Pin> {
|
|
self.validate()?;
|
|
Ok(Pin {
|
|
schema_version: 1,
|
|
binding: self.binding.clone(),
|
|
policy_sha256: self.policy_sha256()?,
|
|
agent: self.agent.clone(),
|
|
helper: self.helper.clone(),
|
|
})
|
|
}
|
|
}
|
|
fn decode_key(s: &str) -> Result<Vec<u8>> {
|
|
ensure!(
|
|
s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()),
|
|
"SYSTEM_KEY_SIZE"
|
|
);
|
|
(0..32)
|
|
.map(|i| Ok(u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)?))
|
|
.collect()
|
|
}
|
|
pub fn read_settings() -> Result<(Settings, Vec<PinnedFile>)> {
|
|
let agent = ipc::service_sid(crate::SERVICE_NAME)?;
|
|
let helper = ipc::service_sid(ipc::HELPER_SERVICE)?;
|
|
let readers = vec![agent, helper];
|
|
// A rename into PUBLIC_ROOT opens the directory with FILE_ADD_FILE.
|
|
// The handle stays read-only and denies deletion of the pinned directory.
|
|
let root = PinnedFile::open_read_shared(Path::new(PUBLIC_ROOT), true, &readers, &[])?;
|
|
let mut file = PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
|
ensure!(file.file.metadata()?.len() <= 32768, "SYSTEM_CONFIG_SIZE");
|
|
use std::io::Read;
|
|
let mut bytes = Vec::new();
|
|
file.file.read_to_end(&mut bytes)?;
|
|
let settings: Settings = serde_json::from_slice(&bytes)?;
|
|
settings.validate()?;
|
|
Ok((settings, vec![root, file]))
|
|
}
|
|
pub struct WindowsBoot(Uuid);
|
|
impl BootSource for WindowsBoot {
|
|
fn current_boot(&self) -> Result<Uuid> {
|
|
Ok(self.0)
|
|
}
|
|
}
|
|
impl WindowsBoot {
|
|
pub fn capture() -> Result<Self> {
|
|
// The exact existing fixed read-only CIM getter, independently called here.
|
|
// No caller values, execution-policy flag, or supplied command are accepted.
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()?;
|
|
let id = rt.block_on(crate::native::boot_id())?;
|
|
let id = Uuid::parse_str(&id)?;
|
|
ensure!(!id.is_nil(), "SYSTEM_BOOT_ID");
|
|
Ok(Self(id))
|
|
}
|
|
}
|
|
pub struct LedgerGuard {
|
|
root: PinnedFile,
|
|
lock: PinnedFile,
|
|
ledger: PinnedFile,
|
|
}
|
|
impl LedgerGuard {
|
|
fn acquire(helper_sid: &str, binding: &Binding) -> Result<(Self, Connection)> {
|
|
let root = PinnedFile::open(Path::new(STATE_ROOT), true, &[], &[helper_sid.into()], true)?;
|
|
for name in ["executor.lock", "ledger.sqlite"] {
|
|
let path = Path::new(STATE_ROOT).join(name);
|
|
if !path.exists() {
|
|
let _ = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(&path)?;
|
|
}
|
|
}
|
|
let lock = PinnedFile::open(
|
|
&Path::new(STATE_ROOT).join("executor.lock"),
|
|
false,
|
|
&[],
|
|
&[helper_sid.into()],
|
|
true,
|
|
)?;
|
|
lock.file
|
|
.try_lock_exclusive()
|
|
.context("SYSTEM_EXECUTOR_BUSY")?;
|
|
let ledger = PinnedFile::open(
|
|
&Path::new(STATE_ROOT).join("ledger.sqlite"),
|
|
false,
|
|
&[],
|
|
&[helper_sid.into()],
|
|
true,
|
|
)?;
|
|
let db =
|
|
Connection::open_with_flags(&ledger.path, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE)?;
|
|
db.busy_timeout(Duration::from_millis(250))?;
|
|
ledger::initialize_ledger(&db)?;
|
|
db.execute_batch("CREATE TABLE IF NOT EXISTS windows_helper_files(id INTEGER PRIMARY KEY CHECK(id=1),ledger BLOB NOT NULL,executor_lock BLOB NOT NULL,binding_sha256 TEXT NOT NULL)")?;
|
|
let a = serde_json::to_vec(&ledger.identity)?;
|
|
let b = serde_json::to_vec(&lock.identity)?;
|
|
let binding_hash = ipc::binding_hash(binding)?;
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO windows_helper_files(id,ledger,executor_lock,binding_sha256) VALUES(1,?1,?2,?3)",
|
|
rusqlite::params![a, b, binding_hash],
|
|
)?;
|
|
let retained: (Vec<u8>, Vec<u8>, String) = 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!(
|
|
retained == (a, b, binding_hash),
|
|
"SYSTEM_LEDGER_OR_LOCK_REPLACED"
|
|
);
|
|
let guard = Self { root, lock, ledger };
|
|
guard.check(&db)?;
|
|
Ok((guard, db))
|
|
}
|
|
pub(crate) fn update_identity(
|
|
&self,
|
|
db: &Connection,
|
|
) -> Result<crate::update_state::LedgerIdentity> {
|
|
self.check(db)?;
|
|
Ok(crate::update_state::LedgerIdentity {
|
|
ledger: self.ledger.identity,
|
|
lock: self.lock.identity,
|
|
})
|
|
}
|
|
fn check_files(&self) -> Result<()> {
|
|
for file in [&self.root, &self.lock, &self.ledger] {
|
|
ensure!(
|
|
ipc::file_identity(&file.file)? == file.identity,
|
|
"SYSTEM_HELD_FILE_CHANGED"
|
|
);
|
|
let opened = PinnedFile::open(
|
|
&file.path,
|
|
file.path == Path::new(STATE_ROOT),
|
|
&[],
|
|
&[ipc::service_sid(ipc::HELPER_SERVICE)?],
|
|
true,
|
|
)?;
|
|
ensure!(
|
|
opened.identity == file.identity,
|
|
"SYSTEM_LEDGER_PATH_CHANGED"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
impl ExecutorLedgerGuard for LedgerGuard {
|
|
fn check(&self, db: &Connection) -> Result<()> {
|
|
self.check_files()?;
|
|
let path = db.path().context("SYSTEM_DB_PATH_MISSING")?;
|
|
let actual = PinnedFile::open(
|
|
Path::new(path),
|
|
false,
|
|
&[],
|
|
&[ipc::service_sid(ipc::HELPER_SERVICE)?],
|
|
true,
|
|
)?;
|
|
ensure!(actual.identity == self.ledger.identity, "SYSTEM_DB_FILE_ID");
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// All data other than the immutable intent reference comes from held local
|
|
/// handles. The IPC caller cannot manufacture a NoDispatchObservation.
|
|
struct DenialGuard<'a> {
|
|
ledger: &'a LedgerGuard,
|
|
pin: &'a Pin,
|
|
intent: Option<(Uuid, &'a str)>,
|
|
}
|
|
impl ExecutorLedgerGuard for DenialGuard<'_> {
|
|
fn check(&self, db: &Connection) -> Result<()> {
|
|
ipc::require_self(&self.pin.helper)?;
|
|
self.ledger.check(db)
|
|
}
|
|
}
|
|
impl NoStartGuard for DenialGuard<'_> {
|
|
fn live_instance_sha256(&self) -> Result<String> {
|
|
let pid = std::process::id();
|
|
let peer = ipc::PeerProof::for_service(&self.pin.helper, pid)?;
|
|
Ok(hash(&serde_json::to_vec(&(
|
|
peer.identity(),
|
|
self.ledger.ledger.identity,
|
|
self.ledger.lock.identity,
|
|
))?))
|
|
}
|
|
fn verify_no_dispatch(
|
|
&self,
|
|
original: &Request,
|
|
anchor: &NoStartAnchor,
|
|
) -> Result<NoDispatchObservation> {
|
|
let (id, digest) = self
|
|
.intent
|
|
.context("SYSTEM_NO_DISPATCH_REFERENCE_REQUIRED")?;
|
|
let mut store = crate::helper_runtime::intent::Store::open(false)?;
|
|
let (intent, _) = store.load(id)?;
|
|
ensure!(
|
|
intent.policy_sha256 == self.pin.policy_sha256
|
|
&& intent.helper_binary_sha256 == self.pin.helper.binary_sha256,
|
|
"SYSTEM_NO_DISPATCH_PIN_BINDING"
|
|
);
|
|
store.verify_no_dispatch(id, digest, original, anchor)
|
|
}
|
|
}
|
|
|
|
struct ServiceHandle(SC_HANDLE);
|
|
impl Drop for ServiceHandle {
|
|
fn drop(&mut self) {
|
|
unsafe {
|
|
CloseServiceHandle(self.0);
|
|
}
|
|
}
|
|
}
|
|
#[derive(Clone, Copy, Debug, Serialize)]
|
|
struct ServiceState {
|
|
state: u32,
|
|
pid: u32,
|
|
checkpoint: u32,
|
|
wait_hint_ms: u32,
|
|
win32_exit: u32,
|
|
service_exit: u32,
|
|
}
|
|
fn state(handle: SC_HANDLE) -> Result<ServiceState> {
|
|
let mut value: SERVICE_STATUS_PROCESS = unsafe { zeroed() };
|
|
let mut needed = 0;
|
|
ensure!(
|
|
unsafe {
|
|
QueryServiceStatusEx(
|
|
handle,
|
|
SC_STATUS_PROCESS_INFO,
|
|
(&mut value as *mut SERVICE_STATUS_PROCESS).cast(),
|
|
size_of::<SERVICE_STATUS_PROCESS>() as u32,
|
|
&mut needed,
|
|
)
|
|
} != 0,
|
|
"SYSTEM_SERVICE_STATUS"
|
|
);
|
|
Ok(ServiceState {
|
|
state: value.dwCurrentState,
|
|
pid: value.dwProcessId,
|
|
checkpoint: value.dwCheckPoint,
|
|
wait_hint_ms: value.dwWaitHint,
|
|
win32_exit: value.dwWin32ExitCode,
|
|
service_exit: value.dwServiceSpecificExitCode,
|
|
})
|
|
}
|
|
fn desired_state(value: &str) -> Result<u32> {
|
|
match value {
|
|
"running" => Ok(SERVICE_RUNNING),
|
|
"stopped" => Ok(SERVICE_STOPPED),
|
|
_ => anyhow::bail!("SYSTEM_SERVICE_STATE_UNAVAILABLE"),
|
|
}
|
|
}
|
|
fn check_runtime(deadline: Instant) -> Result<()> {
|
|
ensure!(Instant::now() < deadline, "SYSTEM_SCM_RUNTIME_EXCEEDED");
|
|
Ok(())
|
|
}
|
|
#[derive(Clone, Debug)]
|
|
struct ServiceConfig {
|
|
service_type: u32,
|
|
binary: String,
|
|
account: String,
|
|
dependencies_empty: bool,
|
|
load_group_empty: bool,
|
|
recovery: RecoveryConfig,
|
|
sid_type: u32,
|
|
}
|
|
#[derive(Clone, Debug)]
|
|
struct RecoveryConfig {
|
|
actions: Vec<SC_ACTION_TYPE>,
|
|
command_empty: bool,
|
|
reboot_text_empty: bool,
|
|
}
|
|
impl RecoveryConfig {
|
|
fn validate(&self) -> Result<()> {
|
|
ensure!(
|
|
self.command_empty
|
|
&& self.reboot_text_empty
|
|
&& self.actions.iter().all(|kind| *kind == SC_ACTION_NONE),
|
|
"SYSTEM_UNAPPROVED_SERVICE_RECOVERY"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
impl ServiceConfig {
|
|
fn validate(&self, rule: &ServiceRule) -> Result<()> {
|
|
ensure!(
|
|
self.service_type == SERVICE_WIN32_OWN_PROCESS
|
|
&& self.binary == format!("\"{}\"", rule.binary.display())
|
|
&& matches!(
|
|
self.account.as_str(),
|
|
"NT AUTHORITY\\LocalService" | "NT AUTHORITY\\Local Service"
|
|
),
|
|
"SYSTEM_FIXTURE_SCM_BINDING"
|
|
);
|
|
// StartService may implicitly start dependencies/groups. A fixed-fixture
|
|
// grant authorizes exactly this service, so neither is admitted.
|
|
ensure!(
|
|
self.dependencies_empty && self.load_group_empty,
|
|
"SYSTEM_UNAPPROVED_SERVICE_DEPENDENCY"
|
|
);
|
|
self.recovery.validate()?;
|
|
ensure!(
|
|
self.sid_type == SERVICE_SID_TYPE_UNRESTRICTED,
|
|
"SYSTEM_FIXTURE_SERVICE_SID_DISABLED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
fn query_service_config2(handle: SC_HANDLE, level: u32) -> Result<Vec<usize>> {
|
|
let mut needed = 0;
|
|
unsafe {
|
|
QueryServiceConfig2W(handle, level, ptr::null_mut(), 0, &mut needed);
|
|
}
|
|
ensure!((1..=32768).contains(&needed), "SYSTEM_SERVICE_CONFIG2_SIZE");
|
|
let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
|
ensure!(
|
|
unsafe {
|
|
QueryServiceConfig2W(
|
|
handle,
|
|
level,
|
|
bytes.as_mut_ptr().cast(),
|
|
needed,
|
|
&mut needed,
|
|
)
|
|
} != 0,
|
|
"SYSTEM_SERVICE_CONFIG2"
|
|
);
|
|
Ok(bytes)
|
|
}
|
|
fn buffer_empty_string(bytes: &[usize], text: *const u16) -> Result<bool> {
|
|
if text.is_null() {
|
|
return Ok(true);
|
|
}
|
|
let base = bytes.as_ptr() as usize;
|
|
let address = text as usize;
|
|
let size = std::mem::size_of_val(bytes);
|
|
ensure!(
|
|
address >= base && address - base <= size.saturating_sub(2) && address.is_multiple_of(2),
|
|
"SYSTEM_CONFIG2_STRING_POINTER"
|
|
);
|
|
Ok(unsafe { *text } == 0)
|
|
}
|
|
fn recovery_config(handle: SC_HANDLE) -> Result<RecoveryConfig> {
|
|
let bytes = query_service_config2(handle, SERVICE_CONFIG_FAILURE_ACTIONS)?;
|
|
ensure!(
|
|
std::mem::size_of_val(bytes.as_slice()) >= size_of::<SERVICE_FAILURE_ACTIONSW>(),
|
|
"SYSTEM_RECOVERY_STRUCT_SIZE"
|
|
);
|
|
let value = unsafe { &*bytes.as_ptr().cast::<SERVICE_FAILURE_ACTIONSW>() };
|
|
ensure!(value.cActions <= 128, "SYSTEM_RECOVERY_ACTION_COUNT");
|
|
let mut actions = Vec::new();
|
|
if value.cActions > 0 {
|
|
let base = bytes.as_ptr() as usize;
|
|
let address = value.lpsaActions as usize;
|
|
let length = value.cActions as usize * size_of::<SC_ACTION>();
|
|
let size = std::mem::size_of_val(bytes.as_slice());
|
|
ensure!(
|
|
!value.lpsaActions.is_null()
|
|
&& address >= base
|
|
&& length <= size
|
|
&& address - base <= size - length
|
|
&& address.is_multiple_of(std::mem::align_of::<SC_ACTION>()),
|
|
"SYSTEM_RECOVERY_ACTION_POINTER"
|
|
);
|
|
actions.extend(
|
|
unsafe { std::slice::from_raw_parts(value.lpsaActions, value.cActions as usize) }
|
|
.iter()
|
|
.map(|a| a.Type),
|
|
);
|
|
}
|
|
Ok(RecoveryConfig {
|
|
actions,
|
|
command_empty: buffer_empty_string(&bytes, value.lpCommand)?,
|
|
reboot_text_empty: buffer_empty_string(&bytes, value.lpRebootMsg)?,
|
|
})
|
|
}
|
|
fn query_service_config(handle: SC_HANDLE) -> Result<ServiceConfig> {
|
|
let mut needed = 0;
|
|
unsafe {
|
|
QueryServiceConfigW(handle, ptr::null_mut(), 0, &mut needed);
|
|
}
|
|
ensure!((1..=32768).contains(&needed), "SYSTEM_SERVICE_CONFIG_SIZE");
|
|
let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
|
ensure!(
|
|
unsafe { QueryServiceConfigW(handle, bytes.as_mut_ptr().cast(), needed, &mut needed) } != 0,
|
|
"SYSTEM_SERVICE_CONFIG"
|
|
);
|
|
let value = unsafe { &*bytes.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
|
// Microsoft defines NULL or first UTF16 NUL as empty for both fields.
|
|
// Do not enumerate or adopt any dependency supplied by configuration.
|
|
let sid_info = query_service_config2(handle, SERVICE_CONFIG_SERVICE_SID_INFO)?;
|
|
ensure!(
|
|
std::mem::size_of_val(sid_info.as_slice()) >= size_of::<SERVICE_SID_INFO>(),
|
|
"SYSTEM_SID_CONFIG_SIZE"
|
|
);
|
|
Ok(ServiceConfig {
|
|
service_type: value.dwServiceType,
|
|
binary: unsafe { ipc::utf16_pointer(value.lpBinaryPathName) }?,
|
|
account: unsafe { ipc::utf16_pointer(value.lpServiceStartName) }?,
|
|
dependencies_empty: value.lpDependencies.is_null() || unsafe { *value.lpDependencies } == 0,
|
|
load_group_empty: value.lpLoadOrderGroup.is_null()
|
|
|| unsafe { *value.lpLoadOrderGroup } == 0,
|
|
recovery: recovery_config(handle)?,
|
|
sid_type: unsafe { (*sid_info.as_ptr().cast::<SERVICE_SID_INFO>()).dwServiceSidType },
|
|
})
|
|
}
|
|
struct PreparedService {
|
|
handle: ServiceHandle,
|
|
_manager: ServiceHandle,
|
|
image: PinnedFile,
|
|
root: PinnedFile,
|
|
rule: ServiceRule,
|
|
pin: PeerPin,
|
|
running: Option<ipc::PeerProof>,
|
|
wanted: u32,
|
|
initial: ServiceState,
|
|
}
|
|
impl PreparedService {
|
|
fn prepare(settings: &Settings, job: &JobPayload) -> Result<Self> {
|
|
ensure!(
|
|
job.execution_identity == "system"
|
|
&& job.max_runtime_seconds <= settings.max_runtime_seconds,
|
|
"SYSTEM_IDENTITY_OR_RUNTIME"
|
|
);
|
|
let Action::SetServiceState {
|
|
unit,
|
|
state: desired,
|
|
} = &job.action
|
|
else {
|
|
anyhow::bail!("SYSTEM_TYPED_SERVICE_ONLY");
|
|
};
|
|
let wanted = desired_state(desired)?;
|
|
let rule = settings
|
|
.allowed_services
|
|
.iter()
|
|
.find(|r| r.name == *unit)
|
|
.context("SYSTEM_SERVICE_DENIED")?
|
|
.clone();
|
|
let sid = ipc::service_sid(&rule.name)?;
|
|
let readers = [
|
|
settings.agent.service_sid.clone(),
|
|
settings.helper.service_sid.clone(),
|
|
sid.clone(),
|
|
];
|
|
let root = PinnedFile::open(
|
|
Path::new(r"C:\Program Files\RustDiscoveryFixtures"),
|
|
true,
|
|
&readers,
|
|
&[],
|
|
false,
|
|
)?;
|
|
let mut image = PinnedFile::open(&rule.binary, false, &readers, &[], false)?;
|
|
ensure!(
|
|
image.sha256()? == rule.binary_sha256,
|
|
"SYSTEM_SERVICE_IMAGE_HASH"
|
|
);
|
|
let manager =
|
|
ServiceHandle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
|
ensure!(!manager.0.is_null(), "SYSTEM_SERVICE_MANAGER");
|
|
let handle = ServiceHandle(unsafe {
|
|
OpenServiceW(
|
|
manager.0,
|
|
ipc::wide(unit).as_ptr(),
|
|
SERVICE_QUERY_CONFIG
|
|
| SERVICE_QUERY_STATUS
|
|
| if wanted == SERVICE_RUNNING {
|
|
SERVICE_START
|
|
} else {
|
|
SERVICE_STOP
|
|
},
|
|
)
|
|
});
|
|
ensure!(!handle.0.is_null(), "SYSTEM_SERVICE_OPEN");
|
|
query_service_config(handle.0)?.validate(&rule)?;
|
|
let initial = state(handle.0)?;
|
|
ensure!(
|
|
matches!(initial.state, SERVICE_RUNNING | SERVICE_STOPPED),
|
|
"SYSTEM_SERVICE_BUSY"
|
|
);
|
|
let pin = PeerPin {
|
|
service_name: rule.name.clone(),
|
|
service_sid: sid,
|
|
user_sid: "S-1-5-19".into(),
|
|
binary: rule.binary.clone(),
|
|
binary_sha256: rule.binary_sha256.clone(),
|
|
};
|
|
let running = if initial.state == SERVICE_RUNNING {
|
|
Some(ipc::PeerProof::for_service(&pin, initial.pid)?)
|
|
} else {
|
|
None
|
|
};
|
|
Ok(Self {
|
|
handle,
|
|
_manager: manager,
|
|
image,
|
|
root,
|
|
rule,
|
|
pin,
|
|
running,
|
|
wanted,
|
|
initial,
|
|
})
|
|
}
|
|
fn recheck(&mut self) -> Result<ServiceState> {
|
|
self.image.check()?;
|
|
self.root.check()?;
|
|
query_service_config(self.handle.0)?.validate(&self.rule)?;
|
|
let before = state(self.handle.0)?;
|
|
ensure!(
|
|
before.state == self.initial.state && before.pid == self.initial.pid,
|
|
"SYSTEM_SERVICE_CHANGED_BEFORE_EFFECT"
|
|
);
|
|
if let Some(process) = &mut self.running {
|
|
process.check()?;
|
|
}
|
|
Ok(before)
|
|
}
|
|
fn execute(&mut self, timeout: Duration, mut authorize: impl FnMut() -> Result<()>) -> Outcome {
|
|
let result = (|| -> Result<Outcome> {
|
|
let deadline = Instant::now() + timeout;
|
|
let before = match self.recheck() {
|
|
Ok(value) => value,
|
|
Err(error) => {
|
|
return Ok(Outcome {
|
|
state: "failed".into(),
|
|
evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}),
|
|
..Outcome::unknown(&safe_error(&error))
|
|
});
|
|
}
|
|
};
|
|
let noop = before.state == self.wanted;
|
|
// This callback performs the final BOTH-edge clock/permit check,
|
|
// after all potentially slow configuration/process preflights.
|
|
if let Err(error) = authorize() {
|
|
return Ok(Outcome {
|
|
state: "failed".into(),
|
|
evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}),
|
|
..Outcome::unknown(&safe_error(&error))
|
|
});
|
|
}
|
|
if let Err(error) = check_runtime(deadline) {
|
|
return Ok(Outcome {
|
|
state: "failed".into(),
|
|
evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}),
|
|
..Outcome::unknown(&safe_error(&error))
|
|
});
|
|
}
|
|
if !noop {
|
|
// SCM's synchronous RPC can block (documented up to30s), and
|
|
// cannot be safely cancelled here. Exceedance remains Unknown,
|
|
// never success or a claim that effects stopped at the limit.
|
|
let ok = unsafe {
|
|
if self.wanted == SERVICE_RUNNING {
|
|
StartServiceW(self.handle.0, 0, ptr::null())
|
|
} else {
|
|
let mut ignored: SERVICE_STATUS = zeroed();
|
|
ControlService(self.handle.0, SERVICE_CONTROL_STOP, &mut ignored)
|
|
}
|
|
};
|
|
let native_error = if ok == 0 {
|
|
Some(unsafe { GetLastError() })
|
|
} else {
|
|
None
|
|
};
|
|
check_runtime(deadline)?;
|
|
if ok == 0 {
|
|
return Ok(Outcome {
|
|
evidence: serde_json::json!({"postconditions_passed":false,"native_error":native_error,"initial":before}),
|
|
..Outcome::unknown("SYSTEM_SCM_EFFECT_UNCONFIRMED")
|
|
});
|
|
}
|
|
}
|
|
let mut final_state = state(self.handle.0)?;
|
|
while final_state.state != self.wanted && Instant::now() < deadline {
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
final_state = state(self.handle.0)?;
|
|
}
|
|
if final_state.state != self.wanted {
|
|
return Ok(Outcome {
|
|
evidence: serde_json::json!({"postconditions_passed":false,"initial":before,"last_status":final_state}),
|
|
..Outcome::unknown("SYSTEM_SERVICE_POSTCONDITION_TIMEOUT")
|
|
});
|
|
}
|
|
self.image.check()?;
|
|
query_service_config(self.handle.0)?.validate(&self.rule)?;
|
|
let process_identity = if self.wanted == SERVICE_RUNNING {
|
|
if self.running.is_none() {
|
|
self.running = Some(ipc::PeerProof::for_service(&self.pin, final_state.pid)?);
|
|
}
|
|
let process = self.running.as_mut().unwrap();
|
|
process.check()?;
|
|
Some(process.identity().clone())
|
|
} else {
|
|
if let Some(process) = &self.running {
|
|
while !process.exited()? && Instant::now() < deadline {
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
ensure!(process.exited()?, "SYSTEM_STOPPED_PROCESS_STILL_ALIVE");
|
|
}
|
|
None
|
|
};
|
|
// Re-read after live process proof; a stale SCM config/state is
|
|
// never turned into success for an old SYSTEM/other image process.
|
|
query_service_config(self.handle.0)?.validate(&self.rule)?;
|
|
let confirmed = state(self.handle.0)?;
|
|
ensure!(
|
|
confirmed.state == self.wanted
|
|
&& (self.wanted != SERVICE_RUNNING || confirmed.pid == final_state.pid),
|
|
"SYSTEM_SERVICE_CHANGED_DURING_POSTCONDITION"
|
|
);
|
|
check_runtime(deadline)?;
|
|
Ok(Outcome {
|
|
state: "succeeded".into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: Some(0),
|
|
output_truncated: false,
|
|
reboot_required: false,
|
|
error_code: String::new(),
|
|
evidence: serde_json::json!({"postconditions_passed":true,"provider":"windows.scm/1","service":self.rule.name,"requested_state":self.wanted,"initial":before,"final_status":confirmed,"noop":noop,"fixture_sha256":self.rule.binary_sha256,"fixture_file_id":self.image.identity,"running_process":process_identity,"captured_process_exited":self.wanted==SERVICE_STOPPED&&self.running.is_some()}),
|
|
})
|
|
})();
|
|
result.unwrap_or_else(|error| Outcome::unknown(&safe_error(&error)))
|
|
}
|
|
}
|
|
|
|
fn verified_window(
|
|
binding: &Binding,
|
|
request: &Request,
|
|
clock: &impl rmm_agent_core::reconcile::SyncClock,
|
|
) -> Result<(
|
|
JobPayload,
|
|
ExecutionPermitPayload,
|
|
chrono::DateTime<chrono::Utc>,
|
|
)> {
|
|
let now = clock.now()?;
|
|
let lower = now
|
|
.checked_sub_signed(chrono::Duration::seconds(2))
|
|
.context("SYSTEM_CLOCK_RANGE")?;
|
|
let upper = now
|
|
.checked_add_signed(chrono::Duration::seconds(2))
|
|
.context("SYSTEM_CLOCK_RANGE")?;
|
|
let (job, permit) = binding.verify_with(request, lower, &DalekVerifier)?;
|
|
binding.verify_with(request, upper, &DalekVerifier)?;
|
|
Ok((job, permit, now))
|
|
}
|
|
|
|
struct UnsettledMsi {
|
|
grant: Uuid,
|
|
request_sha256: String,
|
|
installer: Box<crate::package::Installer>,
|
|
}
|
|
/// Internal native-control adapter. No caller can construct readiness, choose
|
|
/// another database, or replace the real held executor through the wire.
|
|
pub(crate) struct UpdateContext<'a> {
|
|
pub db:&'a mut Connection,
|
|
pub guard:&'a LedgerGuard,
|
|
pub binding:&'a Binding,
|
|
pub clock:&'a BoundClock,
|
|
pub pin:&'a Pin,
|
|
pub boot:&'a WindowsBoot,
|
|
pub sync:Option<&'a mut HelperSync<DalekVerifier>>,
|
|
}
|
|
pub struct SystemHelper {
|
|
settings: Settings,
|
|
pin: Pin,
|
|
files: Vec<PinnedFile>,
|
|
guard: LedgerGuard,
|
|
db: Connection,
|
|
clock: BoundClock,
|
|
boot: WindowsBoot,
|
|
sync: Option<HelperSync<DalekVerifier>>,
|
|
last_diagnostic: Option<Instant>,
|
|
last_apply_diagnostic: Option<Instant>,
|
|
unsettled_msi: Option<UnsettledMsi>,
|
|
pending_update_activation: Option<crate::update_admission::Activation>,
|
|
}
|
|
impl SystemHelper {
|
|
pub fn open() -> Result<Self> {
|
|
let (settings, files) = read_settings()?;
|
|
ipc::require_self(&settings.helper)?;
|
|
let pin = settings.pin()?;
|
|
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
|
|
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
|
|
let clock = if settings.windows_update_only() {
|
|
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
|
|
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
|
|
let boot = WindowsBoot::capture()?;
|
|
let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock)
|
|
.ok()
|
|
.map(|s| s.with_helper_identity(HelperIdentity::System));
|
|
Ok(Self {
|
|
settings,
|
|
pin,
|
|
files,
|
|
guard,
|
|
db,
|
|
clock,
|
|
boot,
|
|
sync,
|
|
last_diagnostic: None,
|
|
last_apply_diagnostic: None,
|
|
unsettled_msi: None,
|
|
pending_update_activation: None,
|
|
})
|
|
}
|
|
pub(crate) fn update_context(&mut self)->UpdateContext<'_> {
|
|
UpdateContext{db:&mut self.db,guard:&self.guard,binding:&self.settings.binding,clock:&self.clock,
|
|
pin:&self.pin,boot:&self.boot,sync:self.sync.as_mut()}
|
|
}
|
|
pub fn pin(&self) -> &Pin {
|
|
&self.pin
|
|
}
|
|
/// One bounded private bootstrap diagnostic, never inventory or payload.
|
|
/// Diagnostic failure is intentionally ignored by the service loop; the
|
|
/// original security failure still closes Sync and disconnects the pipe.
|
|
fn record_pipe_error(&mut self, error: &anyhow::Error) -> Result<()> {
|
|
if self
|
|
.last_diagnostic
|
|
.is_some_and(|at| at.elapsed() < Duration::from_secs(30))
|
|
{
|
|
return Ok(());
|
|
}
|
|
self.last_diagnostic = Some(Instant::now());
|
|
self.recheck()?;
|
|
let path = Path::new(STATE_ROOT).join("pipe-last-error.json");
|
|
let pending = Path::new(STATE_ROOT).join(".pipe-last-error.pending");
|
|
let writers = vec![self.settings.helper.service_sid.clone()];
|
|
if path.try_exists()? {
|
|
let _old = PinnedFile::open(&path, false, &[], &writers, false)?;
|
|
}
|
|
let diagnostic = ipc::diagnostic(error);
|
|
let bytes = serde_json::to_vec(
|
|
&serde_json::json!({"pid":std::process::id(),"observed_at_utc":chrono::Utc::now(),"diagnostic":diagnostic}),
|
|
)?;
|
|
ensure!(bytes.len() <= 1024, "SYSTEM_DIAGNOSTIC_BOUND");
|
|
use std::io::Write;
|
|
let mut file = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(&pending)?;
|
|
let identity = ipc::file_identity(&file)?;
|
|
let result = (|| -> Result<()> {
|
|
{
|
|
let _check = PinnedFile::open_read_shared(&pending, false, &[], &writers)?;
|
|
}
|
|
file.write_all(&bytes)?;
|
|
file.sync_all()?;
|
|
Ok(())
|
|
})();
|
|
drop(file);
|
|
result?;
|
|
std::fs::rename(&pending, &path)?;
|
|
let saved = PinnedFile::open(&path, false, &[], &writers, false)?;
|
|
ensure!(
|
|
saved.identity == identity,
|
|
"SYSTEM_DIAGNOSTIC_FILE_REPLACED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn wait_apply_clock(&self,issued:chrono::DateTime<chrono::Utc>,until:chrono::DateTime<chrono::Utc>)->Result<()> {
|
|
crate::job_readiness::wait_for_helper_apply_clock(&self.clock,issued,until)
|
|
}
|
|
/// Passive, bounded static denial metadata only. Never feeds a gate.
|
|
fn record_apply_error(&mut self,error:&anyhow::Error)->Result<()> {
|
|
if self.last_apply_diagnostic.is_some_and(|at|at.elapsed()<Duration::from_secs(5)){return Ok(());}
|
|
self.last_apply_diagnostic=Some(Instant::now());self.recheck()?;
|
|
const CODES:&[&str]=&["SYSTEM_APPLY_CLOCK_WAIT_EXPIRED","SYSTEM_APPLY_ORIGINAL_DEADLINE_EXPIRED","SYNC_PROFILE_OR_CLOCK","FRESH_PROCESS_SNAPSHOT_REQUIRED","OLD_PROCESS_DECISION_OR_BOOT","ROOT_SNAPSHOT_REQUEST_MISMATCH","TIME_RUNTIME_NO_EVIDENCE","TIME_NATIVE_NO_EVIDENCE","TIME_STALE_RESPONSE","TIME_NATIVE_EVIDENCE_INVALIDATED","TIME_SOURCE_AGE_AT_CHECK","TIME_LOCAL_WALL_OUTSIDE_BOUND","TIME_NATIVE_CONFIG_CHANGED","TIME_RUNTIME_CONNECTION_CHANGED","TIME_RUNTIME_GENERATION"];
|
|
let code=error.chain().find_map(|e|CODES.iter().copied().find(|c|*c==e.to_string())).unwrap_or("SYSTEM_APPLY_VALIDATION_OR_STORAGE_FAILURE");
|
|
let path=Path::new(STATE_ROOT).join("apply-last-error.json");
|
|
let pending=Path::new(STATE_ROOT).join(".apply-last-error.pending");
|
|
let writers=[self.settings.helper.service_sid.clone()];
|
|
if path.try_exists()?{let _old=PinnedFile::open(&path,false,&[],&writers,false)?;}
|
|
let bytes=serde_json::to_vec(&serde_json::json!({"schema_version":1,"observed_at_utc":chrono::Utc::now(),"helper_pid":std::process::id(),"code":code,"ready":false,"diagnostic_only":true}))?;
|
|
ensure!(bytes.len()<=1024,"SYSTEM_APPLY_DIAGNOSTIC_LIMIT");
|
|
use std::io::Write;
|
|
let mut file=OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
|
let identity=ipc::file_identity(&file)?;
|
|
{let _check=PinnedFile::open_read_shared(&pending,false,&[],&writers)?;}
|
|
file.write_all(&bytes)?;file.sync_all()?;drop(file);
|
|
std::fs::rename(&pending,&path)?;
|
|
let checked=PinnedFile::open(&path,false,&[],&writers,false)?;
|
|
ensure!(checked.identity==identity,"SYSTEM_APPLY_DIAGNOSTIC_REPLACED");Ok(())
|
|
}
|
|
fn recheck(&mut self) -> Result<()> {
|
|
ipc::require_self(&self.settings.helper)?;
|
|
for file in &mut self.files {
|
|
file.check()?;
|
|
}
|
|
self.guard.check(&self.db)
|
|
}
|
|
fn sync(&mut self) -> Result<&mut HelperSync<DalekVerifier>> {
|
|
if self.sync.is_none() {
|
|
self.sync = Some(
|
|
HelperSync::with_verifier(
|
|
self.settings.binding.clone(),
|
|
DalekVerifier,
|
|
&self.clock,
|
|
)?
|
|
.with_helper_identity(HelperIdentity::System),
|
|
);
|
|
}
|
|
self.sync.as_mut().context("SYSTEM_SYNC_CLOSED")
|
|
}
|
|
pub fn handle(&mut self, call: &Call, peer: &mut ipc::PeerProof) -> Reply {
|
|
let result = (|| -> Result<ReplyBody> {
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
ensure!(
|
|
call.schema_version == 1
|
|
&& !call.challenge.is_nil()
|
|
&& ipc::binding_hash(&call.binding)?
|
|
== ipc::binding_hash(&self.settings.binding)?
|
|
&& call.policy_sha256 == self.pin.policy_sha256,
|
|
"SYSTEM_CALL_BINDING"
|
|
);
|
|
let response: Result<ReplyBody> = match &call.operation {
|
|
Operation::TimeBegin { .. }
|
|
| Operation::TimeComplete { .. }
|
|
| Operation::TimeClose { .. } => {
|
|
anyhow::bail!("SYSTEM_TIME_PIPE_REQUIRED")
|
|
}
|
|
Operation::UpdateObserve{request}=>{
|
|
Ok(ReplyBody::UpdateObservation{response:Box::new(crate::update_observer::collect(self.update_context(),request)?)})
|
|
}
|
|
Operation::UpdateHealth{request}=>{
|
|
ensure!(matches!(request.method,rmm_agent_core::update_handoff::NativeControlOperation::Health{..}),"UPDATE_AGENT_HEALTH_ONLY");
|
|
Ok(ReplyBody::UpdateHealth{reply:Box::new(crate::update_control::handle_agent_health(self.update_context(),peer,request)?)})
|
|
}
|
|
Operation::Probe {} => {
|
|
let ready = self.settings.enable_effects
|
|
&& self
|
|
.sync
|
|
.as_ref()
|
|
.and_then(|s| {
|
|
s.active_generation().map(|g| {
|
|
s.can_start(&self.db, &self.guard, g, &self.clock, &self.boot)
|
|
})
|
|
})
|
|
.unwrap_or(false);
|
|
Ok(ReplyBody::Probe {
|
|
update_observer_configured:Some(crate::update_admission::configured(&self.settings.binding)),
|
|
clock_qualified: self.clock.now().is_ok(),
|
|
ready,
|
|
ledger: self.guard.ledger.identity,
|
|
lock: self.guard.lock.identity,
|
|
reboot_privilege_available: if self.settings.schema_version == 4
|
|
&& self.settings.allow_reboot
|
|
{
|
|
Some(crate::reboot::privilege_available()?)
|
|
} else {
|
|
None
|
|
},
|
|
})
|
|
}
|
|
Operation::Snapshot { generation } => {
|
|
self.clock = self.clock.for_generation(*generation);
|
|
self.sync()?;
|
|
let snapshot = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
|
|
let budget=crate::update_native::Budget::new(&self.boot,self.boot.current_boot()?,Duration::from_secs(5))?;
|
|
let guard=crate::update_control::Guard::open(&self.db,&self.guard,&self.settings.binding,
|
|
&self.clock,&self.pin,&budget,grant)?;
|
|
self.sync.as_mut().unwrap().snapshot(&mut self.db,&guard,*generation,&self.clock,&self.boot)?
|
|
} else {
|
|
self.sync.as_mut().unwrap().snapshot(&mut self.db,&self.guard,*generation,&self.clock,&self.boot)?
|
|
};
|
|
Ok(ReplyBody::Snapshot { snapshot })
|
|
}
|
|
Operation::Apply {
|
|
response,
|
|
request_bytes,
|
|
} => {
|
|
let decision: rmm_domain::reconciliation::ReconcileDecisionPayload =
|
|
serde_json::from_slice(&response.decision_bytes)?;
|
|
self.clock
|
|
.require_generation(decision.connection_generation)?;
|
|
self.wait_apply_clock(decision.issued_at,decision.valid_until)?;
|
|
self.sync()?;
|
|
let value = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
|
|
let budget=crate::update_native::Budget::new(&self.boot,self.boot.current_boot()?,Duration::from_secs(5))?;
|
|
let guard=crate::update_control::Guard::open(&self.db,&self.guard,&self.settings.binding,
|
|
&self.clock,&self.pin,&budget,grant)?;
|
|
self.sync.as_mut().unwrap().apply(&mut self.db,&guard,response,request_bytes,&self.clock,&self.boot)?
|
|
} else {
|
|
self.sync.as_mut().unwrap().apply(&mut self.db,&self.guard,response,request_bytes,&self.clock,&self.boot)?
|
|
};
|
|
let no_start_anchor = if value.ready
|
|
&& (self.settings.enable_effects
|
|
|| crate::update_admission::configured(&self.settings.binding))
|
|
{
|
|
let guard = DenialGuard {
|
|
ledger: &self.guard,
|
|
pin: &self.pin,
|
|
intent: None,
|
|
};
|
|
let generation = self
|
|
.sync
|
|
.as_ref()
|
|
.unwrap()
|
|
.active_generation()
|
|
.context("SYSTEM_READY_GENERATION_REQUIRED")?;
|
|
Some(Box::new(self.sync.as_ref().unwrap().no_start_anchor(
|
|
&self.db,
|
|
&guard,
|
|
generation,
|
|
&self.clock,
|
|
&self.boot,
|
|
)?))
|
|
} else {
|
|
None
|
|
};
|
|
Ok(ReplyBody::Applied {
|
|
snapshot: value.snapshot,
|
|
unlocked_grants: value.unlocked_grants,
|
|
ready: value.ready && self.settings.enable_effects,
|
|
no_start_anchor,
|
|
})
|
|
}
|
|
Operation::Execute {
|
|
generation,
|
|
request,
|
|
} => {
|
|
let job = self.settings.binding.job(&request.job_bytes)?;
|
|
if matches!(job.action, Action::UpdateAgent { .. }) {
|
|
ensure!(
|
|
self.pending_update_activation.is_none(),
|
|
"UPDATE_ACTIVATION_PENDING"
|
|
);
|
|
self.clock.require_generation(*generation)?;
|
|
self.sync()?;
|
|
let prepared = crate::update_admission::Prepared::new(
|
|
&self.db,
|
|
crate::update_admission::Local {
|
|
binding: &self.settings.binding,
|
|
guard: &self.guard,
|
|
clock: &self.clock,
|
|
boot: &self.boot,
|
|
pin: &self.pin,
|
|
generation: *generation,
|
|
},
|
|
self.sync.as_ref().context("SYSTEM_SYNC_REQUIRED")?,
|
|
request,
|
|
)?;
|
|
peer.check()?;
|
|
let accepted = prepared.consume(
|
|
&mut self.db,
|
|
self.sync.as_mut().context("SYSTEM_SYNC_REQUIRED")?,
|
|
)?;
|
|
self.pending_update_activation = Some(prepared.into_activation());
|
|
Ok(ReplyBody::UpdateAccepted { accepted })
|
|
} else {
|
|
Ok(ReplyBody::Executed {
|
|
outcome: self.execute(*generation, request, peer)?,
|
|
})
|
|
}
|
|
}
|
|
Operation::Abandon {
|
|
anchor,
|
|
request,
|
|
intent_id,
|
|
intent_sha256,
|
|
} => {
|
|
ensure!(
|
|
!intent_id.is_nil() && ipc::digest(intent_sha256),
|
|
"SYSTEM_NO_DISPATCH_REFERENCE_REQUIRED"
|
|
);
|
|
let job = self.settings.binding.job(&request.job_bytes)?;
|
|
ensure!(
|
|
job.execution_identity == "system"
|
|
&& ((job.max_runtime_seconds <= self.settings.max_runtime_seconds
|
|
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|
|
|| self.settings.permits_msi(&job)
|
|
|| self.settings.permits_reboot(&job)))
|
|
|| self.settings.permits_script(&job)
|
|
|| crate::update_admission::permits_denial(
|
|
&self.settings.binding,
|
|
&job
|
|
)),
|
|
"SYSTEM_ABANDON_POLICY_DENIED"
|
|
);
|
|
self.sync()?;
|
|
let guard = DenialGuard {
|
|
ledger: &self.guard,
|
|
pin: &self.pin,
|
|
intent: Some((*intent_id, intent_sha256)),
|
|
};
|
|
Ok(ReplyBody::Abandoned {
|
|
outcome: self.sync.as_mut().unwrap().abandon_no_start(
|
|
&mut self.db,
|
|
&guard,
|
|
anchor,
|
|
request,
|
|
&self.clock,
|
|
&self.boot,
|
|
)?,
|
|
})
|
|
}
|
|
};
|
|
let response = response?;
|
|
peer.check()?;
|
|
Ok(response)
|
|
})();
|
|
let body = match result {
|
|
Ok(body) => body,
|
|
Err(e) => {
|
|
if matches!(call.operation,Operation::Apply{..}) {let _diagnostic=self.record_apply_error(&e);}
|
|
if let Some(sync) = &mut self.sync {
|
|
sync.close();
|
|
}
|
|
ReplyBody::Denied {
|
|
code: safe_error(&e),
|
|
}
|
|
}
|
|
};
|
|
Reply {
|
|
schema_version: 1,
|
|
challenge: call.challenge,
|
|
binding_sha256: ipc::binding_hash(&self.settings.binding).expect("validated binding"),
|
|
policy_sha256: self.pin.policy_sha256.clone(),
|
|
helper_binary_sha256: self.settings.helper.binary_sha256.clone(),
|
|
body,
|
|
}
|
|
}
|
|
fn execute(
|
|
&mut self,
|
|
generation: u64,
|
|
request: &Request,
|
|
peer: &mut ipc::PeerProof,
|
|
) -> Result<Outcome> {
|
|
self.clock.require_generation(generation)?;
|
|
// Historical signature validation can only return retained evidence. It
|
|
// never reopens a start window or authorizes an effect after expiry.
|
|
let parsed: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
|
let (job, permit) =
|
|
self.settings
|
|
.binding
|
|
.verify_with(request, parsed.not_before, &DalekVerifier)?;
|
|
ensure!(
|
|
job.execution_identity == "system",
|
|
"SYSTEM_IDENTITY_REQUIRED"
|
|
);
|
|
type Completion = (Option<Vec<u8>>, Option<Vec<u8>>);
|
|
let old:Option<Completion>=self.db.query_row("SELECT e.start,COALESCE(c.result,e.outcome) FROM consumed c LEFT JOIN execution_evidence e ON e.grant_id=c.grant_id WHERE c.grant_id=?1",[permit.grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?))).optional()?;
|
|
if let Some((start, outcome)) = old {
|
|
let Some(start) = start else {
|
|
return Ok(Outcome::unknown("SYSTEM_PREVIOUS_START_UNRESOLVED"));
|
|
};
|
|
let value: serde_json::Value = serde_json::from_slice(&start)?;
|
|
let original: Request = serde_json::from_value(value["request"].clone())?;
|
|
ensure!(
|
|
serde_json::to_vec(&original)? == serde_json::to_vec(request)?,
|
|
"SYSTEM_REDELIVERY_REQUEST_CHANGED"
|
|
);
|
|
return outcome
|
|
.map(|bytes| Ok(serde_json::from_slice(&bytes)?))
|
|
.unwrap_or_else(|| Ok(Outcome::unknown("SYSTEM_PREVIOUS_EFFECT_UNRESOLVED")));
|
|
}
|
|
ensure!(self.settings.enable_effects, "SYSTEM_EFFECTS_DISABLED");
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
self.sync()?;
|
|
ensure!(
|
|
self.sync.as_ref().unwrap().can_start(
|
|
&self.db,
|
|
&self.guard,
|
|
generation,
|
|
&self.clock,
|
|
&self.boot
|
|
),
|
|
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
|
);
|
|
if job.action.full_maintenance() {
|
|
return self.execute_script(generation, request, &job, &permit, peer);
|
|
}
|
|
if job.action.windows_msi().is_some() {
|
|
return self.execute_msi(generation, request, &job, &permit, peer);
|
|
}
|
|
if matches!(job.action, Action::Reboot { .. }) {
|
|
return self.execute_reboot(generation, request, &job, &permit, peer);
|
|
}
|
|
let mut provider = PreparedService::prepare(&self.settings, &job)?;
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
ensure!(
|
|
self.sync.as_ref().unwrap().can_start(
|
|
&self.db,
|
|
&self.guard,
|
|
generation,
|
|
&self.clock,
|
|
&self.boot
|
|
),
|
|
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
|
);
|
|
provider.recheck()?;
|
|
let (_, fresh, recorded_at) =
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
ensure!(fresh == permit, "SYSTEM_START_REQUEST_CHANGED");
|
|
// Parent core provides atomic request/consumption persistence; never
|
|
// dispatch SCM until both exact request and tombstone are durable.
|
|
ledger::begin_execution(
|
|
&mut self.db,
|
|
&permit,
|
|
request,
|
|
self.boot.current_boot()?,
|
|
recorded_at,
|
|
)?;
|
|
self.sync.as_mut().unwrap().close();
|
|
let mut outcome =
|
|
provider.execute(Duration::from_secs(job.max_runtime_seconds.into()), || {
|
|
self.clock.require_generation(generation)?;
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
Ok(())
|
|
});
|
|
if outcome.state == "succeeded" && self.clock.reading().is_err() {
|
|
outcome.state = "unknown".into();
|
|
outcome.error_code = "SYSTEM_FINAL_CLOCK_UNTRUSTED".into();
|
|
outcome.evidence["postconditions_passed"] = false.into();
|
|
}
|
|
ledger::persist_outcome(&self.db, &permit, &outcome)?;
|
|
self.guard.check(&self.db)?;
|
|
ledger::finish(&self.db, &permit, &outcome)?;
|
|
Ok(outcome)
|
|
}
|
|
fn execute_reboot(
|
|
&mut self,
|
|
generation: u64,
|
|
request: &Request,
|
|
job: &JobPayload,
|
|
permit: &ExecutionPermitPayload,
|
|
peer: &mut ipc::PeerProof,
|
|
) -> Result<Outcome> {
|
|
ensure!(
|
|
self.settings.permits_reboot(job),
|
|
"SYSTEM_REBOOT_POLICY_DENIED"
|
|
);
|
|
self.observe_unsettled_msi()?;
|
|
ensure!(
|
|
self.unsettled_msi.is_none(),
|
|
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
|
);
|
|
let provider = crate::reboot::Prepared::prepare(job)?;
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
let (_, fresh, recorded_at) =
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
ensure!(
|
|
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
|
"SYSTEM_REBOOT_START_FENCED"
|
|
);
|
|
let boot = self.boot.current_boot()?;
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
boot,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
ledger::begin_execution(&mut self.db, permit, request, boot, recorded_at)?;
|
|
self.sync.as_mut().unwrap().close();
|
|
let outcome = provider
|
|
.request(boot, || {
|
|
self.clock.require_generation(generation)?;
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
ensure!(
|
|
!STOP.load(Ordering::SeqCst),
|
|
"SYSTEM_REBOOT_CANCELLED_BEFORE_REQUEST"
|
|
);
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
boot,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
Ok(())
|
|
})
|
|
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_REBOOT_REQUEST_UNCONFIRMED"));
|
|
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
|
self.guard.check(&self.db)?;
|
|
// Awaiting/Unknown deliberately keeps consumed.result NULL. Only the
|
|
// existing signed new-boot reconciliation may finish the same attempt.
|
|
ledger::finish(&self.db, permit, &outcome)?;
|
|
Ok(outcome)
|
|
}
|
|
fn execute_script(
|
|
&mut self,
|
|
generation: u64,
|
|
request: &Request,
|
|
job: &JobPayload,
|
|
permit: &ExecutionPermitPayload,
|
|
peer: &mut ipc::PeerProof,
|
|
) -> Result<Outcome> {
|
|
let began = Instant::now();
|
|
ensure!(
|
|
self.settings.permits_script(job),
|
|
"SYSTEM_SCRIPT_POLICY_DENIED"
|
|
);
|
|
self.observe_unsettled_msi()?;
|
|
ensure!(
|
|
self.unsettled_msi.is_none(),
|
|
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
|
);
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
let mut context_helper=ipc::PeerProof::for_service(&self.pin.helper,std::process::id())?;
|
|
context_helper.check()?;
|
|
let agent_identity=peer.identity();
|
|
agent_identity.validate(&self.pin.agent,agent_identity.pid)?;
|
|
let helper_identity=context_helper.identity();
|
|
let execution_context=serde_json::json!({"schema_version":1,"tenant_id":self.pin.binding.tenant_id,
|
|
"asset_id":self.pin.binding.asset_id,"agent_id":self.pin.binding.agent_id,
|
|
"agent_binary_sha256":agent_identity.image_sha256,"helper_binary_sha256":helper_identity.image_sha256,
|
|
"policy_sha256":self.pin.policy_sha256,"agent_process_id":agent_identity.pid,
|
|
"agent_creation_ticks":agent_identity.creation_ticks,"helper_process_id":helper_identity.pid,
|
|
"helper_creation_ticks":helper_identity.creation_ticks,"binding_sha256":ipc::binding_hash(&self.pin.binding)?});
|
|
let (_, fresh, recorded_at) =
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
ensure!(
|
|
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
|
"SYSTEM_SCRIPT_START_FENCED"
|
|
);
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
self.boot.current_boot()?,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
ledger::begin_execution(
|
|
&mut self.db,
|
|
permit,
|
|
request,
|
|
self.boot.current_boot()?,
|
|
recorded_at,
|
|
)?;
|
|
self.sync.as_mut().unwrap().close();
|
|
let helper_sid = self.settings.helper.service_sid.clone();
|
|
let result = crate::system_script::execute(
|
|
job,
|
|
permit.grant_id,
|
|
&helper_sid,
|
|
began,
|
|
|before_start| {
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
self.clock.require_generation(generation)?;
|
|
self.clock.now()?;
|
|
ensure!(!STOP.load(Ordering::SeqCst), "SYSTEM_SCRIPT_CANCELLED");
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
self.boot.current_boot()?,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
if before_start {
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
}
|
|
Ok(())
|
|
},
|
|
);
|
|
let mut outcome = result.unwrap_or_else(|error| {
|
|
let mut value = Outcome::unknown("SYSTEM_SCRIPT_EFFECT_UNRESOLVED");
|
|
value.evidence["script_error"] = crate::system_script::diagnostic(&error);
|
|
value
|
|
});
|
|
if outcome.state == "succeeded" && self.clock.reading().is_err() {
|
|
outcome.state = "unknown".into();
|
|
outcome.error_code = "SYSTEM_FINAL_CLOCK_UNTRUSTED".into();
|
|
outcome.evidence["postconditions_passed"] = false.into();
|
|
}
|
|
let context_rechecked=self.recheck().and_then(|_|peer.check()).and_then(|_|context_helper.check()).is_ok();
|
|
if outcome.state=="succeeded" && !context_rechecked {
|
|
outcome.state="unknown".into();outcome.error_code="SYSTEM_FINAL_CONTEXT_UNCONFIRMED".into();
|
|
outcome.evidence["postconditions_passed"]=false.into();
|
|
}
|
|
outcome.evidence["execution_context"]=execution_context;
|
|
outcome.evidence["execution_context"]["rechecked_at_finish"]=context_rechecked.into();
|
|
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
|
self.guard.check(&self.db)?;
|
|
ledger::finish(&self.db, permit, &outcome)?;
|
|
Ok(outcome)
|
|
}
|
|
fn execute_msi(
|
|
&mut self,
|
|
generation: u64,
|
|
request: &Request,
|
|
job: &JobPayload,
|
|
permit: &ExecutionPermitPayload,
|
|
peer: &mut ipc::PeerProof,
|
|
) -> Result<Outcome> {
|
|
use crate::package::{Prepared, Run};
|
|
self.observe_unsettled_msi()?;
|
|
ensure!(
|
|
self.unsettled_msi.is_none(),
|
|
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
|
);
|
|
let began = Instant::now();
|
|
let original_request_sha256 = hash(&serde_json::to_vec(request)?);
|
|
let timeout = Duration::from_secs(job.max_runtime_seconds.into());
|
|
let m = job
|
|
.action
|
|
.windows_msi()
|
|
.context("SYSTEM_MSI_MANIFEST_REQUIRED")?;
|
|
ensure!(
|
|
self.settings.permits_msi(job),
|
|
"SYSTEM_MSI_RECIPE_NOT_ALLOWED"
|
|
);
|
|
// No implicit bootstrap: reject absent/unprotected cache before consume.
|
|
let _cache = PinnedFile::open(Path::new(crate::msi_cache::CACHE), true, &[], &[], false)
|
|
.context("MSI_CACHE_NOT_CONFIGURED")?;
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
ensure!(
|
|
self.sync.as_ref().unwrap().can_start(
|
|
&self.db,
|
|
&self.guard,
|
|
generation,
|
|
&self.clock,
|
|
&self.boot
|
|
),
|
|
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
|
);
|
|
let (_, fresh, recorded_at) =
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
ensure!(
|
|
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
|
"SYSTEM_MSI_START_FENCED"
|
|
);
|
|
ledger::begin_execution(
|
|
&mut self.db,
|
|
permit,
|
|
request,
|
|
self.boot.current_boot()?,
|
|
recorded_at,
|
|
)?;
|
|
self.sync.as_mut().unwrap().close();
|
|
let result = (|| -> Result<Outcome> {
|
|
ensure!(
|
|
began.elapsed() < timeout,
|
|
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
|
);
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
self.boot.current_boot()?,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
let _copied_archive = crate::msi_cache::import(m, permit.grant_id)?;
|
|
ensure!(
|
|
began.elapsed() < timeout,
|
|
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
|
);
|
|
let provider = Prepared::prepare(m, &m.recipe_sha256, began, timeout)?;
|
|
let run = provider.start(began, timeout, &STOP, || {
|
|
self.recheck()?;
|
|
peer.check()?;
|
|
ensure!(
|
|
!STOP.load(Ordering::SeqCst),
|
|
"SYSTEM_MSI_CANCELLED_BEFORE_START"
|
|
);
|
|
verified_window(&self.settings.binding, request, &self.clock)?;
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
self.boot.current_boot()?,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)?;
|
|
Ok(())
|
|
})?;
|
|
let observation = match run {
|
|
Run::Noop(value) => *value, // Noop variant can itself be Unknown.
|
|
Run::Installer(mut child) => loop {
|
|
// Continue observing this original transaction after start.
|
|
// A lost clock/peer/agent-denial observation cannot free the
|
|
// lane or retroactively produce success; never kill/retry.
|
|
let fenced = STOP.load(Ordering::SeqCst)
|
|
|| self.clock.now().is_err()
|
|
|| peer.check().is_err()
|
|
|| self
|
|
.boot
|
|
.current_boot()
|
|
.and_then(|boot| {
|
|
crate::helper_runtime::intent::Store::require_not_denied(
|
|
request,
|
|
boot,
|
|
generation,
|
|
&self.pin.policy_sha256,
|
|
&self.pin.helper.binary_sha256,
|
|
)
|
|
})
|
|
.is_err();
|
|
let cancelled = AtomicBool::new(fenced);
|
|
match child.poll(&cancelled) {
|
|
Ok(Some(mut value)) => {
|
|
if fenced {
|
|
value.state = "unknown";
|
|
value.code = "MSI_RUNNING_OBSERVATION_FENCED";
|
|
value.postconditions_passed = false;
|
|
}
|
|
if value.state == "unknown" {
|
|
self.unsettled_msi = Some(UnsettledMsi {
|
|
grant: permit.grant_id,
|
|
request_sha256: original_request_sha256.clone(),
|
|
installer: child,
|
|
});
|
|
}
|
|
break value;
|
|
}
|
|
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
|
|
Err(error) => {
|
|
let outcome = Outcome {
|
|
evidence: serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":true,"process_id":child.process_id(),"automatic_retry":false,"observer_error":safe_error(&error)}),
|
|
..Outcome::unknown("MSI_OBSERVER_FAILED_EFFECT_UNRESOLVED")
|
|
};
|
|
self.unsettled_msi = Some(UnsettledMsi {
|
|
grant: permit.grant_id,
|
|
request_sha256: original_request_sha256.clone(),
|
|
installer: child,
|
|
});
|
|
return Ok(outcome);
|
|
}
|
|
}
|
|
},
|
|
};
|
|
let mut evidence = serde_json::to_value(&observation)?;
|
|
evidence["provider"] = "windows.msi.fixture/1".into();
|
|
let mut outcome = Outcome {
|
|
state: observation.state.into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: observation.exit_code.map(|v| v as i32),
|
|
output_truncated: false,
|
|
reboot_required: observation.installer_reboot_required.unwrap_or(false),
|
|
error_code: if observation.state == "succeeded" {
|
|
String::new()
|
|
} else {
|
|
observation.code.into()
|
|
},
|
|
evidence,
|
|
};
|
|
if outcome.state == "succeeded" {
|
|
let fresh = self.clock.now().is_ok() && peer.check().is_ok();
|
|
if !fresh || began.elapsed() >= timeout {
|
|
outcome.state = "unknown".into();
|
|
outcome.error_code = "MSI_FINAL_OBSERVATION_FENCED".into();
|
|
outcome.evidence["postconditions_passed"] = false.into();
|
|
}
|
|
}
|
|
Ok(outcome)
|
|
})();
|
|
let outcome = result.unwrap_or_else(|error| {
|
|
let code = safe_error(&error);
|
|
Outcome {state:if began.elapsed() >= timeout {"unknown"} else {"failed"}.into(),
|
|
evidence:serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":false,"transaction_started":false,"automatic_retry":false}), ..Outcome::unknown(&code)}
|
|
});
|
|
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
|
self.guard.check(&self.db)?;
|
|
ledger::finish(&self.db, permit, &outcome)?;
|
|
Ok(outcome)
|
|
}
|
|
fn observe_unsettled_msi(&mut self) -> Result<()> {
|
|
let Some(slot) = self.unsettled_msi.as_mut() else {
|
|
return Ok(());
|
|
};
|
|
self.guard.check(&self.db)?;
|
|
let (start, outcome): (Vec<u8>, Vec<u8>) = self.db.query_row(
|
|
"SELECT start,outcome FROM execution_evidence WHERE grant_id=?1",
|
|
[slot.grant.to_string()],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
let start: serde_json::Value = serde_json::from_slice(&start)?;
|
|
let original: Request = serde_json::from_value(start["request"].clone())?;
|
|
let saved: Outcome = serde_json::from_slice(&outcome)?;
|
|
ensure!(
|
|
hash(&serde_json::to_vec(&original)?) == slot.request_sha256
|
|
&& saved.state == "unknown",
|
|
"SYSTEM_MSI_UNSETTLED_ORIGINAL_BINDING"
|
|
);
|
|
if slot.installer.process_exited()? {
|
|
self.unsettled_msi = None;
|
|
}
|
|
// No ledger/outcome update here. An observed late exit never revises
|
|
// the original deadline outcome or grants permission for another job.
|
|
Ok(())
|
|
}
|
|
}
|
|
pub fn safe_error(error: &anyhow::Error) -> String {
|
|
if error.chain().any(|cause| {
|
|
matches!(cause.downcast_ref::<rusqlite::Error>(),
|
|
Some(rusqlite::Error::SqliteFailure(code,_)) if code.code==rusqlite::ErrorCode::DiskFull)
|
|
}) {
|
|
return "JOURNAL_STORAGE_CAPACITY_BLOCKED".into();
|
|
}
|
|
let text = error.to_string();
|
|
if text.len() <= 96
|
|
&& text
|
|
.bytes()
|
|
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
|
|
{
|
|
text
|
|
} else {
|
|
"SYSTEM_VALIDATION_OR_STORAGE_FAILURE".into()
|
|
}
|
|
}
|
|
|
|
static STOP: AtomicBool = AtomicBool::new(false);
|
|
static SCM_HANDLE: AtomicUsize = AtomicUsize::new(0);
|
|
static START: OnceLock<()> = OnceLock::new();
|
|
fn scm_status(state: u32, error: u32) {
|
|
let h = SCM_HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
|
if h.is_null() {
|
|
return;
|
|
}
|
|
let status = SERVICE_STATUS {
|
|
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
|
dwCurrentState: state,
|
|
dwControlsAccepted: if state == SERVICE_RUNNING {
|
|
SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN
|
|
} else {
|
|
0
|
|
},
|
|
dwWin32ExitCode: error,
|
|
dwServiceSpecificExitCode: 0,
|
|
dwCheckPoint: u32::from(state == SERVICE_START_PENDING || state == SERVICE_STOP_PENDING),
|
|
dwWaitHint: if state == SERVICE_STOP_PENDING {
|
|
125000
|
|
} else {
|
|
30000
|
|
},
|
|
};
|
|
unsafe {
|
|
SetServiceStatus(h, &status);
|
|
}
|
|
}
|
|
unsafe extern "system" fn control(
|
|
code: u32,
|
|
_: u32,
|
|
_: *mut std::ffi::c_void,
|
|
_: *mut std::ffi::c_void,
|
|
) -> u32 {
|
|
if matches!(code, SERVICE_CONTROL_STOP | SERVICE_CONTROL_SHUTDOWN) {
|
|
STOP.store(true, Ordering::SeqCst);
|
|
scm_status(SERVICE_STOP_PENDING, 0);
|
|
}
|
|
0
|
|
}
|
|
unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
|
let name = ipc::wide(ipc::HELPER_SERVICE);
|
|
let handle =
|
|
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
|
if handle.is_null() {
|
|
return;
|
|
}
|
|
SCM_HANDLE.store(handle as usize, Ordering::SeqCst);
|
|
scm_status(SERVICE_START_PENDING, 0);
|
|
let result = (|| -> Result<()> {
|
|
let mut helper = SystemHelper::open()?;
|
|
let server = ipc::Server::bind(helper.pin().clone())?;
|
|
let time_server = ipc::Server::bind_time(helper.pin().clone())?;
|
|
let update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
|
|
.map(crate::update_control_ipc::Server::bind).transpose()?;
|
|
let time_pin = helper.pin().clone();
|
|
let time_clock = helper.clock.source();
|
|
let time_worker = std::thread::Builder::new()
|
|
.name("rmm-helper-time-control".into())
|
|
.spawn(move || time_control(time_server, time_pin, time_clock))?;
|
|
scm_status(SERVICE_RUNNING, 0);
|
|
let mut next_update_unknown=Instant::now();
|
|
while !STOP.load(Ordering::SeqCst) {
|
|
if Instant::now()>=next_update_unknown {
|
|
next_update_unknown=Instant::now()+Duration::from_secs(2);
|
|
if let Err(error)=crate::update_control::observe_worker_unknown(helper.update_context()) {
|
|
let _diagnostic=helper.record_pipe_error(&error);
|
|
}
|
|
}
|
|
// A failed observation keeps the owned slot and its handles locked.
|
|
if helper.observe_unsettled_msi().is_err()
|
|
&& let Some(sync) = &mut helper.sync
|
|
{
|
|
sync.close();
|
|
}
|
|
if let Some(update_server)=&update_server {
|
|
match update_server.receive() {
|
|
Ok(Some(mut incoming))=> {
|
|
let reply=crate::update_control::handle_updater(helper.update_context(),&mut incoming.peer,&incoming.request);
|
|
let result=match reply {
|
|
Ok(reply)=>update_server.reply(&mut incoming,&reply),
|
|
Err(error)=>Err(error),
|
|
};
|
|
update_server.disconnect();
|
|
if let Err(error)=result {
|
|
if let Some(sync)=&mut helper.sync {sync.close();}
|
|
let _diagnostic=helper.record_pipe_error(&error);
|
|
}
|
|
}
|
|
Ok(None)=>{},
|
|
Err(error)=> {
|
|
update_server.disconnect();
|
|
if let Some(sync)=&mut helper.sync {sync.close();}
|
|
let _diagnostic=helper.record_pipe_error(&error);
|
|
}
|
|
}
|
|
}
|
|
match server.receive() {
|
|
Ok(Some(mut incoming)) => {
|
|
let reply = helper.handle(&incoming.call, &mut incoming.peer);
|
|
let delivered = server.reply(&reply, &mut incoming.peer);
|
|
server.disconnect();
|
|
if let Err(error) = delivered {
|
|
if let Some(sync) = &mut helper.sync {
|
|
sync.close();
|
|
}
|
|
// Receipt loss cannot trigger an Activate or a retry.
|
|
helper.pending_update_activation = None;
|
|
let _diagnostic = helper.record_pipe_error(&error);
|
|
} else if matches!(reply.body, ReplyBody::UpdateAccepted { .. })
|
|
&& let Some(activation) = helper.pending_update_activation.take()
|
|
&& let Err(error) = activation.dispatch_after_reply(
|
|
&helper.db,
|
|
&helper.guard,
|
|
&helper.clock,
|
|
&helper.boot,
|
|
)
|
|
{
|
|
if let Some(sync) = &mut helper.sync {
|
|
sync.close();
|
|
}
|
|
let _diagnostic = helper.record_pipe_error(&error);
|
|
}
|
|
}
|
|
Ok(None) => {}
|
|
Err(error) => {
|
|
if let Some(sync) = &mut helper.sync {
|
|
sync.close();
|
|
}
|
|
server.disconnect();
|
|
let _diagnostic = helper.record_pipe_error(&error);
|
|
}
|
|
}
|
|
}
|
|
// The time lane has no ledger/job operation and its receive wait is
|
|
// bounded. Shutdown closes its private evidence before service exit.
|
|
time_worker
|
|
.join()
|
|
.map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
|
|
Ok(())
|
|
})();
|
|
scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
|
}
|
|
|
|
fn time_control(server: ipc::Server, pin: Pin, clock: RuntimeClock) -> Result<()> {
|
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()?;
|
|
while !STOP.load(Ordering::SeqCst) {
|
|
let received = match server.receive() {
|
|
Ok(Some(value)) => value,
|
|
Ok(None) => continue,
|
|
Err(_) => {
|
|
clock.close()?;
|
|
server.disconnect();
|
|
continue;
|
|
}
|
|
};
|
|
let mut incoming = received;
|
|
let result = (|| -> Result<ReplyBody> {
|
|
incoming.peer.check()?;
|
|
let body = match &incoming.call.operation {
|
|
Operation::TimeBegin { generation } => {
|
|
if !clock.configured_for(*generation) {
|
|
runtime.block_on(clock.open_connection(*generation))?;
|
|
}
|
|
ReplyBody::TimeChallenge {
|
|
request: clock.begin(*generation)?,
|
|
}
|
|
}
|
|
Operation::TimeComplete {
|
|
generation,
|
|
response_bytes,
|
|
} => {
|
|
ensure!(response_bytes.len() <= 16384, "SYSTEM_TIME_RESPONSE_BOUND");
|
|
clock.complete(*generation, response_bytes)?;
|
|
ReplyBody::TimeCompleted {}
|
|
}
|
|
Operation::TimeClose { generation } => {
|
|
clock.close_generation(*generation)?;
|
|
ReplyBody::TimeClosed {}
|
|
}
|
|
_ => anyhow::bail!("SYSTEM_TIME_OPERATION_REQUIRED"),
|
|
};
|
|
incoming.peer.check()?;
|
|
Ok(body)
|
|
})();
|
|
let body = match result {
|
|
Ok(value) => value,
|
|
Err(_) => {
|
|
clock.close()?;
|
|
ReplyBody::Denied {
|
|
code: "SYSTEM_TIME_DENIED".into(),
|
|
}
|
|
}
|
|
};
|
|
let reply = Reply {
|
|
schema_version: 1,
|
|
challenge: incoming.call.challenge,
|
|
binding_sha256: ipc::binding_hash(&pin.binding)?,
|
|
policy_sha256: pin.policy_sha256.clone(),
|
|
helper_binary_sha256: pin.helper.binary_sha256.clone(),
|
|
body,
|
|
};
|
|
if server.reply(&reply, &mut incoming.peer).is_err() {
|
|
clock.close()?;
|
|
}
|
|
server.disconnect();
|
|
}
|
|
clock.close()
|
|
}
|
|
pub fn dispatch() -> Result<()> {
|
|
ensure!(
|
|
std::env::args().skip(1).collect::<Vec<_>>() == ["--service"],
|
|
"SYSTEM_SCM_MODE_ONLY"
|
|
);
|
|
ensure!(START.set(()).is_ok(), "SYSTEM_SCM_ALREADY_STARTED");
|
|
let mut name = ipc::wide(ipc::HELPER_SERVICE);
|
|
let table = [
|
|
SERVICE_TABLE_ENTRYW {
|
|
lpServiceName: name.as_mut_ptr(),
|
|
lpServiceProc: Some(service_main),
|
|
},
|
|
SERVICE_TABLE_ENTRYW {
|
|
lpServiceName: ptr::null_mut(),
|
|
lpServiceProc: None,
|
|
},
|
|
];
|
|
ensure!(
|
|
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
|
"SYSTEM_SCM_DISPATCH"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi() {
|
|
let job = crate::helper_runtime::msi_test_job();
|
|
let m = job.action.windows_msi().unwrap();
|
|
let peer = PeerPin {
|
|
service_name: "synthetic".into(),
|
|
service_sid: "synthetic".into(),
|
|
user_sid: "synthetic".into(),
|
|
binary: PathBuf::from("synthetic"),
|
|
binary_sha256: "ab".repeat(32),
|
|
};
|
|
let mut settings = Settings {
|
|
schema_version: 1,
|
|
binding: Binding {
|
|
tenant_id: job.tenant_id,
|
|
asset_id: job.asset_id,
|
|
agent_id: job.agent_id,
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
public_key_hex: "ab".repeat(32),
|
|
},
|
|
agent: peer.clone(),
|
|
helper: peer,
|
|
allowed_services: vec![],
|
|
max_runtime_seconds: 30,
|
|
enable_effects: false,
|
|
allow_reboot: false,
|
|
allowed_msi_recipe_sha256: None,
|
|
allowed_script_profiles: None,
|
|
windows_update_max_runtime_seconds: None,
|
|
};
|
|
let legacy = serde_json::to_value(&settings).unwrap();
|
|
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
|
|
let mut null = legacy.clone();
|
|
null["allowed_msi_recipe_sha256"] = serde_json::Value::Null;
|
|
assert!(serde_json::from_value::<Settings>(null).is_err());
|
|
assert!(!settings.permits_msi(&job));
|
|
settings.allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
|
|
assert!(!settings.permits_msi(&job));
|
|
assert_eq!(
|
|
settings.validate().unwrap_err().to_string(),
|
|
"SYSTEM_POLICY_PROFILE"
|
|
);
|
|
settings.schema_version = 2;
|
|
assert!(settings.permits_msi(&job));
|
|
assert!(!settings.enable_effects);
|
|
settings.max_runtime_seconds = 29;
|
|
assert!(!settings.permits_msi(&job));
|
|
settings.max_runtime_seconds = 30;
|
|
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
|
assert!(!settings.permits_msi(&job));
|
|
let mut script = job.clone();
|
|
script.action = Action::RunScript {
|
|
interpreter: "powershell".into(),
|
|
script_utf8: "Write-Output 'hi'\r\n".into(),
|
|
arguments: vec![],
|
|
expected_stdout: None,
|
|
windows_execution_profile: None,
|
|
privileged_script_profile: Some(
|
|
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
|
),
|
|
};
|
|
assert!(!settings.permits_script(&script));
|
|
settings.allowed_script_profiles = Some(vec![
|
|
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
|
]);
|
|
assert!(!settings.permits_script(&script));
|
|
settings.schema_version = 3;
|
|
assert!(settings.permits_script(&script));
|
|
let generic_script = script.action.clone();
|
|
script.max_runtime_seconds = 3600;
|
|
settings.windows_update_max_runtime_seconds = Some(3600);
|
|
assert!(!settings.permits_script(&script));
|
|
if let Action::RunScript { script_utf8, windows_execution_profile, .. } = &mut script.action {
|
|
*script_utf8 = rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into();
|
|
*windows_execution_profile = Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
|
|
}
|
|
assert!(settings.permits_script(&script));
|
|
settings.windows_update_max_runtime_seconds = None;
|
|
assert!(!settings.permits_script(&script));
|
|
script.action = generic_script;
|
|
script.max_runtime_seconds = 30;
|
|
script.execution_identity = "root".into();
|
|
assert!(!settings.permits_script(&script));
|
|
let mut null = legacy;
|
|
null["allowed_script_profiles"] = serde_json::Value::Null;
|
|
assert!(serde_json::from_value::<Settings>(null).is_err());
|
|
let mut reboot = job.clone();
|
|
reboot.action = Action::Reboot {
|
|
reason: "Windows-MVP".into(),
|
|
dependency_group: "windows-mvp".into(),
|
|
reconnect_timeout_seconds: 180,
|
|
};
|
|
reboot.max_runtime_seconds = 60;
|
|
settings.max_runtime_seconds = 120;
|
|
settings.allow_reboot = true;
|
|
for v in 1..=3 {
|
|
settings.schema_version = v;
|
|
assert!(!settings.permits_reboot(&reboot));
|
|
}
|
|
settings.schema_version = 4;
|
|
assert!(settings.permits_reboot(&reboot));
|
|
settings.allow_reboot = false;
|
|
assert!(!settings.permits_reboot(&reboot));
|
|
settings.allow_reboot = true;
|
|
reboot.execution_identity = "agent_service".into();
|
|
assert!(!settings.permits_reboot(&reboot));
|
|
}
|
|
#[test]
|
|
fn service_adapter_exposes_only_implemented_states() {
|
|
assert_eq!(desired_state("running").unwrap(), SERVICE_RUNNING);
|
|
assert_eq!(desired_state("stopped").unwrap(), SERVICE_STOPPED);
|
|
for state in ["restarted", "reload", "start;whoami", ""] {
|
|
assert!(desired_state(state).is_err());
|
|
}
|
|
}
|
|
#[test]
|
|
fn single_fixture_cannot_start_services_or_groups_as_dependencies() {
|
|
let rule = ServiceRule {
|
|
name: "RmmDiscoveryFixtureTest".into(),
|
|
binary: PathBuf::from(r"C:\Program Files\RustDiscoveryFixtures\fixture.exe"),
|
|
binary_sha256: "a".repeat(64),
|
|
};
|
|
let view = ServiceConfig {
|
|
service_type: SERVICE_WIN32_OWN_PROCESS,
|
|
binary: format!("\"{}\"", rule.binary.display()),
|
|
account: "NT AUTHORITY\\LocalService".into(),
|
|
dependencies_empty: true,
|
|
load_group_empty: true,
|
|
recovery: RecoveryConfig {
|
|
actions: vec![],
|
|
command_empty: true,
|
|
reboot_text_empty: true,
|
|
},
|
|
sid_type: SERVICE_SID_TYPE_UNRESTRICTED,
|
|
};
|
|
assert!(view.validate(&rule).is_ok());
|
|
for changed in [
|
|
ServiceConfig {
|
|
dependencies_empty: false,
|
|
..view.clone()
|
|
},
|
|
ServiceConfig {
|
|
load_group_empty: false,
|
|
..view.clone()
|
|
},
|
|
ServiceConfig {
|
|
account: "LocalSystem".into(),
|
|
..view.clone()
|
|
},
|
|
ServiceConfig {
|
|
binary: r"C:\Windows\System32\other.exe".into(),
|
|
..view.clone()
|
|
},
|
|
ServiceConfig {
|
|
sid_type: SERVICE_SID_TYPE_NONE,
|
|
..view.clone()
|
|
},
|
|
] {
|
|
assert!(changed.validate(&rule).is_err());
|
|
}
|
|
}
|
|
#[test]
|
|
fn fixture_recovery_cannot_add_commands_reboots_or_restart_attempts() {
|
|
let none = RecoveryConfig {
|
|
actions: vec![SC_ACTION_NONE],
|
|
command_empty: true,
|
|
reboot_text_empty: true,
|
|
};
|
|
assert!(none.validate().is_ok());
|
|
for kind in [SC_ACTION_RESTART, SC_ACTION_RUN_COMMAND, SC_ACTION_REBOOT] {
|
|
assert!(
|
|
RecoveryConfig {
|
|
actions: vec![kind],
|
|
..none.clone()
|
|
}
|
|
.validate()
|
|
.is_err()
|
|
);
|
|
}
|
|
assert!(
|
|
RecoveryConfig {
|
|
command_empty: false,
|
|
..none.clone()
|
|
}
|
|
.validate()
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
RecoveryConfig {
|
|
reboot_text_empty: false,
|
|
..none
|
|
}
|
|
.validate()
|
|
.is_err()
|
|
);
|
|
}
|
|
#[test]
|
|
fn completed_scm_state_cannot_override_elapsed_runtime() {
|
|
let expired = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
|
|
assert!(check_runtime(expired).is_err());
|
|
assert!(check_runtime(Instant::now() + Duration::from_secs(10)).is_ok());
|
|
}
|
|
}
|