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())
+4 -10
View File
@@ -60,14 +60,8 @@ pub const WINDOWS_UPDATE_SCRIPT_SHA256: &str =
"0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf";
pub const WINDOWS_UPDATE_MAX_SECONDS: u32 = 3600;
pub const WINDOWS_UPDATE_LONG_CAPABILITY: &str = "script.windows_update.long/1";
pub fn valid_windows_update_limit(
limit: Option<u32>,
profiles: Option<&[PrivilegedScriptProfile]>,
) -> bool {
limit.is_none_or(|seconds| {
(121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds)
&& profiles == Some(&[PrivilegedScriptProfile::FullMaintenanceV1][..])
})
pub fn valid_windows_update_limit(limit: Option<u32>) -> bool {
limit.is_none_or(|seconds| (121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds))
}
/// Only the built-in template's final ASCII JSON object describes the host's
/// restart state. Earlier lines can include per-update results and native titles.
@@ -489,7 +483,7 @@ impl Action {
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
if !has(self.name())
|| (self.full_maintenance()
&& !(has(FULL_MAINTENANCE_CAPABILITY)
&& !((has(FULL_MAINTENANCE_CAPABILITY) || (self.is_windows_update_template() && has(WINDOWS_UPDATE_LONG_CAPABILITY)))
&& has("rmm.sync.v1")
&& has(&format!("{}:run_script", identity))
&& has(if identity == "root" {
@@ -843,7 +837,7 @@ mod tests {
None
);
assert_eq!(windows_update_reboot_report(b"partial"), None);
assert!(!valid_windows_update_limit(Some(3600), None));
assert!(!valid_windows_update_limit(Some(3601)));
}
#[test]
fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() {
+1 -1
View File
@@ -238,7 +238,7 @@ fn verify_envelope_with_keyring(
keyring_generation: config.generation,
protocol_major: 1,
state_schema: 1,
updater_version: 1,
updater_version: if binding.is_none() && decoded.manifest.platform == Platform::WindowsGnuX64 { 2 } else { 1 },
minimum_release_sequence: 0,
active_release: None,
};
+21 -1
View File
@@ -123,7 +123,7 @@ try {
Set-Text $ring ($meta.keyring | ConvertTo-Json -Depth 16 -Compress)
Set-Text $envelope ($meta.release_envelope | ConvertTo-Json -Depth 16 -Compress)
$updater = Join-Path $appStage 'rmm-updater-windows.exe'
Get-Download ('/agent/v1/bootstrap/updater' + $query) $updater $meta.updater.bytes $true
Get-Download ('/agent/v1/bootstrap/updater' + $query + '&sha256=' + $meta.updater.sha256) $updater $meta.updater.bytes $true
if ((Get-Hash $updater) -cne $meta.updater.sha256) { throw 'Bootstrap updater digest mismatch.' }
$roles = @('agent', 'helper')
for ($i = 0; $i -lt $roles.Count; $i++) {
@@ -145,6 +145,25 @@ try {
$ca = Join-Path $data 'server-ca.pem'
Set-Text (Join-Path $dataStage 'server-ca.pem') $meta.ca_pem
$config = [ordered]@{server_name=$gateway.DnsSafeHost; connect_address=$endpoint.ToString(); ca_file=$ca; state_directory=$state; enrollment_token_file=$tokenPath; transport='https'}
$localJobs = $verified.minimum_updater_version -ge 2
if ($localJobs) {
$features = & $agentPath --release-capabilities
if ($LASTEXITCODE -ne 0 -or $features -cne 'enrolled-localservice/1') { throw 'Signed agent lacks its required LocalService profile.' }
$features = & $updater --release-capabilities
if ($LASTEXITCODE -ne 0 -or $features -cne 'release-job-lock/1') { throw 'Stable updater lacks coordinated job draining.' }
$trust = $meta.windows_time_trust
if (-not $trust -or $meta.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$' -or
$trust.key_generation -lt 1 -or @($trust.public_keys_hex.PSObject.Properties).Count -notin (1..8)) { throw 'Missing enrolled Windows job trust.' }
foreach ($key in $trust.public_keys_hex.PSObject.Properties) {
if ($key.Value -cnotmatch '^[0-9a-f]{64}$' -or $key.Value -ceq $meta.job_signing_public_key_hex) { throw 'Invalid independent time signing key.' }
}
$policy = [ordered]@{schema_version=1; tenant_id=$tenant; job_signing_public_key_hex=$meta.job_signing_public_key_hex; key_generation=$trust.key_generation; server_instance=(Get-Id $trust.server_instance); public_keys_hex=$trust.public_keys_hex}
Set-Text (Join-Path $dataStage 'job-time.json') ($policy | ConvertTo-Json -Depth 8 -Compress)
Set-Text (Join-Path $dataStage 'release-job.lock') ''
$config['enable_jobs'] = $true
$config['localservice_time_policy'] = Join-Path $data 'job-time.json'
$config['windows_execution_profile'] = 'powershell_51_remote_signed'
}
Set-Text (Join-Path $dataStage 'config.json') ($config | ConvertTo-Json -Compress)
$baseline = [ordered]@{schema_version=1; tenant_id=$tenant; release_id=$releaseId; release_sequence=$verified.release_sequence; manifest_sha256=(Get-Hash (Join-Path $images 'manifest.json'))}
Set-Text (Join-Path $dataStage 'installed-release.json') ($baseline | ConvertTo-Json -Compress)
@@ -165,6 +184,7 @@ try {
Set-Acl -LiteralPath $app -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute')
Set-Acl -LiteralPath $data -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute')
[void][IO.Directory]::CreateDirectory($state, (Get-DirectoryAcl $sid 'Modify'))
if ($localJobs) { [void][IO.Directory]::CreateDirectory((Join-Path $state 'jobs'), (Get-DirectoryAcl $sid 'Modify')) }
# Agent-side private-path checks authenticate the owner as well as the DACL.
foreach ($root in @($app, $data)) {
foreach ($item in @(Get-ChildItem -LiteralPath $root -Recurse -Force)) {
+10 -3
View File
@@ -117,7 +117,10 @@ def device_get(route, size=None, digest=None):
def device_idle():
# The root worker holds the admission lock before consulting this journal.
with sqlite3.connect(f'file:{STATE}/journal.sqlite?mode=ro', uri=True) as conn:
busy, = conn.execute("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))").fetchone()
busy, = conn.execute(
"SELECT EXISTS(SELECT 1 FROM job_attempts "
"WHERE state IN ('requesting','running','verifying','unknown','awaiting_reboot'))"
).fetchone()
print('busy' if busy else 'idle')
@@ -248,7 +251,7 @@ def enable():
else:
save(path, data.encode())
service('daemon-reload')
service('enable', '--now', SERVICE, TIMER)
service('enable', '--now', SERVICE)
def enrollment_token(path):
@@ -279,6 +282,7 @@ def install(base, token_file):
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
enable()
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
service('enable', '--now', TIMER)
(ROOT / 'first.token').unlink(missing_ok=True)
return
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
@@ -302,7 +306,7 @@ def install(base, token_file):
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
'tenant': canonical_id(doc['tenant_id'])})
updater = staging / 'updater'
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM, updater, doc['updater'])
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
updater.chmod(0o755)
releases = staging / 'releases'
releases.mkdir()
@@ -318,6 +322,9 @@ def install(base, token_file):
os.rename(staging, ROOT)
enable()
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
# OnBootSec may already be in the past on a running machine. The first
# timer check can run immediately once the device has reported its platform.
service('enable', '--now', TIMER)
(ROOT / 'first.token').unlink(missing_ok=True)
+32 -5
View File
@@ -9,14 +9,41 @@ struct Config {
updater_sha256: String,
updater_bytes: u64,
}
fn config(platform: Platform) -> Result<Config, Error> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pin { sha256: String, bytes: u64 }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Previous { pin: Pin, expires_at: i64 }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TenantPins { current: Pin, previous: Vec<Previous> }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> }
fn config(platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
let slot = match platform {
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
};
let path = std::env::var(slot).map_err(|_| fail("BOOTSTRAP_NOT_CONFIGURED"))?;
let config: Config = serde_json::from_slice(&protected_file(FsPath::new(&path), 8192)?)?;
let path = FsPath::new(&path);
let mut config: Config = serde_json::from_slice(&protected_file(path, 8192)?)?;
let scoped = path.with_extension(format!("{tenant}.json"));
if scoped.try_exists().map_err(|_| fail("BOOTSTRAP_CONFIGURATION_INVALID"))? {
let pins: TenantPins = serde_json::from_slice(&protected_file(&scoped, 32768)?)?;
let selected = match wanted {
Some(digest) if pins.current.sha256 != digest => pins.previous.into_iter()
.find(|p| p.pin.sha256 == digest && p.expires_at > chrono::Utc::now().timestamp())
.map(|p| p.pin).ok_or_else(missing)?,
_ => pins.current,
};
config.updater_sha256 = selected.sha256;
config.updater_bytes = selected.bytes;
}
if wanted.is_some_and(|digest| digest != config.updater_sha256) { return Err(missing()); }
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
if url.scheme() != "https"
|| url.domain().is_none()
@@ -143,7 +170,7 @@ pub(super) async fn current(
Query(q): Query<Current>,
) -> Result<Response, Error> {
let t = token_tenant(&s, &headers).await?;
let c = config(q.platform)?;
let c = config(q.platform, t, None)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
let release: Uuid = sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1")
.bind(platform_name(q.platform)).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
@@ -187,9 +214,9 @@ pub(super) async fn artifact(
pub(super) async fn updater(
State(s): State<crate::State>,
headers: HeaderMap,
Query(q): Query<Current>,
Query(q): Query<UpdaterQuery>,
) -> Result<Response, Error> {
let tenant = token_tenant(&s, &headers).await?;
let c = config(q.platform)?;
let c = config(q.platform, tenant, q.sha256.as_deref())?;
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
}
+3 -6
View File
@@ -124,10 +124,7 @@ impl SystemScope {
.allowed_script_profiles
.as_deref()
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
&& rmm_domain::jobs::valid_windows_update_limit(
self.windows_update_max_runtime_seconds,
self.allowed_script_profiles.as_deref(),
)
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
&& (1..=120).contains(&self.max_runtime_seconds)
}
fn permits(
@@ -184,11 +181,11 @@ impl SystemScope {
Action::RunScript { .. } => {
allow_scripts
&& job.action.full_maintenance()
&& self.allowed_script_profiles.as_ref().is_some_and(|v| {
&& (self.allowed_script_profiles.as_ref().is_some_and(|v| {
v.contains(
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
)
})
}) || (self.windows_update_max_runtime_seconds.is_some() && job.action.is_windows_update_template()))
&& job.action.validate()
&& job
.action
+3 -1
View File
@@ -221,6 +221,7 @@ fn current_keyring(file: &UpdateKeyringFile) -> Result<UpdateKeyring> {
match key.platform {
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
},
key.first_sequence,
key.last_sequence,
@@ -309,6 +310,7 @@ fn verify_record_release(
let platform = match record.platform {
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
};
let envelope: &ReleaseEnvelope = &record.release_envelope;
verify_release(
@@ -402,7 +404,7 @@ fn verify_update(
job.execution_identity
== match record.platform {
Platform::LinuxX64 => "root",
Platform::WindowsX64 => "system",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
}
&& update.release_envelope == record.release_envelope
&& agent_update::handoff_matches_job(&header, &job)
+2 -1
View File
@@ -44,7 +44,8 @@ mod linux {
pub fn run() -> Result<()> {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.first().is_some_and(|arg| arg == "--verify-bootstrap") {
let release = rmm_updater::verify_bootstrap_files(rmm_updater::Platform::LinuxX64, &args[1..])?;
let release =
rmm_updater::verify_bootstrap_files(rmm_updater::Platform::LinuxX64, &args[1..])?;
println!("{}", serde_json::to_string(release.manifest())?);
return Ok(());
}
+53 -18
View File
@@ -1,8 +1,16 @@
//! Local verification for the separately distributed stable bootstrap updater.
use crate::{ArtifactRole, Platform, SignedRelease, TrustedContext, TrustedUpdateKey, UpdateKeyring, VerifiedRelease};
use crate::{
ArtifactRole, Platform, SignedRelease, TrustedContext, TrustedUpdateKey, UpdateKeyring,
VerifiedRelease,
};
use anyhow::{Context, Result, ensure};
use rmm_domain::agent_update::{Platform as WirePlatform, ReleaseEnvelope, UpdateKeyringFile};
use std::{ffi::OsString, fs::File, io::Read, time::{SystemTime, UNIX_EPOCH}};
use std::{
ffi::OsString,
fs::File,
io::Read,
time::{SystemTime, UNIX_EPOCH},
};
fn bounded(path: &OsString, limit: u64) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
@@ -19,26 +27,53 @@ pub fn verify_bootstrap_files(platform: Platform, args: &[OsString]) -> Result<V
};
let config: UpdateKeyringFile = serde_json::from_slice(&bounded(keyring, 16384)?)?;
ensure!(config.validate(), "invalid bootstrap keyring");
let keys = config.keys.into_iter().map(|key| {
let platform = match key.platform {
WirePlatform::LinuxX64 => Platform::LinuxX64,
WirePlatform::WindowsX64 => Platform::WindowsX64,
WirePlatform::WindowsGnuX64 => Platform::WindowsGnuX64,
};
let raw = hex::decode(key.public_key_hex)?.try_into().ok().context("Ed25519 public key length")?;
TrustedUpdateKey::new(raw, platform, key.first_sequence, key.last_sequence, key.revoked)
}).collect::<Result<Vec<_>>>()?;
let keys = config
.keys
.into_iter()
.map(|key| {
let platform = match key.platform {
WirePlatform::LinuxX64 => Platform::LinuxX64,
WirePlatform::WindowsX64 => Platform::WindowsX64,
WirePlatform::WindowsGnuX64 => Platform::WindowsGnuX64,
};
let raw = hex::decode(key.public_key_hex)?
.try_into()
.ok()
.context("Ed25519 public key length")?;
TrustedUpdateKey::new(
raw,
platform,
key.first_sequence,
key.last_sequence,
key.revoked,
)
})
.collect::<Result<Vec<_>>>()?;
let ring = UpdateKeyring::new(config.generation, keys)?;
let envelope: ReleaseEnvelope = serde_json::from_slice(&bounded(envelope, 32768)?)?;
let decoded = envelope.decode().map_err(|_| anyhow::anyhow!("invalid release envelope"))?;
let decoded = envelope
.decode()
.map_err(|_| anyhow::anyhow!("invalid release envelope"))?;
let context = TrustedContext {
platform, now_utc_seconds: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
keyring_generation: config.generation, protocol_major: 1, state_schema: 1,
updater_version: 1, minimum_release_sequence: 0, active_release: None,
platform,
now_utc_seconds: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
keyring_generation: config.generation,
protocol_major: 1,
state_schema: 1,
updater_version: if platform == Platform::WindowsGnuX64 { 2 } else { 1 },
minimum_release_sequence: 0,
active_release: None,
};
let release = crate::verify_release(SignedRelease {schema_version: envelope.schema_version,
key_id: &envelope.key_id, payload_bytes: &decoded.payload_bytes,
signature: &decoded.signature}, &ring, &context)?;
let release = crate::verify_release(
SignedRelease {
schema_version: envelope.schema_version,
key_id: &envelope.key_id,
payload_bytes: &decoded.payload_bytes,
signature: &decoded.signature,
},
&ring,
&context,
)?;
release.verify_artifact(ArtifactRole::Agent, File::open(agent)?)?;
release.verify_artifact(ArtifactRole::Helper, File::open(helper)?)?;
Ok(release)