Support interactive customer transfers for enrolled devices
Rust development slice / linux (push) Failing after 8s

This commit is contained in:
2026-11-18 21:35:28 +01:00
parent db6325131a
commit 5253a9f596
24 changed files with 1715 additions and 39 deletions
+131 -15
View File
@@ -92,6 +92,11 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
])
}
impl Config {
fn supports_customer_transfer(&self) -> bool {
cfg!(feature = "system-helper") && self.enable_jobs
&& self.localservice_time_policy.is_some() && self.job_binding_file.is_none()
&& !self.windows_echo_probe_only && !self.windows_update_helper
}
fn allows_script_action(&self, action: &Action, identity: &str) -> bool {
let Action::RunScript { interpreter, windows_execution_profile, .. } = action else {
return false;
@@ -183,6 +188,16 @@ fn protected_read(path: &Path, max: usize) -> Result<Vec<u8>> {
);
Ok(fs::read(path)?)
}
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
let key = match previous {
Some(raw) => KeyPair::from_pem(std::str::from_utf8(raw)?)?,
None => KeyPair::generate()?,
};
let mut parameters = CertificateParams::default();
parameters.distinguished_name.push(DnType::CommonName, "customer-transfer");
let csr = parameters.serialize_request(&key)?.pem()?;
Ok((key.serialize_pem().into_bytes(), csr))
}
async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
let state = &config.state_directory;
let identity = state.join("identity.json");
@@ -625,6 +640,7 @@ struct Agent {
config: Config,
reported_version: String,
release_job_guard: Option<fs::File>,
transfer_gate: Option<fs::File>,
identity: EnrollmentResponse,
ca: Vec<u8>,
journal: Journal,
@@ -1561,12 +1577,54 @@ impl Agent {
}
Ok(false)
}
async fn stage_customer_transfer(&mut self) -> Result<bool> {
if !self.config.supports_customer_transfer() || self.running.is_some()
|| self.prepared || self.deferred_sync.is_some() || self.deferred_permit.is_some()
|| self.release_job_guard.is_some() {
return Ok(false);
}
let (Some(binding), Some(ledger)) = (&self.binding, &self.ledger) else {
return Ok(false);
};
if !rmm_agent_core::customer_transfer::idle(self.journal.connection(), ledger)? {
return Ok(false);
}
#[cfg(feature = "system-helper")]
if self.helper_control_busy_for_sync() || self.update_health.is_some() {
return Ok(false);
}
// Keep the release service from replacing the program during the handoff.
let binding = binding.clone();
if !self.reserve_release_gate()? {
return Ok(false);
}
let result = async {
let identity = self.certificates.current(
self.journal.connection(), &self.key_files, Utc::now().timestamp(),
)?;
let client = crate::https_channel::mtls_client(
self.config.connect_address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
)?;
let base = format!("https://{}:{}", self.config.server_name, self.config.connect_address.port());
rmm_agent_core::customer_transfer::stage(
&client, &base, &self.config.state_directory, &binding, transfer_csr,
).await
}.await;
let gate = self.release_job_guard.take();
if matches!(&result, Ok(true)) {
self.transfer_gate = gate;
}
result
}
fn capabilities(&self) -> Vec<String> {
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
#[cfg(target_env = "gnu")]
caps.push("agent.release.windows.gnu/1".into());
// queue_update_observation emits the passive update status in every profile.
caps.push("agent.update/1".into());
if self.config.supports_customer_transfer() {
caps.push(rmm_domain::customer_transfer::CAPABILITY.into());
}
if self.config.windows_echo_probe_only {
caps.push("windows.echo-probe/1".into());
}
@@ -2746,6 +2804,11 @@ impl Agent {
if rotation_at.elapsed() >= rotation_after {
rotation_at = Instant::now();
rotation_after = Duration::from_secs(30);
match self.stage_customer_transfer().await {
Ok(true) => return Ok(()),
Ok(false) => (),
Err(_) => eprintln!("CUSTOMER_TRANSFER_PENDING"),
}
let now = Utc::now().timestamp();
if self
.certificates
@@ -2905,7 +2968,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
);
let path = Path::new(&arguments[2]);
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
let config = Config::read(path)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()?;
runtime.block_on(async {
let mut gate = None;
loop {
match run_service_binding(path, stop, gate.take()).await? {
Some(held) => gate = Some(held),
None => return Ok(()),
}
}
})
}
async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_guard: Option<fs::File>) -> Result<Option<fs::File>> {
let mut config = Config::read(path)?;
native::require_local_service()?;
ensure!(
config.state_directory.is_absolute(),
@@ -2921,21 +3000,50 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let child = child?;
native::private_path(&child.path(), child.file_type()?.is_dir())?;
}
let journal = Journal::open(&config.state_directory)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()?;
runtime.block_on(async move {
let identity = enrollment(&config, &ca).await?;
let mut journal=journal;
if rmm_agent_core::customer_transfer::pending(&config.state_directory)? {
#[cfg(feature = "system-helper")]
{
ensure!(config.supports_customer_transfer(), "TRANSFER_CONFIG");
let policy = config.localservice_time_policy.as_deref().context("TRANSFER_POLICY")?;
let signer = rmm_agent_windows::signed_clock::enrolled_transfer_signer(policy)?;
loop {
if stop.load(Ordering::SeqCst) {
return Ok(None);
}
match rmm_agent_core::customer_transfer::activate(&config.state_directory, &signer) {
Ok(()) => break,
Err(error) if error.downcast_ref::<std::io::Error>()
.is_some_and(|e| matches!(e.raw_os_error(), Some(32 | 33))) => {
// Another service can briefly hold a read-only handle.
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err(error) => return Err(error),
}
}
}
#[cfg(not(feature = "system-helper"))]
anyhow::bail!("TRANSFER_CONFIG");
}
drop(release_guard);
let mut journal = Journal::open(&config.state_directory)?;
let identity = enrollment(&config, &ca).await?;
journal.pin_identity(&identity.agent_id)?;
let (boot, booted_at) = native::boot_identity().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 };
let (binding, installed_tenant) = if let Some(policy) = &config.localservice_time_policy {
let mut enrolled = rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?;
let installed = enrolled.tenant_id;
if config.supports_customer_transfer()
&& let Some(target) = rmm_agent_core::customer_transfer::assigned_tenant(
&config.state_directory, &identity, &enrolled.public_key_hex,
)? {
enrolled.tenant_id = target;
// Elevated helpers are bound to the original installation.
config.managed_script_helper = false;
}
(Some(enrolled), Some(installed))
} else { (binding, None) };
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)?;
@@ -2952,7 +3060,9 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
#[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) }
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
).for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
@@ -2974,6 +3084,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
config,
reported_version: installed_version()?,
release_job_guard: None,
transfer_gate: None,
identity,
ca,
journal,
@@ -3038,6 +3149,12 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
if let Err(error) = agent.session(stop).await {
record_session_error(&agent.config.state_directory, &error);
}
if let Some(guard) = agent.transfer_gate.take() {
if let Some(worker) = agent.readiness_worker.take() {
let _ = worker.await;
}
return Ok(Some(guard));
}
if start.elapsed() > Duration::from_secs(60) {
backoff = 1;
}
@@ -3056,8 +3173,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
Ok(())
})
Ok(None)
}
pub fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
+21 -11
View File
@@ -802,10 +802,7 @@ mod installed {
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> {
fn installed_policy(policy: &Path) -> Result<LocalPolicy> {
crate::job_binding::check_admin_readonly(policy)?;
ensure!(
std::fs::metadata(policy)?.len() <= MAX_CONFIG_BYTES as u64,
@@ -816,6 +813,16 @@ mod installed {
p.schema_version == 1 && !p.tenant_id.is_nil() && digest(&p.job_signing_public_key_hex),
"INSTALLED_JOB_TRUST"
);
Ok(p)
}
pub fn enrolled_transfer_signer(policy: &Path) -> Result<String> {
Ok(installed_policy(policy)?.job_signing_public_key_hex)
}
pub fn enrolled_binding(
policy: &Path,
registration: &rmm_protocol::EnrollmentResponse,
) -> Result<rmm_agent_core::auth::Binding> {
let p = installed_policy(policy)?;
let binding = rmm_agent_core::auth::Binding {
tenant_id: p.tenant_id,
agent_id: Uuid::parse_str(&registration.agent_id)?,
@@ -963,6 +970,7 @@ mod installed {
generation: u64,
binding: &rmm_agent_core::auth::Binding,
policy_file: &Path,
installed_tenant: Uuid,
helper: Option<&ipc::PeerPin>,
) -> Result<Self> {
let mut failure_fence = ConstructorFailureFence { armed: true };
@@ -1002,7 +1010,7 @@ mod installed {
.map(|(id, key)| Ok((id, independent_time_key(&key, &binding.public_key_hex)?)))
.collect::<Result<BTreeMap<_, _>>>()?;
ensure!(
p.tenant_id == binding.tenant_id
p.tenant_id == installed_tenant
&& p.job_signing_public_key_hex == binding.public_key_hex,
"TIME_POLICY_BINDING"
);
@@ -1394,7 +1402,7 @@ mod installed {
pub struct RuntimeClock {
role: Role,
enrolled_helper: Option<ipc::PeerPin>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
}
#[derive(Clone)]
@@ -1414,14 +1422,16 @@ mod installed {
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
installed_tenant: Uuid,
) -> Self {
let mut value = Self::new(Role::Agent);
value.local_policy = Some((binding, policy));
value.local_policy = Some((binding, policy, installed_tenant));
value
}
pub fn enrolled_windows_update_helper(binding: rmm_agent_core::auth::Binding, helper: ipc::PeerPin) -> Self {
let mut value = Self::new(Role::SystemHelper);
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json")));
let installed_tenant = binding.tenant_id;
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json"), installed_tenant));
value.enrolled_helper = Some(helper);
value
}
@@ -1440,8 +1450,8 @@ mod installed {
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
self.close()?;
let clock = match &self.local_policy {
Some((binding, policy)) => {
SignedClock::open_local_service(generation, binding, policy, self.enrolled_helper.as_ref()).await?
Some((binding, policy, installed_tenant)) => {
SignedClock::open_local_service(generation, binding, policy, *installed_tenant, self.enrolled_helper.as_ref()).await?
}
None => SignedClock::open(self.role, generation).await?,
};
@@ -1561,7 +1571,7 @@ mod installed {
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
enrolled_binding,
enrolled_binding, enrolled_transfer_signer,
};
#[cfg(test)]