Qualify tenant-scoped bootstrap rotation and fresh Windows scripting

This commit is contained in:
2026-11-17 16:19:08 +01:00
parent 81fcd9c8f8
commit fbd24b6d75
26 changed files with 877 additions and 118 deletions
@@ -7,6 +7,10 @@ fn main() -> anyhow::Result<()> {
Some(flag) if flag == "--release-service" && args.next().is_none() => {
rmm_agent_windows::release_service::dispatch()
}
Some(flag) if flag == "--release-capabilities" && args.next().is_none() => {
println!("release-job-lock/1");
Ok(())
}
Some(flag) if flag == "--verify-bootstrap" => {
let release = rmm_updater::verify_bootstrap_files(
rmm_agent_windows::release_platform::VERIFY,
+8 -4
View File
@@ -1432,7 +1432,8 @@ impl Server {
/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor.
pub fn execution_timeout(action: &rmm_domain::jobs::Action, seconds: u32) -> Result<Duration> {
ensure!(
(1..=action.windows_system_runtime_limit(120, Some(rmm_domain::jobs::WINDOWS_UPDATE_MAX_SECONDS))).contains(&seconds),
(1..=action.windows_system_runtime_limit(120, Some(rmm_domain::jobs::WINDOWS_UPDATE_MAX_SECONDS)))
.contains(&seconds),
"SYSTEM_EXECUTION_TIMEOUT_BOUND"
);
Ok(Duration::from_secs(u64::from(seconds) + 5))
@@ -1455,9 +1456,12 @@ fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) ->
anyhow::bail!("HELPER_CALL_TIMEOUT_BOUND");
};
let job = pin.binding.job(&request.job_bytes)?;
ensure!(job.execution_identity == "system" && job.action.is_windows_update_template()
&& execution_timeout(&job.action, job.max_runtime_seconds)? == timeout,
"HELPER_CALL_TIMEOUT_BOUND");
ensure!(
job.execution_identity == "system"
&& job.action.is_windows_update_template()
&& execution_timeout(&job.action, job.max_runtime_seconds)? == timeout,
"HELPER_CALL_TIMEOUT_BOUND"
);
} else {
ensure!(timeout >= Duration::from_secs(1), "HELPER_CALL_TIMEOUT_BOUND");
}
+4 -2
View File
@@ -116,8 +116,9 @@ impl Settings {
.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()
&& (self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|| (self.windows_update_max_runtime_seconds.is_some() && job.action.is_windows_update_template()))
}
fn permits_reboot(&self, job: &JobPayload) -> bool {
self.schema_version == 4
@@ -146,7 +147,8 @@ impl Settings {
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
)
&& (self.schema_version == 4 || !self.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds, self.allowed_script_profiles.as_deref())
&& (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"
+33 -3
View File
@@ -52,6 +52,8 @@ struct Endpoint {
ca_file: PathBuf,
#[serde(default)]
enable_jobs: bool,
#[serde(default)]
localservice_time_policy: Option<PathBuf>,
}
#[derive(Deserialize)]
struct Health {
@@ -349,16 +351,36 @@ async fn stage(device: &Device, release: &Published, active: &Installed) -> Resu
result
}
fn exclusive_job_gate() -> Result<Option<fs::File>> {
use std::os::windows::fs::OpenOptionsExt;
let path = data("release-job.lock");
job_binding::check_admin_readonly(&path)?;
match fs::OpenOptions::new().read(true).share_mode(0).open(path) {
Ok(file) => Ok(Some(file)),
Err(error) if error.raw_os_error() == Some(32) => Ok(None),
Err(error) => Err(error.into()),
}
}
async fn cycle() -> Result<()> {
let active: Installed = read_record(ACTIVE)?;
let config: Endpoint = serde_json::from_slice(&protected(&data("config.json"), 32768)?)?;
// Installed passive pairs only. A separately provisioned SYSTEM helper and
// privileged time/profile pins need the existing coordinated handoff.
// Additional SYSTEM helper pins need their separately coordinated handoff.
ensure!(
!config.enable_jobs,
!config.enable_jobs
|| config.localservice_time_policy.as_ref() == Some(&data("job-time.json")),
"job-enabled pair requires coordinated helper handoff"
);
if data(INTENT).try_exists()? {
let _job_gate = if config.enable_jobs {
let Some(file) = exclusive_job_gate()? else {
return Ok(());
};
Some(file)
} else {
None
};
let t: Transition = read_record(INTENT)?;
if active.release_id == t.new.release_id {
fs::remove_file(data(INTENT))?;
@@ -414,6 +436,14 @@ async fn cycle() -> Result<()> {
"current agent version not confirmed"
);
let new = stage(&device, &release, &active).await?;
let _job_gate = if config.enable_jobs {
let Some(file) = exclusive_job_gate()? else {
return Ok(());
};
Some(file)
} else {
None
};
let t = Transition { old: active, new };
write_record(INTENT, &t)?;
let start = chrono::Utc::now();
@@ -9,7 +9,10 @@ $from = Get-Image 'FROM_UUID'
$to = Get-Image 'TO_UUID'
$service = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$config = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) { throw 'Job-enabled agent requires a coordinated handoff.' }
if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) {
if (-not $config.PSObject.Properties['localservice_time_policy'] -or
$config.localservice_time_policy -cne (Join-Path (Split-Path $configPath) 'job-time.json')) { throw 'Job-enabled pair requires a coordinated helper handoff.' }
}
if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cnotin @($from,$to) -or (Get-Service 'RmmDiscoverySystemHelper' -ErrorAction SilentlyContinue)) { throw 'Unexpected service configuration.' }
if ($service.PathName -cne $to) {
+63 -5
View File
@@ -36,6 +36,8 @@ struct Config {
transport: String,
#[serde(default)]
job_binding_file: Option<PathBuf>,
#[serde(default)]
localservice_time_policy: Option<PathBuf>,
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
#[serde(default)]
enable_jobs: bool,
@@ -88,13 +90,20 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
impl Config {
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
self.enable_jobs
&& self.job_binding_file.is_some()
&& (self.job_binding_file.is_some() || self.localservice_time_policy.is_some())
&& cfg!(feature = "system-helper")
&& self.windows_execution_profile == Some(profile)
}
fn read(path: &Path) -> Result<Self> {
let raw = protected_read(path, 32768)?;
let config: Self = serde_json::from_slice(&raw)?;
if let Some(policy) = &config.localservice_time_policy {
let parent = path.parent().context("CONFIG_PARENT")?;
ensure!(policy == &parent.join("job-time.json")
&& config.job_binding_file.is_none()
&& config.profile_enabled(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned)
&& !config.windows_echo_probe_only, "INVALID_ENROLLED_LOCALSERVICE_CONFIGURATION");
}
if config.windows_echo_probe_only {
ensure!(
config.profile_enabled(
@@ -593,6 +602,7 @@ impl HelperControl {
struct Agent {
config: Config,
reported_version: String,
release_job_guard: Option<fs::File>,
identity: EnrollmentResponse,
ca: Vec<u8>,
journal: Journal,
@@ -802,12 +812,14 @@ impl Agent {
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let helper = rmm_agent_windows::helper_runtime::Client::discover(
let helper = if self.config.localservice_time_policy.is_some() {
None
} else { rmm_agent_windows::helper_runtime::Client::discover(
&self.identity.agent_id,
&self.identity.asset_id,
self.binding.as_ref(),
self.helper_lane.clone(),
)?;
)? };
let clock = self.clock.native.source();
let stop = Arc::new(AtomicBool::new(false));
let mut tasks = Vec::new();
@@ -828,6 +840,7 @@ impl Agent {
.chain(helper_receipt.iter())
.cloned()
.collect();
let installed_localservice = self.config.localservice_time_policy.is_some();
tasks.push(tokio::spawn(async move {
let mut own_report = RefreshReport::default();
while !own_stop.load(Ordering::SeqCst) {
@@ -857,7 +870,12 @@ impl Agent {
let _ = own_clock.close_generation(generation);
}
own_report.record(&own_state, "agent", &result);
tokio::time::sleep(mode.interval(result.is_ok())).await;
let interval = if installed_localservice && result.is_ok() {
Duration::from_secs(5)
} else {
mode.interval(result.is_ok())
};
tokio::time::sleep(interval).await;
}
let _ = own_clock.close_generation(generation);
}));
@@ -1359,7 +1377,32 @@ impl Agent {
}));
Ok(false)
}
fn reserve_release_gate(&mut self) -> Result<bool> {
let Some(policy) = &self.config.localservice_time_policy else { return Ok(true) };
if self.release_job_guard.is_some() { return Ok(true) }
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
let path = policy.with_file_name("release-job.lock");
rmm_agent_windows::job_binding::check_admin_readonly(&path)?;
match fs::OpenOptions::new().read(true).share_mode(FILE_SHARE_READ).open(path) {
Ok(file) => { self.release_job_guard = Some(file); Ok(true) }
Err(error) if error.raw_os_error() == Some(32) => Ok(false),
Err(error) => Err(error.into()),
}
}
fn release_idle_gate(&mut self) -> Result<()> {
if self.release_job_guard.is_some() && self.running.is_none() && self.deferred_permit.is_none() {
let idle: bool = self.journal.connection().query_row(
"SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying','awaiting_reboot'))",
[], |row| row.get(0))?;
if idle { self.release_job_guard.take(); }
}
Ok(())
}
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service" {
return false;
}
if self.config.windows_echo_probe_only
&& !self
.config
@@ -2577,7 +2620,7 @@ impl Agent {
let prefetched=self.prefetch_update(generation,&offer,&job).await?;
#[cfg(not(feature="system-helper"))]
let prefetched=true;
if prefetched {
if prefetched && self.reserve_release_gate()? {
jobs::reserve_request(self.journal.connection(),&offer)?;
let request=self.envelope(generation,Payload::ExecutionPermitRequest(ExecutionPermitRequest{job_id:offer.job_id,attempt_id:offer.attempt_id,job_payload_hash:offer.job_payload_hash,assignment_version:job.assignment_version}))?;
channel.send(&request).await?;
@@ -2632,6 +2675,7 @@ impl Agent {
}
}
}
self.release_idle_gate()?;
if readiness_at.elapsed() >= Duration::from_secs(5) {
readiness_at = Instant::now();
if self
@@ -2832,6 +2876,10 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
#[cfg(feature = "system-helper")]
let binding = if let Some(policy) = &config.localservice_time_policy {
Some(rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?)
} else { binding };
if let Some(binding)=&binding {
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
native::private_path(&config.state_directory.join("jobs"),true)?;
@@ -2845,6 +2893,11 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
for child in fs::read_dir(&config.state_directory)? { let child=child?;native::private_path(&child.path(),child.file_type()?.is_dir())?; }
let (ledger,ledger_file)=match &binding {Some(binding)=>{let (db,file)=open_ledger(&config.state_directory,binding)?;(Some(db),Some(file))},None=>(None,None)};
let clock=JobClock::new(config.enable_jobs);
#[cfg(feature = "system-helper")]
let clock = if let Some(policy) = &config.localservice_time_policy {
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(binding,policy.clone()).for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
config.echo_scope=rmm_agent_windows::echo_probe::installed(journal.connection(),binding.as_ref().context("JOB_BINDING_REQUIRED")?)?;
@@ -2864,6 +2917,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let mut agent = Agent {
config,
reported_version: installed_version()?,
release_job_guard: None,
identity,
ca,
journal,
@@ -2954,6 +3008,10 @@ pub fn main() -> Result<()> {
ensure!(args.len() == 2, "EVENT_LOG_WORKER_ARGUMENTS");
return rmm_agent_windows::event_log_job::worker(Path::new(&args[1]));
}
if args == ["--release-capabilities"] {
println!("enrolled-localservice/1");
return Ok(());
}
if args == ["--help"] {
println!(
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
+174 -6
View File
@@ -176,6 +176,7 @@ impl UpdaterConfiguration {
enum CaptureMode {
Physical { base_error_ns: u64 },
TrustedOsActiveGuest,
EnrolledLocalService,
}
fn digest(value: &str) -> bool {
value.len() == 64
@@ -476,7 +477,9 @@ fn bracket_sample(
// This is a software bracket in trusted nominal OS units, not a
// physical accuracy bound. Checked multiplication by100 is exact, so
// there is no conversion rounding remainder or invented base constant.
CaptureMode::TrustedOsActiveGuest => width.max(unbiased_width),
CaptureMode::TrustedOsActiveGuest | CaptureMode::EnrolledLocalService => {
width.max(unbiased_width)
}
};
ensure!(
capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS,
@@ -778,14 +781,58 @@ mod installed {
challenge: Challenge,
}
struct HeldEvidence {
received_ticks: Sample,
evidence: VerifiedEvidence,
epoch: u64,
}
/// Own-process role proof, protected held configuration, private challenge
/// and native timers. No constructor accepts agent-reported helper times.
enum ClockOwner {
Service(Box<PeerProof>),
EnrolledLocalService,
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct LocalPolicy {
schema_version: u32,
key_generation: u64,
server_instance: Uuid,
public_keys_hex: BTreeMap<String, String>,
tenant_id: Uuid,
job_signing_public_key_hex: String,
}
pub fn enrolled_binding(
policy: &Path,
registration: &rmm_protocol::EnrollmentResponse,
) -> Result<rmm_agent_core::auth::Binding> {
crate::job_binding::check_admin_readonly(policy)?;
ensure!(
std::fs::metadata(policy)?.len() <= MAX_CONFIG_BYTES as u64,
"TIME_NATIVE_CONFIG_SIZE"
);
let p: LocalPolicy = serde_json::from_slice(&std::fs::read(policy)?)?;
ensure!(
p.schema_version == 1 && !p.tenant_id.is_nil() && digest(&p.job_signing_public_key_hex),
"INSTALLED_JOB_TRUST"
);
let binding = rmm_agent_core::auth::Binding {
tenant_id: p.tenant_id,
agent_id: Uuid::parse_str(&registration.agent_id)?,
asset_id: Uuid::parse_str(&registration.asset_id)?,
enrollment_generation: 1,
assignment_version: 1,
public_key_hex: p.job_signing_public_key_hex,
};
ensure!(
!binding.agent_id.is_nil() && !binding.asset_id.is_nil(),
"INSTALLED_DEVICE_IDENTITY"
);
Ok(binding)
}
pub struct SignedClock {
verifier: Verifier,
own_process: PeerProof,
owner: ClockOwner,
files: Vec<PinnedFile>,
config_sha256: String,
boot_id: Uuid,
@@ -891,7 +938,7 @@ mod installed {
files.push(config_file);
let mut value = Self {
verifier: Verifier::new(context, pins)?,
own_process,
owner: ClockOwner::Service(Box::new(own_process)),
files,
config_sha256: hash(&raw),
boot_id,
@@ -910,6 +957,88 @@ mod installed {
failure_fence.armed = false;
Ok(value)
}
/// An enrolled LocalService never supplies time evidence for a helper.
/// Its public broker pins and job binding are installed by the HTTPS
/// bootstrap; every usable reading still needs a current signed challenge.
async fn open_local_service(
generation: u64,
binding: &rmm_agent_core::auth::Binding,
policy_file: &Path,
) -> Result<Self> {
let mut failure_fence = ConstructorFailureFence { armed: true };
crate::native::require_local_service()?;
let readers = [crate::native::service_sid()?];
let parent = PinnedFile::open(
policy_file.parent().context("TIME_POLICY_PARENT")?,
true,
&readers,
&[],
false,
)?;
let mut config_file = PinnedFile::open(policy_file, false, &readers, &[], false)?;
let mut raw = Vec::new();
(&mut config_file.file)
.take(MAX_CONFIG_BYTES as u64 + 1)
.read_to_end(&mut raw)?;
ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE");
let p: LocalPolicy = serde_json::from_slice(&raw)?;
ensure!(
p.schema_version == 1
&& !p.public_keys_hex.is_empty()
&& p.public_keys_hex.len() <= 8,
"TIME_LOCAL_SERVICE_POLICY"
);
let keys = p
.public_keys_hex
.into_iter()
.map(|(id, key)| Ok((id, independent_time_key(&key, &binding.public_key_hex)?)))
.collect::<Result<BTreeMap<_, _>>>()?;
ensure!(
p.tenant_id == binding.tenant_id
&& p.job_signing_public_key_hex == binding.public_key_hex,
"TIME_POLICY_BINDING"
);
let pins = Pins::new(p.key_generation, p.server_instance, keys)?;
let boot_id = Uuid::parse_str(&crate::native::boot_id().await?)?;
let context = Context {
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: binding.enrollment_generation,
assignment_generation: binding.assignment_version,
connection_generation: generation,
windows_boot_id: boot_id,
verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4),
role: Role::Agent,
binding_schema: 1,
helper_image_sha256: None,
updater_image_sha256: None,
};
let hash = hash(&raw);
let mut clock = Self {
verifier: Verifier::new(context, pins)?,
owner: ClockOwner::EnrolledLocalService,
files: vec![parent, config_file],
config_sha256: hash.clone(),
boot_id,
connection_generation: generation,
capture_mode: CaptureMode::EnrolledLocalService,
pending: None,
latest: None,
own_updater_configuration: None,
};
clock.recheck()?;
{
let mut state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
state.accept_configuration(p.key_generation, &hash)?;
state.accept_connection(generation)?;
}
observed(boot_id, clock.capture_mode)?;
failure_fence.armed = false;
Ok(clock)
}
/// Stable-updater-only process proof and separately protected profile.
/// It uses its OWN current SCM process/image/token and challenge.
pub async fn open_updater(connection_generation: u64) -> Result<Self> {
@@ -1011,7 +1140,7 @@ mod installed {
let capture_mode = CaptureMode::TrustedOsActiveGuest;
let mut value = Self {
verifier: Verifier::new(context, pins)?,
own_process,
owner: ClockOwner::Service(Box::new(own_process)),
files: vec![root, policy_file, config_file],
config_sha256: hash(&raw),
boot_id,
@@ -1032,7 +1161,10 @@ mod installed {
}
fn recheck(&mut self) -> Result<()> {
let result = (|| {
self.own_process.check()?;
match &mut self.owner {
ClockOwner::Service(process) => process.check()?,
ClockOwner::EnrolledLocalService => crate::native::require_local_service()?,
}
if let Some((pin, expected)) = &self.own_updater_configuration {
ensure!(
crate::update_native::services::updater_configuration_sha256(pin)?
@@ -1141,6 +1273,7 @@ mod installed {
state.active = None;
self.latest = Some(HeldEvidence {
evidence,
received_ticks: received,
epoch: pending.epoch,
});
let comparison = Comparison {
@@ -1179,6 +1312,25 @@ mod installed {
self.recheck()?;
let (sample, current_epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == current_epoch, "TIME_NATIVE_EVIDENCE_INVALIDATED");
if self.capture_mode == CaptureMode::EnrolledLocalService {
let previous = self
.latest
.as_ref()
.context("TIME_NATIVE_NO_EVIDENCE")?
.received_ticks;
let wall = sample
.interrupt_ns
.checked_sub(previous.interrupt_ns)
.context("TIME_INTERRUPT_RESET")?;
let awake = sample
.unbiased_ns
.checked_sub(previous.unbiased_ns)
.context("TIME_AWAKE_RESET")?;
ensure!(
wall <= 15 * SECOND_NS && wall.abs_diff(awake) <= 10_000_000,
"TIME_LOCAL_SERVICE_STALE_OR_SUSPENDED"
);
}
let state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
@@ -1233,6 +1385,7 @@ mod installed {
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
}
#[derive(Clone)]
@@ -1244,9 +1397,18 @@ mod installed {
pub fn new(role: Role) -> Self {
Self {
role,
local_policy: None,
state: Arc::new(Mutex::new(None)),
}
}
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
) -> Self {
let mut value = Self::new(Role::Agent);
value.local_policy = Some((binding, policy));
value
}
pub fn for_generation(&self, generation: u64) -> BoundClock {
BoundClock {
source: self.clone(),
@@ -1261,7 +1423,12 @@ mod installed {
pub async fn open_connection(&self, generation: u64) -> Result<()> {
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
self.close()?;
let clock = SignedClock::open(self.role, generation).await?;
let clock = match &self.local_policy {
Some((binding, policy)) => {
SignedClock::open_local_service(generation, binding, policy).await?
}
None => SignedClock::open(self.role, generation).await?,
};
let mut state = self
.state
.lock()
@@ -1378,6 +1545,7 @@ mod installed {
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
enrolled_binding,
};
#[cfg(test)]
@@ -80,19 +80,13 @@ pub fn qualified(
for action in q.actions {
match action.as_str() {
"run_script" => {
ensure!(
settings.schema_version >= 3
&& settings.allowed_script_profiles.as_deref()
== Some(&[
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1
])
&& crate::actions::powershell().is_ok(),
"system script qualification policy"
);
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned());
}
caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string));
let general = settings.allowed_script_profiles.as_deref() ==
Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]);
let windows_update = settings.windows_update_max_runtime_seconds.is_some();
ensure!(settings.schema_version >= 3 && (general || windows_update), "system script qualification policy");
caps.push("system:run_script".into());
if general { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.to_owned()); }
if windows_update { caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned()); }
}
"set_service_state" => {
ensure!(
+12 -2
View File
@@ -121,7 +121,12 @@ pub(crate) fn execute(
.as_ref()
.is_none_or(|s| output.stdout == s.as_bytes());
let interrupted = output.interrupted || began.elapsed() >= timeout || observe(false).is_err();
let success = !interrupted && output.exit_code == Some(0) && expected && !output.truncated;
let windows_update = job.action.is_windows_update_template();
let reboot = if windows_update && !interrupted && !output.truncated {
rmm_domain::jobs::windows_update_reboot_report(&output.stdout)
} else { None };
let success = !interrupted && output.exit_code == Some(0) && expected && !output.truncated
&& (!windows_update || reboot.is_some());
let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"privileged_script_profile":"full_maintenance_v1",
"execution_sid":"S-1-5-18","output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
@@ -133,6 +138,9 @@ pub(crate) fn execute(
evidence["execution_policy_requested"] = "RemoteSigned".into();
evidence["execution_policy_scope"] = "process".into();
}
if windows_update {
evidence["windows_update_reboot_required"] = serde_json::json!(reboot);
}
Ok(Outcome {
state: if interrupted {
"unknown"
@@ -146,13 +154,15 @@ pub(crate) fn execute(
stderr: output.stderr,
exit_code: output.exit_code,
output_truncated: output.truncated,
reboot_required: false,
reboot_required: reboot.unwrap_or(false),
error_code: if success {
""
} else if interrupted {
"SYSTEM_SCRIPT_INTERRUPTED_EFFECT_UNKNOWN"
} else if output.truncated {
"OUTPUT_LIMIT_REACHED"
} else if windows_update && output.exit_code == Some(0) && reboot.is_none() {
"WINDOWS_UPDATE_SUMMARY_MISSING"
} else if !expected {
"STDOUT_POSTCONDITION_FAILED"
} else {
@@ -215,7 +215,8 @@ pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
ensure!(
matches!(settings.schema_version, 1..=4)
&& (settings.schema_version == 4 || !settings.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(settings.windows_update_max_runtime_seconds, settings.allowed_script_profiles.as_deref())
&& (settings.schema_version >= 3 || settings.windows_update_max_runtime_seconds.is_none())
&& rmm_domain::jobs::valid_windows_update_limit(settings.windows_update_max_runtime_seconds)
&& (1..=120).contains(&settings.max_runtime_seconds)
&& settings.allowed_services.len() <= 16
&& (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none())