Integrate independent signed Windows clocks with native Linux lease guards
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-15 10:26:24 +01:00
parent 6ddfc95fff
commit 09f7e5af84
13 changed files with 1093 additions and 37 deletions
+8 -3
View File
@@ -312,6 +312,12 @@ struct WorkerConfig {
job_binding_file: PathBuf,
enable_jobs: bool,
}
/// This is a separate child process, not the SCM agent's clock context. Until
/// it has its own independently qualified signed adapter, deny rather than
/// accepting parent timestamps or falling back to the unqualified RPC clock.
fn worker_clock_now() -> Result<DateTime<Utc>> {
anyhow::bail!("EVENT_LOG_SIGNED_CHILD_CLOCK_NOT_CONFIGURED")
}
fn ticket_name(permit: &ExecutionPermitPayload) -> String {
format!("eventlog-{}.json", hash(permit.grant_id.as_bytes()))
}
@@ -527,8 +533,7 @@ pub fn worker(path: &Path) -> Result<()> {
"EVENT_LOG_PARENT_INSTANCE"
);
let binding = crate::job_binding::readonly_binding(&config.job_binding_file)?;
let clock = crate::clock::NativeClock::new();
let now = clock.now()?;
let now = worker_clock_now()?;
let (job, permit) = binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
let query = event_log::for_job(&job)?;
@@ -579,7 +584,7 @@ pub fn worker(path: &Path) -> Result<()> {
once.sync_all()?;
native::private_path(&marker, false)?;
// File I/O, CIM and child scheduling cannot extend the signed start window.
let now = clock.now()?;
let now = worker_clock_now()?;
binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
ensure!(
+59 -3
View File
@@ -33,6 +33,7 @@ pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper";
// Framing v2 is deliberately a separate endpoint. Old peers cannot send a
// v1 call to this server or interpret the drain receipt as another reply.
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
pub const TIME_PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-Time-v1";
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
const FRAME_HEADER_LEN: usize = 12;
@@ -289,6 +290,17 @@ impl Pin {
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
pub enum Operation {
TimeBegin {
generation: u64,
},
TimeComplete {
generation: u64,
response_bytes: Vec<u8>,
},
/// Deny-only transport/context fence. It cannot qualify a clock or lease.
TimeClose {
generation: u64,
},
Probe {},
Snapshot {
generation: u64,
@@ -308,6 +320,14 @@ pub enum Operation {
intent_sha256: String,
},
}
impl Operation {
fn time_only(&self) -> bool {
matches!(
self,
Self::TimeBegin { .. } | Self::TimeComplete { .. } | Self::TimeClose { .. }
)
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Call {
@@ -331,6 +351,11 @@ impl Call {
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReplyBody {
TimeChallenge {
request: rmm_time_attestation::Request,
},
TimeCompleted {},
TimeClosed {},
Probe {
clock_qualified: bool,
ready: bool,
@@ -1261,6 +1286,7 @@ fn verify_drain_receipt(
pub struct Server {
pipe: OwnedHandle,
pin: Pin,
time_only: bool,
}
pub struct Received {
pub call: Call,
@@ -1268,6 +1294,12 @@ pub struct Received {
}
impl Server {
pub fn bind(pin: Pin) -> Result<Self> {
Self::bind_fixed(pin, false)
}
pub fn bind_time(pin: Pin) -> Result<Self> {
Self::bind_fixed(pin, true)
}
fn bind_fixed(pin: Pin, time_only: bool) -> Result<Self> {
pin.validate()?;
require_self(&pin.helper)?;
let descriptor = pipe_descriptor(&pin.agent.service_sid, &pin.helper.service_sid)?;
@@ -1278,7 +1310,7 @@ impl Server {
};
let pipe = owned(unsafe {
CreateNamedPipeW(
wide(PIPE_NAME).as_ptr(),
wide(if time_only { TIME_PIPE_NAME } else { PIPE_NAME }).as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
1,
@@ -1288,7 +1320,11 @@ impl Server {
&security,
)
})?;
Ok(Self { pipe, pin })
Ok(Self {
pipe,
pin,
time_only,
})
}
pub fn receive(&self) -> Result<Option<Received>> {
let pipe = self.pipe.as_raw_handle();
@@ -1341,6 +1377,10 @@ impl Server {
auth.context(Stage::ServerVerifyToken)?;
require_self(&self.pin.helper).context(Stage::ServerVerifyToken)?;
let call: Call = body(pipe, len, deadline).context(Stage::ServerReadBody)?;
ensure!(
call.operation.time_only() == self.time_only,
"HELPER_PIPE_OPERATION_SCOPE"
);
if !(call.schema_version == 1
&& !call.challenge.is_nil()
&& call.policy_sha256 == self.pin.policy_sha256
@@ -1378,6 +1418,16 @@ impl Server {
}
/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor.
pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
exchange_fixed(pin, call, timeout, false)
}
pub fn exchange_time(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
exchange_fixed(pin, call, timeout, true)
}
fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) -> Result<Reply> {
ensure!(
call.operation.time_only() == time_only,
"HELPER_PIPE_OPERATION_SCOPE"
);
pin.validate()?;
require_self(&pin.agent).context(Stage::ClientSelfRole)?;
ensure!(
@@ -1387,7 +1437,7 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
let deadline = Instant::now() + timeout;
let pipe = owned(unsafe {
CreateFileW(
wide(PIPE_NAME).as_ptr(),
wide(if time_only { TIME_PIPE_NAME } else { PIPE_NAME }).as_ptr(),
CLIENT_PIPE_RIGHTS,
0,
ptr::null(),
@@ -1422,6 +1472,12 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
| (Operation::Apply { .. }, ReplyBody::Applied { .. })
| (Operation::Execute { .. }, ReplyBody::Executed { .. })
| (Operation::Abandon { .. }, ReplyBody::Abandoned { .. })
| (Operation::TimeBegin { .. }, ReplyBody::TimeChallenge { .. })
| (
Operation::TimeComplete { .. },
ReplyBody::TimeCompleted { .. }
)
| (Operation::TimeClose { .. }, ReplyBody::TimeClosed { .. })
) {
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
}
@@ -242,6 +242,81 @@ impl Client {
async fn call(&self, operation: ipc::Operation) -> Result<ipc::Reply> {
self.call_bounded(operation, Duration::from_secs(5)).await
}
async fn time_call(&self, operation: ipc::Operation, timeout: Duration) -> Result<ipc::Reply> {
// Separate from the long Execute lane, retained process-wide even if a
// caller/session is dropped while a blocking native call is outstanding.
static TIME_LANE: std::sync::OnceLock<Arc<Semaphore>> = std::sync::OnceLock::new();
let permit = TIME_LANE
.get_or_init(|| Arc::new(Semaphore::new(1)))
.clone()
.try_acquire_owned()
.context("HELPER_TIME_BUSY")?;
let client = self.clone();
tokio::task::spawn_blocking(move || {
let _permit = permit;
client.check_pin()?;
let call = ipc::Call::new(&client.pin, operation);
let reply = ipc::exchange_time(&client.pin, &call, timeout)?;
client.check_pin()?;
Ok(reply)
})
.await?
}
pub async fn time_begin(&self, generation: u64) -> Result<rmm_time_attestation::Request> {
let reply = self
.time_call(
ipc::Operation::TimeBegin { generation },
Duration::from_secs(20),
)
.await?;
let ipc::ReplyBody::TimeChallenge { request } = reply.body else {
anyhow::bail!("HELPER_TIME_BEGIN_DENIED");
};
request.validate()?;
ensure!(
request.context.role == rmm_time_attestation::Role::SystemHelper
&& request.context.connection_generation == generation
&& request.context.tenant_id == self.pin.binding.tenant_id
&& request.context.asset_id == self.pin.binding.asset_id
&& request.context.agent_id == self.pin.binding.agent_id
&& request.context.enrollment_generation == self.pin.binding.enrollment_generation
&& request.context.assignment_generation == self.pin.binding.assignment_version
&& request.context.helper_image_sha256.as_deref()
== Some(self.pin.helper.binary_sha256.as_str()),
"HELPER_TIME_REQUEST_BINDING"
);
Ok(request)
}
pub async fn time_complete(&self, generation: u64, response_bytes: Vec<u8>) -> Result<()> {
ensure!(response_bytes.len() <= 16384, "HELPER_TIME_RESPONSE_BOUND");
let reply = self
.time_call(
ipc::Operation::TimeComplete {
generation,
response_bytes,
},
Duration::from_secs(1),
)
.await?;
ensure!(
matches!(reply.body, ipc::ReplyBody::TimeCompleted {}),
"HELPER_TIME_COMPLETE_DENIED"
);
Ok(())
}
pub async fn time_close(&self, generation: u64) -> Result<()> {
let reply = self
.time_call(
ipc::Operation::TimeClose { generation },
Duration::from_secs(1),
)
.await?;
ensure!(
matches!(reply.body, ipc::ReplyBody::TimeClosed {}),
"HELPER_TIME_CLOSE_UNCONFIRMED"
);
Ok(())
}
async fn call_bounded(
&self,
operation: ipc::Operation,
+114 -10
View File
@@ -18,8 +18,8 @@
//! 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::{
clock::NativeClock,
helper_ipc::{self as ipc, Call, Operation, PeerPin, Pin, PinnedFile, Reply, ReplyBody},
signed_clock::{BoundClock, RuntimeClock},
};
use anyhow::{Context, Result, ensure};
use fs2::FileExt;
@@ -31,6 +31,7 @@ use rmm_agent_core::{
NoStartGuard,
},
ledger,
reconcile::SyncClock as _,
};
use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, hash};
use rusqlite::{Connection, OptionalExtension};
@@ -836,7 +837,7 @@ pub struct SystemHelper {
files: Vec<PinnedFile>,
guard: LedgerGuard,
db: Connection,
clock: NativeClock,
clock: BoundClock,
boot: WindowsBoot,
sync: Option<HelperSync<DalekVerifier>>,
last_diagnostic: Option<Instant>,
@@ -849,7 +850,7 @@ impl SystemHelper {
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 = NativeClock::new();
let clock = 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()
@@ -950,6 +951,11 @@ impl SystemHelper {
"SYSTEM_CALL_BINDING"
);
let response: Result<ReplyBody> = match &call.operation {
Operation::TimeBegin { .. }
| Operation::TimeComplete { .. }
| Operation::TimeClose { .. } => {
anyhow::bail!("SYSTEM_TIME_PIPE_REQUIRED")
}
Operation::Probe {} => {
let ready = self.settings.enable_effects
&& self
@@ -969,6 +975,7 @@ impl SystemHelper {
})
}
Operation::Snapshot { generation } => {
self.clock = self.clock.for_generation(*generation);
self.sync()?;
let snapshot = self.sync.as_mut().unwrap().snapshot(
&mut self.db,
@@ -983,6 +990,10 @@ impl SystemHelper {
response,
request_bytes,
} => {
let decision: rmm_domain::reconciliation::ReconcileDecisionPayload =
serde_json::from_slice(&response.decision_bytes)?;
self.clock
.require_generation(decision.connection_generation)?;
self.sync()?;
let value = self.sync.as_mut().unwrap().apply(
&mut self.db,
@@ -1094,6 +1105,7 @@ impl SystemHelper {
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)?;
@@ -1167,12 +1179,19 @@ impl SystemHelper {
recorded_at,
)?;
self.sync.as_mut().unwrap().close();
let outcome = provider.execute(Duration::from_secs(job.max_runtime_seconds.into()), || {
self.recheck()?;
peer.check()?;
verified_window(&self.settings.binding, request, &self.clock)?;
Ok(())
});
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)?;
@@ -1228,6 +1247,7 @@ impl SystemHelper {
|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(
@@ -1243,8 +1263,13 @@ impl SystemHelper {
Ok(())
},
);
let outcome =
let mut outcome =
result.unwrap_or_else(|_| Outcome::unknown("SYSTEM_SCRIPT_EFFECT_UNRESOLVED"));
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)?;
@@ -1528,6 +1553,12 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
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 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);
while !STOP.load(Ordering::SeqCst) {
// A failed observation keeps the owned slot and its handles locked.
@@ -1558,10 +1589,83 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
}
}
}
// 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"],
+223 -14
View File
@@ -35,7 +35,7 @@ struct Config {
transport: String,
#[serde(default)]
job_binding_file: Option<PathBuf>,
// False until the independent LocalService clock qualification is complete.
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
#[serde(default)]
enable_jobs: bool,
}
@@ -123,14 +123,95 @@ async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
}
#[derive(Clone)]
struct JobClock {
native: Arc<rmm_agent_windows::clock::NativeClock>,
#[cfg(feature = "system-helper")]
native: rmm_agent_windows::signed_clock::BoundClock,
enabled: bool,
}
impl JobClock {
fn new(enabled: bool) -> Self {
Self {
#[cfg(feature = "system-helper")]
native: rmm_agent_windows::signed_clock::RuntimeClock::new(
rmm_time_attestation::Role::Agent,
)
.for_generation(0),
enabled,
}
}
fn for_generation(&self, generation: u64) -> Self {
#[cfg(feature = "system-helper")]
{
Self {
native: self.native.for_generation(generation),
enabled: self.enabled,
}
}
#[cfg(not(feature = "system-helper"))]
{
let _ = generation;
self.clone()
}
}
}
impl SyncClock for JobClock {
fn now(&self) -> Result<chrono::DateTime<Utc>> {
ensure!(self.enabled, "WINDOWS_JOBS_NOT_ENABLED");
self.native.now()
Ok(self.reading()?.own_wall)
}
fn reading(&self) -> Result<reconcile::ClockReading> {
ensure!(self.enabled, "WINDOWS_JOBS_NOT_ENABLED");
#[cfg(feature = "system-helper")]
{
self.native.reading()
}
#[cfg(not(feature = "system-helper"))]
{
anyhow::bail!("WINDOWS_SIGNED_TIME_NOT_CONFIGURED")
}
}
}
#[cfg(feature = "system-helper")]
struct TimeRefresh {
generation: u64,
stop: Arc<AtomicBool>,
clock: rmm_agent_windows::signed_clock::RuntimeClock,
helper: Option<rmm_agent_windows::helper_runtime::Client>,
tasks: Vec<tokio::task::JoinHandle<()>>,
}
#[cfg(feature = "system-helper")]
impl Drop for TimeRefresh {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
let _ = self.clock.close_generation(self.generation);
for task in &self.tasks {
task.abort();
}
}
}
#[cfg(feature = "system-helper")]
async fn time_response(
client: &reqwest::Client,
address: std::net::SocketAddr,
request: &rmm_time_attestation::Request,
) -> Result<Vec<u8>> {
request.validate()?;
ensure!(
crate::https_channel::server_name()? == "discovery.ease-technologies.de",
"TIME_FIXED_SERVER"
);
tokio::time::timeout(Duration::from_millis(650), async {
let response = client
.post(format!(
"https://discovery.ease-technologies.de:{}/agent/v1/time-attestation",
address.port()
))
.timeout(Duration::from_millis(650))
.json(request)
.send()
.await?;
crate::https_channel::bounded_body(response, 16384, "application/json").await
})
.await
.context("TIME_HTTP_DEADLINE")?
}
#[derive(Default)]
struct EffectFence {
@@ -150,9 +231,9 @@ impl EffectFence {
(!helper || self.helper_generation.load(Ordering::SeqCst) == generation)
&& self.generation.load(Ordering::SeqCst) == generation
&& generation > 0
&& clock.now().is_ok_and(|now| {
(now + chrono::Duration::seconds(2)).timestamp_millis()
< self.deadline.load(Ordering::SeqCst)
&& clock.reading().is_ok_and(|reading| {
reading.own_wall.timestamp_millis() < self.deadline.load(Ordering::SeqCst)
&& reading.upper.timestamp_millis() < self.deadline.load(Ordering::SeqCst)
})
}
}
@@ -337,6 +418,8 @@ struct Agent {
ledger: Option<Connection>,
_ledger_file: Option<fs::File>,
clock: JobClock,
#[cfg(feature = "system-helper")]
time_refresh: Option<TimeRefresh>,
sync: Option<reconcile::ClientSync>,
prepared: bool,
#[cfg(feature = "system-helper")]
@@ -365,6 +448,121 @@ struct Agent {
deferred_permit: Option<(u64, ExecutionPermit)>,
}
impl Agent {
#[cfg(feature = "system-helper")]
fn start_time_refresh(
&mut self,
generation: u64,
identity: &crate::certificate_rotation::DeviceIdentity,
) -> Result<()> {
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
if !self.config.enable_jobs {
return Ok(());
}
let client = crate::https_channel::mtls_client(
self.config.connect_address,
&self.ca,
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let helper = 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();
let own_clock = clock.clone();
let own_stop = stop.clone();
let own_http = client.clone();
let address = self.config.connect_address;
tasks.push(tokio::spawn(async move {
while !own_stop.load(Ordering::SeqCst) {
let result = async {
if !own_clock.configured_for(generation) {
own_clock.open_connection(generation).await?;
}
let request = own_clock.begin(generation)?;
let bytes = time_response(&own_http, address, &request).await?;
ensure!(!own_stop.load(Ordering::SeqCst), "TIME_CONNECTION_CLOSED");
own_clock.complete(generation, &bytes)
}
.await;
if result.is_err() {
let _ = own_clock.close_generation(generation);
}
tokio::time::sleep(if result.is_ok() {
Duration::from_millis(20)
} else {
Duration::from_millis(500)
})
.await;
}
let _ = own_clock.close_generation(generation);
}));
if let Some(time_helper) = helper.clone() {
let helper_stop = stop.clone();
tasks.push(tokio::spawn(async move {
while !helper_stop.load(Ordering::SeqCst) {
let result = async {
let request = time_helper.time_begin(generation).await?;
let bytes = time_response(&client, address, &request).await?;
ensure!(
!helper_stop.load(Ordering::SeqCst),
"TIME_CONNECTION_CLOSED"
);
time_helper.time_complete(generation, bytes).await
}
.await;
if result.is_err() {
let _ = time_helper.time_close(generation).await;
}
tokio::time::sleep(if result.is_ok() {
Duration::from_millis(20)
} else {
Duration::from_millis(500)
})
.await;
}
let _ = time_helper.time_close(generation).await;
}));
}
self.time_refresh = Some(TimeRefresh {
generation,
stop,
clock,
helper,
tasks,
});
Ok(())
}
#[cfg(feature = "system-helper")]
async fn stop_time_refresh(&mut self) {
let Some(refresh) = self.time_refresh.take() else {
return;
};
refresh.stop.store(true, Ordering::SeqCst);
let _ = refresh.clock.close_generation(refresh.generation);
for task in &refresh.tasks {
task.abort();
}
if let Some(helper) = &refresh.helper {
let until = Instant::now() + Duration::from_millis(1200);
loop {
if helper.time_close(refresh.generation).await.is_ok() {
break;
}
if Instant::now() >= until {
// No successful remote fence is asserted after a lost or
// busy call; local effects are already closed independently.
eprintln!("HELPER_TIME_CLOSE_UNCONFIRMED");
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
}
fn close_gate(&mut self) {
self.fence.close();
#[cfg(feature = "system-helper")]
@@ -609,9 +807,9 @@ impl Agent {
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
caps.push("agent.update/1".into());
if self.config.enable_jobs
&& cfg!(feature = "system-helper")
&& self.binding.is_some()
&& native::require_local_service().is_ok()
&& self.clock.now().is_ok()
{
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
if rmm_agent_windows::actions::powershell().is_ok() {
@@ -1157,7 +1355,7 @@ impl Agent {
let work_grant = grant.clone();
let original_boot = Uuid::parse_str(&self.boot)?;
let worker = tokio::task::spawn_blocking(move || {
let outcome = (|| -> Result<Outcome> {
let mut outcome = (|| -> Result<Outcome> {
if !fence.allows(generation, &clock)
|| verified_window(&binding, &request, &clock).is_err()
{
@@ -1200,6 +1398,13 @@ impl Agent {
prepared.run(&job, &worker_cancel)
})()
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
if outcome.state == "succeeded" && clock.reading().is_err() {
// Use this worker's original connection-bound clock, never a
// newer session's evidence when its retained outcome is drained.
outcome.state = "unknown".into();
outcome.error_code = "WINDOWS_FINAL_CLOCK_UNTRUSTED".into();
outcome.evidence["postconditions_passed"] = false.into();
}
let _ = completed.blocking_send((work_offer, work_grant, outcome));
});
self.running = Some(Running {
@@ -1283,6 +1488,8 @@ impl Agent {
self.close_gate();
let result = self.session_inner(stop).await;
self.close_gate();
#[cfg(feature = "system-helper")]
self.stop_time_refresh().await;
result
}
async fn session_inner(&mut self, stop: &AtomicBool) -> Result<()> {
@@ -1331,6 +1538,9 @@ impl Agent {
generation > 0 && server.max_message_bytes == rmm_domain::MAX_MESSAGE as u32,
"SERVER_LIMITS"
);
self.clock = self.clock.for_generation(generation);
#[cfg(feature = "system-helper")]
self.start_time_refresh(generation, &identity)?;
self.queue_inventory(generation)?;
self.queue_update_observation(generation)?;
self.replay(&channel, generation).await?;
@@ -1510,7 +1720,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
}
ensure!(!config.enable_jobs || binding.is_some(),"ENABLED_JOBS_REQUIRE_BINDING");
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{native:Arc::new(rmm_agent_windows::clock::NativeClock::new()),enabled:config.enable_jobs};
let clock=JobClock::new(config.enable_jobs);
let sync=if config.enable_jobs {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
@@ -1522,6 +1732,8 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")]
time_refresh:None,
#[cfg(feature="system-helper")]
prepared_request:None,
#[cfg(feature="system-helper")]
helper_lane:Arc::new(tokio::sync::Semaphore::new(1)),
@@ -1713,10 +1925,7 @@ mod tests {
let config:Config=serde_json::from_value(serde_json::json!({"server_name":"example.invalid","connect_address":"127.0.0.1:443","ca_file":"C:/fixture/ca.pem","state_directory":"C:/fixture/state","enrollment_token_file":"C:/fixture/token","transport":"auto"})).unwrap();
assert!(!config.enable_jobs);
assert!(config.job_binding_file.is_none());
let clock = JobClock {
native: Arc::new(rmm_agent_windows::clock::NativeClock::new()),
enabled: config.enable_jobs,
};
let clock = JobClock::new(config.enable_jobs);
assert_eq!(
clock.now().unwrap_err().to_string(),
"WINDOWS_JOBS_NOT_ENABLED"
+123 -4
View File
@@ -1,6 +1,7 @@
//! Independent signed time comparison for the Windows agent and SYSTEM helper.
//! This module does not implement SyncClock, advertise a capability, start a job,
//! change W32Time or replace the still-closed legacy NativeClock adapter.
//! Runtime readers use only their own fresh evidence and protected connection.
//! No provisioning, W32Time change or job authorization occurs here; the legacy
//! RPC adapter remains closed and is never a runtime fallback.
#![cfg(any(test, all(windows, feature = "system-helper")))]
use anyhow::{Result, ensure};
use rmm_time_attestation::Sample;
@@ -414,7 +415,7 @@ mod installed {
collections::BTreeMap,
io::Read,
path::Path,
sync::{Mutex, OnceLock},
sync::{Arc, Mutex, OnceLock},
};
pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\time-attestation.json";
@@ -812,6 +813,122 @@ mod installed {
}
}
/// Shared only inside one installed process. HTTP/IPC receives no access to
/// this slot or to its clock readings; its control surface is nonce/bytes.
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
}
#[derive(Clone)]
pub struct BoundClock {
source: RuntimeClock,
generation: u64,
}
impl RuntimeClock {
pub fn new(role: Role) -> Self {
Self {
role,
state: Arc::new(Mutex::new(None)),
}
}
pub fn for_generation(&self, generation: u64) -> BoundClock {
BoundClock {
source: self.clone(),
generation,
}
}
pub fn configured_for(&self, generation: u64) -> bool {
self.state
.lock()
.is_ok_and(|state| state.as_ref().is_some_and(|(held, _)| *held == generation))
}
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 mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
*state = Some((generation, clock));
Ok(())
}
pub fn begin(&self, generation: u64) -> Result<Request> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NOT_CONFIGURED")?;
ensure!(*held == generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.begin(generation)
}
pub fn complete(&self, generation: u64, bytes: &[u8]) -> Result<()> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NOT_CONFIGURED")?;
ensure!(*held == generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.complete(bytes, |_| Ok(()))
}
pub fn close_generation(&self, generation: u64) -> Result<()> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
if state.as_ref().is_some_and(|(held, _)| *held == generation) {
state.take(); // Drop fences this instance's pending/evidence.
}
Ok(())
}
pub fn close(&self) -> Result<()> {
self.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?
.take();
Ok(())
}
}
impl BoundClock {
pub fn source(&self) -> RuntimeClock {
self.source.clone()
}
pub fn for_generation(&self, generation: u64) -> Self {
self.source.for_generation(generation)
}
pub fn require_generation(&self, generation: u64) -> Result<()> {
ensure!(
self.generation == generation && generation > 0,
"TIME_RUNTIME_GENERATION"
);
Ok(())
}
}
impl rmm_agent_core::reconcile::SyncClock for BoundClock {
fn now(&self) -> Result<chrono::DateTime<chrono::Utc>> {
Ok(self.reading()?.own_wall)
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
let mut state = self
.source
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NO_EVIDENCE")?;
ensure!(*held == self.generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.with_current_comparison(|value| {
let own_wall = chrono::DateTime::from_timestamp_nanos(value.wall_utc_ns());
let upper = chrono::DateTime::from_timestamp_nanos(value.interval().upper_utc_ns());
Ok(rmm_agent_core::reconcile::ClockReading {
own_wall,
upper: upper.max(own_wall),
})
})
}
}
/// Borrowed only inside a completion/current-comparison callback, never returned as a
/// storable clock/lease/permit. Runtime callers must retain all job gates.
pub struct Comparison {
@@ -828,7 +945,9 @@ mod installed {
}
}
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{CONFIG_PATH, Calibration, Comparison, Configuration, SignedClock};
pub use installed::{
BoundClock, CONFIG_PATH, Calibration, Comparison, Configuration, RuntimeClock, SignedClock,
};
#[cfg(test)]
mod tests {