Integrate independent signed Windows clocks with native Linux lease guards
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -881,7 +881,8 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
) -> bool {
|
||||
let result = (|| -> Result<bool> {
|
||||
guard.check(db)?;
|
||||
let now = clock.now()?;
|
||||
let reading = clock.reading()?;
|
||||
let now = reading.own_wall;
|
||||
let Some(lease) = &self.lease else {
|
||||
return Ok(false);
|
||||
};
|
||||
@@ -899,6 +900,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
&& meta.decision == Some(lease.decision_id)
|
||||
&& generation == lease.generation
|
||||
&& now < lease.until
|
||||
&& reading.upper < lease.until
|
||||
&& now >= self.born
|
||||
&& boot.current_boot()? == lease.boot_id
|
||||
&& ledger_fingerprint(db)? == lease.fingerprint
|
||||
|
||||
@@ -21,8 +21,23 @@ use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A fresh observation returned by the trusted local clock implementation,
|
||||
/// never an IPC DTO or an execution permit. Callers must not retain it as a lease.
|
||||
pub struct ClockReading {
|
||||
pub own_wall: DateTime<Utc>,
|
||||
pub upper: DateTime<Utc>,
|
||||
}
|
||||
pub trait SyncClock {
|
||||
fn now(&self) -> Result<DateTime<Utc>>;
|
||||
/// Existing providers retain their existing point-clock contract. Providers
|
||||
/// with an independently verified interval override this atomically.
|
||||
fn reading(&self) -> Result<ClockReading> {
|
||||
let own_wall = self.now()?;
|
||||
Ok(ClockReading {
|
||||
own_wall,
|
||||
upper: own_wall,
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Channel {
|
||||
@@ -108,14 +123,15 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
self.gate.as_ref().map(|gate| gate.until)
|
||||
}
|
||||
pub fn can_start(&self, channel: &Channel, root: bool, clock: &impl SyncClock) -> bool {
|
||||
let Ok(now) = clock.now() else {
|
||||
let Ok(reading) = clock.reading() else {
|
||||
return false;
|
||||
};
|
||||
self.gate.as_ref().is_some_and(|g| {
|
||||
g.channel == *channel
|
||||
&& g.ready
|
||||
&& g.local_applied
|
||||
&& now < g.until
|
||||
&& reading.own_wall < g.until
|
||||
&& reading.upper < g.until
|
||||
&& (!root || (g.helper_ready && g.helper.is_none()))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1010,6 +1010,44 @@ fn clean_ready_shared_lock_and_reopen_start_closed() {
|
||||
assert!(!sync.can_start(&f.db, &f.guard, 1, &f.clock, &f.boot));
|
||||
}
|
||||
#[test]
|
||||
fn system_helper_lease_denies_interval_upper_at_or_after_deadline() {
|
||||
struct IntervalClock {
|
||||
wall: DateTime<Utc>,
|
||||
upper: DateTime<Utc>,
|
||||
}
|
||||
impl Clock for IntervalClock {
|
||||
fn now(&self) -> anyhow::Result<DateTime<Utc>> {
|
||||
Ok(self.wall)
|
||||
}
|
||||
fn reading(&self) -> anyhow::Result<rmm_agent_core::reconcile::ClockReading> {
|
||||
Ok(rmm_agent_core::reconcile::ClockReading {
|
||||
own_wall: self.wall,
|
||||
upper: self.upper,
|
||||
})
|
||||
}
|
||||
}
|
||||
for overshoot in [Duration::zero(), Duration::nanoseconds(1)] {
|
||||
let mut f = Fixture::new();
|
||||
f.identity = HelperIdentity::System;
|
||||
let mut sync = f.sync();
|
||||
let snapshot = f.snapshot(&mut sync, 1);
|
||||
let raw = f.request(&snapshot);
|
||||
let decision = f.decision(&snapshot, &raw, 1, true);
|
||||
assert!(f.apply(&mut sync, &decision, &raw).unwrap().ready);
|
||||
let wall = decision.valid_until - Duration::milliseconds(10);
|
||||
let point = TestClock {
|
||||
now: wall,
|
||||
trusted: true,
|
||||
};
|
||||
assert!(sync.can_start(&f.db, &f.guard, 1, &point, &f.boot));
|
||||
let bounded = IntervalClock {
|
||||
wall,
|
||||
upper: decision.valid_until + overshoot,
|
||||
};
|
||||
assert!(!sync.can_start(&f.db, &f.guard, 1, &bounded, &f.boot));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn exact_signatures_fake_key_wrong_domain_and_all_identity_bindings() {
|
||||
let mut f = Fixture::new();
|
||||
let mut sync = f.sync();
|
||||
|
||||
@@ -17,6 +17,48 @@ struct Clock {
|
||||
now: DateTime<Utc>,
|
||||
trusted: bool,
|
||||
}
|
||||
#[test]
|
||||
fn client_lease_requires_entire_fresh_upper_before_deadline() {
|
||||
struct IntervalClock {
|
||||
wall: DateTime<Utc>,
|
||||
upper: DateTime<Utc>,
|
||||
}
|
||||
impl SyncClock for IntervalClock {
|
||||
fn now(&self) -> anyhow::Result<DateTime<Utc>> {
|
||||
Ok(self.wall)
|
||||
}
|
||||
fn reading(&self) -> anyhow::Result<ClockReading> {
|
||||
Ok(ClockReading {
|
||||
own_wall: self.wall,
|
||||
upper: self.upper,
|
||||
})
|
||||
}
|
||||
}
|
||||
let mut f = Fixture::new();
|
||||
let mut client = f.client();
|
||||
let prepared = f.prepare(&mut client);
|
||||
let decision = f.decision(&prepared, true);
|
||||
f.apply(&mut client, &decision).unwrap();
|
||||
let wall = decision.valid_until - Duration::milliseconds(10);
|
||||
assert!(client.can_start(
|
||||
&f.channel,
|
||||
false,
|
||||
&Clock {
|
||||
now: wall,
|
||||
trusted: true
|
||||
}
|
||||
));
|
||||
for overshoot in [Duration::zero(), Duration::nanoseconds(1)] {
|
||||
assert!(!client.can_start(
|
||||
&f.channel,
|
||||
false,
|
||||
&IntervalClock {
|
||||
wall,
|
||||
upper: decision.valid_until + overshoot
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
impl SyncClock for Clock {
|
||||
fn now(&self) -> anyhow::Result<DateTime<Utc>> {
|
||||
anyhow::ensure!(self.trusted, "CLOCK_UNTRUSTED");
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Frozen four lease guards on Linux; two fixed ELFs, no product clocks or service actions.
|
||||
|
||||
Prepare copies the independently reviewed snapshot locally. Execute is one
|
||||
root-only Cloud-VM fixture run. After any lost reply read the original case;
|
||||
never execute it again or substitute another binary/source generation.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
import windows_msi_runtime_acceptance as support
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
|
||||
QUALIFICATION = ROOT / 'devstate/windows-signed-clock/runtime-qualification-476c0212-4af9-42d2-92ca-1c488d158d21'
|
||||
STATE = ROOT / 'devstate/windows-time-runtime-native-linux'
|
||||
PROFILE = 'rmm.windows-time-runtime.four-linux-guards.v1'
|
||||
RECEIPT_SHA = '8e219d37fef9f1495225b817a62418a4dab240442c0b08724954237e282d1c13'
|
||||
INPUTS_SHA = '505008211630e2b7528cdf085a76309328626fe1e51540170eea293052e53272'
|
||||
ARTIFACTS = {'helper_reconcile': {'filename': 'helper_reconcile-deadline-tests', 'bytes': 7975776, 'sha256': '393c62c0aa8a2850ee88850549d49071811012e18f57347a1b187243a223522f', 'complete_test_list': ['abandon_after_expiry_records_deny_only_evidence_and_requires_normal_signed_unlock', 'abandon_preserves_existing_known_unknown_missing_start_and_foreign_request_rows', 'abandon_rejects_wrong_signature_scope_clock_boot_lineage_instance_and_dispatch_proof', 'abandon_storage_failure_rolls_back_consumption_start_and_outcome_together', 'both_live_profiles_apply_one_signature_and_checkpoint_without_inheriting_readiness', 'checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor', 'checkpoint_rollback_is_sticky_and_cannot_be_fixed_by_omission', 'clean_ready_shared_lock_and_reopen_start_closed', 'definitive_unlock_is_transactional_idempotent_and_keeps_tombstones', 'exact_signatures_fake_key_wrong_domain_and_all_identity_bindings', 'false_clock_expiry_and_invalid_independent_key_stay_closed', 'general_and_apt_instances_share_fencing_but_never_inherit_a_process_gate', 'independently_remembered_agent_journal_cannot_be_replaced_by_server_ready', 'malformed_original_protobuf_or_digest_does_not_open_gate', 'missing_signed_checkpoint_history_closes_the_live_gate_stickily', 'mutated_root_ledger_after_capture_is_not_the_signed_snapshot', 'native_stop_intent_is_original_head_bound_create_once_and_transactional', 'old_process_response_fails_after_fresh_capture_even_inside_ttl', 'omitted_unknown_root_row_is_sticky_despite_signed_ready', 'real_local_boot_must_match_signed_reboot_completion', 'restarted_update_can_only_schedule_control_from_its_verified_original_not_unknown', 'root_and_system_are_distinct_explicit_helper_domains', 'shared_database_only_and_missing_local_start_fail_closed', 'signed_noncanonical_outcome_bytes_do_not_unlock_root_consumption', 'stale_process_connection_does_not_poison_a_new_fenced_process', 'system_helper_lease_denies_interval_upper_at_or_after_deadline', 'targeted_final_unlock_does_not_release_an_unrelated_unknown', 'unknown_code_or_no_result_never_unlocks_even_signed_ready', 'unrelated_action_plan_and_previous_outcome_cannot_unlock', 'update_handoff_consumption_start_and_stop_intent_are_one_transaction', 'update_inflight_negative_control_keeps_every_start_closed_and_owner_loss_is_terminal'], 'selected': ['system_helper_lease_denies_interval_upper_at_or_after_deadline', 'clean_ready_shared_lock_and_reopen_start_closed']}, 'reconcile': {'filename': 'reconcile-deadline-tests', 'bytes': 7084528, 'sha256': '7a7e068e4c832ee139877f84a45283fb2a1101ad3b6626aecd277a14cf97becc', 'complete_test_list': ['accepted_unstarted_keeps_ids_and_never_consumes_or_executes', 'authenticated_helper_outcome_is_imported_as_new_durable_evidence_not_reexecuted', 'clean_reconnect_and_reopen_require_new_signed_challenge', 'client_lease_requires_entire_fresh_upper_before_deadline', 'crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes', 'crash_after_result_commit_before_finish_retains_exact_result_and_local_prior', 'crash_before_running_event_recovers_real_consumption_without_inventing_completion', 'definite_nonstart_result_is_unconsumed_not_ambiguous', 'exact_signatures_all_identity_channel_checkpoint_and_request_bindings', 'final_result_preserves_original_envelope_outputs_and_exact_acks', 'foreign_ack_and_noncanonical_outcome_are_transactionally_rejected', 'helper_gate_requires_exact_signed_instruction_and_applied_checkpoint', 'helper_omitting_a_consumed_root_attempt_is_a_sticky_restore_fault', 'independent_helper_checkpoint_regression_is_sticky', 'independent_local_outcome_mismatch_never_unlocks', 'missing_server_job_fault_is_sticky_even_if_attempt_disappears_later', 'negative_server_revision_never_rolls_back_local_unknown_revision', 'original_completion_after_reconnect_unknown_is_recovered_without_reexecuting', 'reboot_keeps_lock_until_signed_new_authenticated_boot_inventory_evidence', 'requesting_running_and_omitted_attempts_cannot_regain_readiness', 'rollback_and_false_clock_close_mutations_but_do_not_destroy_journal', 'signed_attempt_mutation_or_terminal_regression_is_rejected', 'signed_terminal_nonstart_stays_unconsumed_across_sync_and_pending_denial', 'signed_unlock_still_rejects_a_missing_local_outcome_in_legacy_crash_window', 'system_helper_import_requires_explicit_system_identity_and_never_root_alias', 'terminal_labels_never_override_grant_consumption_or_unclear_attempts', 'uncertain_request_preserves_pending_request_and_last_applied_anchor'], 'selected': ['client_lease_requires_entire_fresh_upper_before_deadline', 'definite_nonstart_result_is_unconsumed_not_ambiguous']}}
|
||||
AGENT_SHA = '0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f'
|
||||
HELPER_SHA = '79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf'
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def save_local(path, value):
|
||||
support.save(path, value)
|
||||
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def copy_exact(source, destination, digest, size):
|
||||
metadata = source.lstat()
|
||||
support.require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1
|
||||
and metadata.st_uid in (0, os.getuid()) and not metadata.st_mode & 0o002
|
||||
and metadata.st_size == size and size <= (16 if source.name.endswith('-deadline-tests') else 2) * 1024 * 1024, 'bounded regular frozen input')
|
||||
raw = source.read_bytes()
|
||||
support.require(sha(raw) == digest, 'frozen snapshot input hash')
|
||||
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
support.private(destination.parent, True)
|
||||
fd = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||
fd = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def verify_case(folder):
|
||||
value = support.load(folder / 'manifest.json')
|
||||
support.require(value['profile'] == PROFILE and value['artifacts'] == ARTIFACTS
|
||||
and value['runner_sha256'] == sha(Path(__file__).read_bytes())
|
||||
and value['receipt_sha256'] == RECEIPT_SHA, 'same original reviewed manifest')
|
||||
support.require(sha((folder / 'receipt.json').read_bytes()) == RECEIPT_SHA
|
||||
and sha((folder / 'inputs.json').read_bytes()) == INPUTS_SHA, 'original qualification provenance')
|
||||
source = support.load(folder / 'inputs.json')
|
||||
support.require(len(source) == 202 and source == value['source_files'], 'exact frozen 202 compiler inputs')
|
||||
paths = set()
|
||||
for item in source:
|
||||
path = Path(item['path'])
|
||||
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique relative frozen source')
|
||||
paths.add(str(path)); file = folder / 'source' / path
|
||||
support.private(file)
|
||||
support.require(file.stat().st_size == item['bytes'] and sha(file.read_bytes()) == item['sha256'], 'retained source freeze')
|
||||
for item in ARTIFACTS.values():
|
||||
binary = folder / item['filename']; support.private(binary)
|
||||
support.require(binary.stat().st_size == item['bytes'] and sha(binary.read_bytes()) == item['sha256'], 'original qualified ELF')
|
||||
for path, digest in value['transport_sources'].items():
|
||||
support.require(sha((ROOT / path).read_bytes()) == digest, 'original strict transport source')
|
||||
return value
|
||||
|
||||
|
||||
def remote(p):
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import selectors
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
|
||||
def enc(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
|
||||
|
||||
def create(path, raw, mode=0o600):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||
fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def run(args, timeout=20):
|
||||
# Keep the owned group leader unreaped until its entire group has been
|
||||
# cleaned up. Its PID therefore cannot be recycled before killpg.
|
||||
child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, start_new_session=True,
|
||||
env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent', 'TMPDIR': str(folder / 'tmp')})
|
||||
selector = selectors.DefaultSelector()
|
||||
buffers = {'stdout': bytearray(), 'stderr': bytearray()}
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
for stream, name in ((child.stdout, 'stdout'), (child.stderr, 'stderr')):
|
||||
os.set_blocking(stream.fileno(), False); selector.register(stream, selectors.EVENT_READ, name)
|
||||
while True:
|
||||
require(time.monotonic() < deadline, 'owned native command timeout; read original case only')
|
||||
for key, _ in selector.select(0.02):
|
||||
raw = os.read(key.fileobj.fileno(), 4096)
|
||||
if raw:
|
||||
buffers[key.data].extend(raw)
|
||||
require(len(buffers[key.data]) <= 65536, 'bounded native output')
|
||||
else:
|
||||
selector.unregister(key.fileobj)
|
||||
ended = os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
|
||||
if ended is not None:
|
||||
# Child remains a zombie until finally: no PID/group reuse.
|
||||
os.killpg(child.pid, signal.SIGKILL)
|
||||
for key in list(selector.get_map().values()):
|
||||
while True:
|
||||
try:
|
||||
raw = os.read(key.fileobj.fileno(), 4096)
|
||||
except BlockingIOError:
|
||||
break
|
||||
if not raw:
|
||||
break
|
||||
buffers[key.data].extend(raw)
|
||||
require(len(buffers[key.data]) <= 65536, 'bounded native output')
|
||||
code = ended.si_status if ended.si_code == os.CLD_EXITED else -ended.si_status
|
||||
return code, bytes(buffers['stdout']), bytes(buffers['stderr'])
|
||||
finally:
|
||||
os.killpg(child.pid, signal.SIGKILL)
|
||||
child.wait()
|
||||
selector.close(); child.stdout.close(); child.stderr.close()
|
||||
|
||||
def metadata_identity(value):
|
||||
return (value.st_dev, value.st_ino, value.st_uid, value.st_gid, value.st_mode,
|
||||
value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
|
||||
|
||||
def hashed(path, maximum, process_image=False):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | (0 if process_image else os.O_NOFOLLOW))
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno()); require(stat.S_ISREG(before.st_mode) and before.st_size <= maximum, 'bounded witness file')
|
||||
digest = hashlib.sha256(); total = 0
|
||||
while True:
|
||||
raw = stream.read(32768)
|
||||
if not raw:
|
||||
break
|
||||
total += len(raw); require(total <= maximum, 'bounded witness hash'); digest.update(raw)
|
||||
after = os.fstat(stream.fileno())
|
||||
require(metadata_identity(before) == metadata_identity(after) and total == before.st_size, 'stable witness hash')
|
||||
return before, digest.hexdigest()
|
||||
|
||||
def witness():
|
||||
out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}}
|
||||
release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line)
|
||||
require(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'fixed native Ubuntu24.04')
|
||||
out['os'] = {'id': 'ubuntu', 'version': '24.04', 'machine': os.uname().machine, 'kernel': os.uname().release}
|
||||
for name, uid, binary in (
|
||||
('rmm-agent-remote.service', 993, p['agent_sha256']),
|
||||
('rmm-helper-cloud.service', 0, p['helper_sha256']),
|
||||
('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])):
|
||||
code, stdout, _ = run(['/usr/bin/systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState', '-p', 'InvocationID'])
|
||||
require(code == 0, 'existing service read')
|
||||
service = dict(line.split('=', 1) for line in stdout.decode().splitlines())
|
||||
pid = int(service['MainPID']); require(service['ActiveState'] == 'active' and pid > 1, 'three existing services active')
|
||||
proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19]
|
||||
ids = {line.split(':')[0]: line.split()[1:] for line in (proc / 'status').read_text().splitlines() if line.startswith(('Uid:', 'Gid:'))}
|
||||
metadata, image = hashed(proc / 'exe', 256 * 1024 * 1024, process_image=True)
|
||||
current = (proc / 'exe').stat()
|
||||
require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary
|
||||
and (metadata.st_dev, metadata.st_ino) == (current.st_dev, current.st_ino)
|
||||
and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'current generation/account/image')
|
||||
out['services'][name] = dict(service, birth=birth, image=image, ids=ids)
|
||||
code, stdout, _ = run(['/usr/bin/systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState'])
|
||||
apt = dict(line.split('=', 1) for line in stdout.decode().splitlines())
|
||||
require(code == 0 and apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed')
|
||||
out['apt'] = apt
|
||||
for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json',
|
||||
'/etc/rmm-remote/full-maintenance-helper-proof.json', '/etc/systemd/system/rmm-full-maintenance-helper.service'):
|
||||
path = Path(name); metadata = path.lstat()
|
||||
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_uid == 0
|
||||
and not metadata.st_mode & 0o022 and metadata.st_nlink == 1, 'protected known control')
|
||||
current, digest = hashed(path, 65536)
|
||||
require(metadata_identity(current) == metadata_identity(metadata), 'same known control file')
|
||||
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode,
|
||||
metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns, digest]
|
||||
for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock',
|
||||
'/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite'):
|
||||
path = Path(name); metadata = path.lstat()
|
||||
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1, 'existing state identity')
|
||||
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode]
|
||||
return out
|
||||
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root contract fixtures')
|
||||
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case')
|
||||
folder = Path('/var/tmp') / ('rmm-windows-time-runtime-linux-' + ident)
|
||||
require(p['action'] in ('execute', 'read'), 'fixed once/read actions')
|
||||
if p['action'] == 'read':
|
||||
metadata = folder.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and not folder.is_symlink() and metadata.st_uid == 0
|
||||
and stat.S_IMODE(metadata.st_mode) == 0o700, 'own original case only')
|
||||
intent = json.loads((folder / 'intent.json').read_bytes())
|
||||
require(intent == {key:value for key,value in p.items() if key not in ('action','binary_b64')}, 'same original payload binding')
|
||||
result = folder / 'result.json'
|
||||
return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(),
|
||||
'result': json.loads(result.read_bytes()) if result.exists() else None, 'current_witness': witness()}
|
||||
os.umask(0o077); folder.mkdir(mode=0o700)
|
||||
create(folder / 'intent.json', enc({key:value for key,value in p.items() if key not in ('action','binary_b64')}))
|
||||
(folder / 'tmp').mkdir(mode=0o700)
|
||||
commands = {}
|
||||
for kind, item in p['artifacts'].items():
|
||||
require(len(p['binary_b64'][kind]) == 4 * ((item['bytes'] + 2) // 3), 'bounded exact ELF transfer')
|
||||
raw = base64.b64decode(p['binary_b64'][kind], validate=True)
|
||||
require(len(raw) == item['bytes'] and hashlib.sha256(raw).hexdigest() == item['sha256'], 'fixed qualified ELF')
|
||||
binary = folder / item['filename']; create(binary, raw, 0o700)
|
||||
commands[kind] = ['/usr/bin/setpriv', '--reuid=0', '--regid=0', '--clear-groups', '--no-new-privs', str(binary)]
|
||||
before = witness(); create(folder / 'before.json', enc(before))
|
||||
for kind, command in commands.items():
|
||||
code, stdout, stderr = run(command + ['--list', '--format', 'terse'])
|
||||
create(folder / (kind + '-list.stdout'), stdout); create(folder / (kind + '-list.stderr'), stderr)
|
||||
lines = stdout.decode().splitlines(); item = p['artifacts'][kind]
|
||||
require(code == 0 and stderr == b'' and len(lines) == len(item['complete_test_list'])
|
||||
and all(line.endswith(': test') for line in lines)
|
||||
and sorted(line[:-6] for line in lines) == item['complete_test_list'], 'complete fixed lists before any test')
|
||||
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
|
||||
runs = []
|
||||
for kind, command in commands.items():
|
||||
item = p['artifacts'][kind]; filtered = len(item['complete_test_list']) - 1
|
||||
for name in item['selected']:
|
||||
code, stdout, stderr = run(command + ['--exact', name, '--test-threads=1', '--nocapture'])
|
||||
create(folder / (name + '.stdout'), stdout); create(folder / (name + '.stderr'), stderr)
|
||||
require(code == 0 and stderr == b'' and ('1 passed; 0 failed; 0 ignored; 0 measured; '+str(filtered)+' filtered out').encode() in stdout
|
||||
and ('test '+name+' ... ok').encode() in stdout, 'one exact selected guard passed')
|
||||
runs.append({'kind':kind,'test':name,'passed':1,'filtered':filtered,'stdout_sha256':hashlib.sha256(stdout).hexdigest()})
|
||||
after = witness(); create(folder / 'after.json', enc(after))
|
||||
require(before == after and len(runs) == 4, 'four guards and retained target state')
|
||||
receipt = dict(id=ident, profile=p['profile'], passed=4, ignored=0, filtered=sum(x['filtered'] for x in runs), execution_uid=0,
|
||||
runs=runs, artifacts=p['artifacts'], before=before, after=after,
|
||||
source_receipt_sha256=p['receipt_sha256'], source_manifest_sha256=p['manifest_sha256'],
|
||||
no_rmm_jobs=True, no_product_time_query=True, no_apply=True, no_service_control=True)
|
||||
create(folder / 'result.json', enc(receipt)); return receipt
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('prepare','execute','read')); parser.add_argument('--case')
|
||||
args=parser.parse_args(); os.umask(0o077)
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=True); support.private(STATE, True)
|
||||
if args.action == 'prepare':
|
||||
support.require(args.case is None, 'new local case only')
|
||||
receipt_path=QUALIFICATION/'receipt.json'; support.private(receipt_path)
|
||||
support.require(sha(receipt_path.read_bytes()) == RECEIPT_SHA, 'exact original local qualification')
|
||||
receipt=support.load(receipt_path); original=support.load(QUALIFICATION/'inputs.json')
|
||||
support.require(sha((QUALIFICATION/'inputs.json').read_bytes()) == INPUTS_SHA and len(original)==202
|
||||
and receipt['inputs_sha256']==INPUTS_SHA and receipt['checks']['linux_selected_guards']==4, 'frozen 202-input four-guard proof')
|
||||
ident=str(uuid.uuid4()); folder=STATE/ident; folder.mkdir(mode=0o700)
|
||||
copy_exact(receipt_path, folder/'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size)
|
||||
copy_exact(QUALIFICATION/'inputs.json', folder/'inputs.json', INPUTS_SHA, (QUALIFICATION/'inputs.json').stat().st_size)
|
||||
paths=set()
|
||||
for item in original:
|
||||
path=Path(item['path'])
|
||||
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique relative frozen source')
|
||||
paths.add(str(path)); copy_exact(QUALIFICATION/'source'/path, folder/'source'/path, item['sha256'], item['bytes'])
|
||||
for kind,item in ARTIFACTS.items():
|
||||
actual=receipt['linux_tests'][kind]
|
||||
support.require(all(actual[key]==item[key] for key in ('bytes','sha256','complete_test_list','selected'))
|
||||
and actual['binary']==item['filename'] and actual['selected_passed']==2, 'two actual local guards per fixed ELF')
|
||||
copy_exact(QUALIFICATION/item['filename'], folder/item['filename'], item['sha256'],item['bytes'])
|
||||
transports={path:sha((ROOT/path).read_bytes()) for path in ('deploy/windows_msi_runtime_acceptance.py','deploy/vm_access_check.py')}
|
||||
save_local(folder/'manifest.json',dict(id=ident,profile=PROFILE,runner_sha256=sha(Path(__file__).read_bytes()),
|
||||
receipt_sha256=RECEIPT_SHA,artifacts=ARTIFACTS,source_files=original,transport_sources=transports))
|
||||
verify_case(folder); print(json.dumps({'id':ident,'prepared_locally':True})); return
|
||||
support.require(args.case is not None, 'original --case required')
|
||||
ident=str(uuid.UUID(args.case)); support.require(ident==args.case,'same canonical original case')
|
||||
folder=STATE/ident; support.private(folder,True); verify_case(folder)
|
||||
payload=dict(id=ident,action=args.action,profile=PROFILE,artifacts=ARTIFACTS,receipt_sha256=RECEIPT_SHA,
|
||||
manifest_sha256=sha((folder/'manifest.json').read_bytes()),agent_sha256=AGENT_SHA,helper_sha256=HELPER_SHA)
|
||||
if args.action=='execute':
|
||||
save_local(folder/'execute-entered.json',{'once':True,'no_retry':True})
|
||||
payload['binary_b64']={kind:base64.b64encode((folder/item['filename']).read_bytes()).decode() for kind,item in ARTIFACTS.items()}
|
||||
code='import json\n'+inspect.getsource(remote)+'\nprint(json.dumps(remote('+repr(payload)+')))\n'
|
||||
response=support.transport(support.access_settings(ACCESS_ROOT,'linux'),'python3 -',code.encode(),folder,timeout=120)
|
||||
save_local(folder/(args.action+'-'+str(uuid.uuid4())+'.json'),response)
|
||||
result=response.get('result') if args.action=='read' else response
|
||||
if result is not None:
|
||||
support.require(result['source_manifest_sha256']==sha((folder/'manifest.json').read_bytes())
|
||||
and result['source_receipt_sha256']==RECEIPT_SHA and result['artifacts']==ARTIFACTS
|
||||
and result['passed']==4 and result['filtered']==112 and result['before']==result['after'], 'exact original four-guard result')
|
||||
if args.action=='read': support.require(response['current_witness']==result['after'],'same-case retained native state')
|
||||
print(json.dumps({'id':ident,'action':args.action,'passed':None if result is None else result['passed'],
|
||||
'complete':result is not None,'read_only':args.action=='read'}))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -1,5 +1,13 @@
|
||||
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
|
||||
|
||||
**Signierte Windows-Runtimequelle Linux-first geprüft:** Original75a4ee16,
|
||||
vollständige27-/31-Listen, exakt4Guards bestanden/112andere gefiltert;
|
||||
separater Originalread vollständig, bekannte Runtimezeugen erhalten.
|
||||
Eigene Agent-/Helper-Timeworker und strikt frische Upper-Leases im Quellcode,
|
||||
[Belege und offene Pfade](windows-signed-clock-runtime.md). Keine native
|
||||
Windows-Runtimequalifikation, Zeitpins oder Jobfreigabe durch diesen Schritt.
|
||||
|
||||
|
||||
**Windows-Rohcapture einschließlich Cleanup abgeschlossen:** beide Rollen
|
||||
nativ mit128Samples/gebundenemKernelExit0 bestanden, beide eigenen gestoppten
|
||||
Messdienste getrennt gelöscht und Abwesenheit nachgelesen. Abschlussread
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Windows: signierter Zeitvergleich in Agent und SYSTEM-Helper
|
||||
|
||||
Stand 2026-11-15: Quellcode implementiert und lokal geprüft, noch keine native Runtime-Abnahme oder Freischaltung auf der Windows-VM. Die bestehende Genehmigungsgrenze bleibt unverändert: Jeder Wartungsauftrag benötigt seinen persistenten Antrag und die interaktive WebUI-Genehmigung.
|
||||
|
||||
Agent und SYSTEM-Helper besitzen jeweils einen eigenen `SignedClock` mit eigener Challenge, Nonce, geschütztem Kontext und kurzlebiger Evidenz. Zwei getrennte Transportpfade verwenden den wiederverwendeten mTLS-Client zur festen Route `/agent/v1/time-attestation` auf `discovery.ease-technologies.de`. Der Agent transportiert für den Helper ausschließlich dessen Anfrage und signierte Antwortbytes. Er liefert weder Zeitstempel noch einen Readiness-Schalter. Die feste zusätzliche Time-Pipe verwendet dieselbe installierte Peerprüfung; ihr eigener Worker kann keine Ledger- oder Joboperationen ausführen. Ein ausdrückliches `TimeClose` schließt den Helper bei Verbindungsende. Kann dessen Abschluss nicht bestätigt werden, wird das als unbestätigt protokolliert.
|
||||
|
||||
Jede Zeitnutzung erfasst die eigene Windows-Uhr frisch und prüft dieselbe unabhängige Evidenz erneut. Es gelten weiter höchstens 1 s ab Challengebeginn und 100 ms ab nativem Empfang; Nutzung verlängert keine Frist. Agent und Helper prüfen für den Start sowohl ihre eigene Wandzeit als auch die obere Intervallgrenze strikt vor Ablauf der Sync-Lease. Der additive Core-Standard setzt die obere Grenze auf die eigene Wandzeit und erhält damit das bisherige Linux-Verhalten. Verbindungsgebundene Clock-Klone verhindern, dass alte Worker eine neue Verbindung als Zeitnachweis übernehmen. Ein erfolgreicher Skriptabschluss ohne abschließenden eigenen Zeitnachweis wird mit erhaltenen tatsächlichen Ausgaben `unknown`.
|
||||
|
||||
Deklarative Fähigkeiten sind von momentaner Zeitbereitschaft getrennt. Fehlende Pins, Kalibrierung oder Quellqualität bleiben sperrend. Der alte Windows-RPC-Adapter wird nicht als Fallback qualifiziert; `ADAPTER_QUALIFIED` bleibt unverändert geschlossen. Diese Implementierung provisioniert keine Schlüssel, Pins oder Kalibrierung und schaltet keine VM-Gates frei.
|
||||
|
||||
## Tatsächlich lokal geprüft
|
||||
|
||||
Der unveränderliche Compilerfall `runtime-qualification-476c0212-4af9-42d2-92ca-1c488d158d21` hält 202 öffentliche Eingaben fest (Manifest-SHA256 `505008211630e2b7528cdf085a76309328626fe1e51540170eea293052e53272`). Offline-Docker, private Ausgaben, keine Credentials-Mounts und keine Netzwerkverbindung:
|
||||
|
||||
- Linux-Release-Link der beiden betroffenen Core-Integrationsprogramme: PASS.
|
||||
- Vier gezielte Guards: PASS. Zwei neue Gegenbeispiele verweigern Client-/SYSTEM-Leases bei oberer Grenze genau am Ablauf und danach; zwei bestehende Punktuhr-/Wiederanlaufsequenzen bleiben erfolgreich. Vollständige Listen: 27 beziehungsweise 31 Tests; ausgeführt wurden je zwei, nicht alle 58.
|
||||
- Windows GNU `system-helper`: All-targets-Clippy mit `-D warnings` PASS.
|
||||
- Windows GNU ohne Feature: All-targets-Check PASS; fehlende signierte Konfiguration bleibt geschlossen.
|
||||
- Rustfmt für die zehn geänderten Quellen PASS. Core-All-targets-Clippy war im vorherigen Fall PASS; die einzige Eingabedifferenz zum finalen Fall ist der Windows-EventLog-Kindpfad und betrifft keine Core-Abhängigkeit.
|
||||
|
||||
Ein anfänglicher unvollständiger 190-Eingaben-Snapshot scheiterte an zwei frisch aus Main übernommenen Core-Modulen. Dieser fehlgeschlagene Beleg bleibt erhalten; erst die vollständigen 202-Eingaben-Fälle lieferten die genannten Erfolge. Cross-Checks und lokale Guards ersetzen die vorgeschriebene tatsächliche Linux-VM-Ausführung und anschließende Windows-Runtime-Abnahme nicht. Ein Windows-Candidate-Link wurde in diesem Schritt noch nicht ausgeführt.
|
||||
|
||||
## Konkret offen
|
||||
|
||||
Die nächsten Abnahmen sind die vier Guards auf der Cloud-Linux-VM, der native Windows-Build/Pair-Upgrade und der unabhängige Agent-/Helper-Zeittransport gegen den tatsächlichen Server. Tatsächliche Server-Quellqualität, getrennte geschützte Zeitpins und die Beurteilung des absoluten nativen Zeitfehlers müssen separat nachgewiesen werden. Roh-Capture-Konsistenzmessungen allein sind keine physikalische Kalibrierung.
|
||||
|
||||
Der strukturierte EventLog-Kindprozess besitzt noch keinen unabhängigen signierten Kindadapter. Er bleibt ausdrücklich deny-only (`EVENT_LOG_SIGNED_CHILD_CLOCK_NOT_CONFIGURED`) und wird nicht als Fähigkeit beworben. Dies ist eine konkrete offene Windows-Aufgabe, keine abgeschlossene Abnahme. Die ausdrücklich genehmigte PowerShell-Skriptkonsole soll währenddessen die gewünschte Wartung einschließlich `Get-WinEvent` abdecken; auch diese native Skript-/SYSTEM-Strecke bleibt bis zu ihren tatsächlichen Abnahmen offen. Windows ist damit noch nicht vollständig abgeschlossen.
|
||||
|
||||
## Vorbereiteter Linux-first-Operator
|
||||
|
||||
`deploy/windows_time_runtime_linux_acceptance.py` bindet beide exakten Release-ELFs und alle 202 Quellen an denselben lokalen Beleg. Erst nach vollständiger Prüfung beider Testlisten führt er die vier festen Einzeltests aus; die übrigen 112 Testauswahlen bleiben transparent gefiltert. Bestehende Linux-Agent-/Helper-Prozesse, deren Identität, geschützte Kontrolldateien und die Identität ihrer Zustandsdateien werden vorher und nachher verglichen. Rust-Fixtures erhalten ausschließlich das eigene Fall-TMPDIR. Der Operator führt keine Produktzeitabfrage, RMM-Jobs, Grantvergabe oder Dienststeuerung aus.
|
||||
|
||||
Lokal wurden Python-AST, einmalige Vorbereitung und erneute Fall-/Hashprüfung tatsächlich geprüft: PASS. Der vorbereitete Fall ist `75a4ee16-1e58-4c37-a798-39d94c5bc9db`. **Geplant, nicht ausgeführt:** unabhängiger Operatorreview, einmalige Cloud-Linux-Ausführung und separater lesender Originalfall-Nachweis. Nach verlorener Antwort ist ausschließlich `read` desselben Falls erlaubt; keine erneute Ausführung.
|
||||
|
||||
## Tatsächlich Linux-first: vier gezielte Cloud-VM-Guards
|
||||
|
||||
2026-11-15: Originalfall75a4ee16-1e58-4c37-a798-39d94c5bc9db auf
|
||||
der tatsächlichen Cloud-Linux-VM, beide vollständigen27-/31-Testlisten vor
|
||||
dem ersten Test geprüft. Genau vier --exact-Ausführungen bestanden:
|
||||
Client-upper-Deadlineguard, SYSTEM-Helper-upper-Deadlineguard sowie zwei
|
||||
bestehende Linuxpoint-/Ready-/Reopenregressionen. Zusammen112 andere
|
||||
Testnamen gefiltert, keine zusätzlichen Featuretests oder Skips. Alle
|
||||
Rustfixtures liefen unter eigenem Fall-TMPDIR, keine Produktzeitabfrage,
|
||||
RMM-Jobs, Grants oder Dienststeuerung. Bekannte Runtimezeugen unverändert.
|
||||
|
||||
Separater vollständiger Originalfall-Readback bestanden. Runner-SHA256
|
||||
`39d49fa3494133aed5c2aed7edc860abb59896871026ef109d46fff1d8c46e2c`,
|
||||
Manifestb465a3d1f6db0cc50a3aa2fa59b960a9e7b2d7b13616b8ec854e6ecc888ee44a;
|
||||
202-Input-Quellenqualification8e219d37fef9f1495225b817a62418a4dab240442c0b08724954237e282d1c13.
|
||||
|
||||
Ein unabhängiger Quellenreview bestätigte die eigene Nonce-/Generation-/
|
||||
Prozess-/Boot-/Pinbindung beider Rollen, strikte ownWall/upper-Leasegrenzen,
|
||||
beidseitige Timepipe-Peerbindung, deny-only Close und geschlossene fehlende
|
||||
Pin-/Quellqualitätspfade. Diese Quellen-/Vertragsnachweise ersetzen keine
|
||||
native Windows-Runtime-/Serververgleichs-/Kalibrierungsabnahme.
|
||||
Kein VM-Deployment, produktiver Zeitpin, Clockgate oder Windows-RMM-Job
|
||||
wurde durch diesen Schritt aktiviert. Der strukturierte EventLog-Kindadapter
|
||||
bleibt ausdrücklich offen und unbeworben; PowerShell-Skriptkonsole hat Vorrang.
|
||||
|
||||
Native Ausführungsreceipt-SHA256 `3ad9e2bc7d0e8c3725b12c0de3e7cd041e09ed858252e5a523220b0ee98985df`.
|
||||
|
||||
Separater Originalread-SHA256 `40b1f918838fb1a93789031c720bbd9112eb142c267cb04cc9259c0ab357e068`.
|
||||
Reference in New Issue
Block a user