2 Commits
Author SHA1 Message Date
kevin_janssen 0fd474b772 Record preserved Chrony peer namespace bootstrap on cloud server
Rust development slice / linux (push) Failing after 6s
2026-11-15 10:37:22 +01:00
kevin_janssen 09f7e5af84 Integrate independent signed Windows clocks with native Linux lease guards
Rust development slice / linux (push) Failing after 6s
2026-11-15 10:26:24 +01:00
15 changed files with 1527 additions and 37 deletions
+3 -1
View File
@@ -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
+18 -2
View File
@@ -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();
+42
View File
@@ -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");
+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 {
@@ -0,0 +1,298 @@
#!/usr/bin/env python3
"""One fixed project-parent ACL and Chrony local peer-socket AppArmor rule.
No time sample, clock setter, keys, service restart, retry or automatic rollback.
The root operator invokes this source independently with python3 -I.
"""
import argparse
import errno
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import stat
import struct
import sys
CASE = '5b358997-3abc-43db-945f-f41855b4e3c0'
BASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE
PHASE = 'peer-namespace-bootstrap-v1'
PROFILE = 'rmm.server-time-source.peer-namespace-bootstrap.v1'
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
PIN_RESULT_SHA = 'd0a9ac7b46bdf4247c420f01d959c41d6620f7081c40629016d6866828884c4b'
PUBLIC_PIN_SHA = '203f63f150026d345614ca53e641f248397166fbdeb1f28318fc5d7763317e0a'
PARENT = Path('/run/rmm-time-source')
MAIN = Path('/etc/apparmor.d/usr.sbin.chronyd')
MAIN_SHA = '214e509af9ab9b713e89b09bf6440c4b4248e97c64d4b0d884d2f869d406e1e2'
LOCAL = Path('/etc/apparmor.d/local/usr.sbin.chronyd')
TEMP = '.rmm-time-source-peer-' + CASE + '.new'
PARSER = '/usr/sbin/apparmor_parser'
SETFACL = '/usr/bin/setfacl'
PRECONDITION_RECEIPT_SHA = 'd33e5a11cbc5ac779112762c58dc80b43217786f2570deaaf01eefdf730c180e'
PARSER_HELP_RECEIPT_SHA = '185c3e51b415b7d4847f0cc4f78034af409fe037d5ba839590a795ea433896e5'
LOCAL_BYTES = (b'# Rust Discovery peer namespace; fixed acceptance v1.\n'
b'# Original case 5b358997-3abc-43db-945f-f41855b4e3c0.\n'
b'@{run}/rmm-time-source/clients/*.sock rw,\n')
def require(ok, reason):
if not ok:
raise RuntimeError(reason)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def load_pin_controller():
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
for part in PIN_CONTROLLER.parent.parts[1:]:
info = os.fstat(fd)
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry')
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
os.close(fd)
fd = next_fd
info = os.fstat(fd)
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_parent')
file_fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
with os.fdopen(file_fd, 'rb') as stream:
before = os.fstat(stream.fileno())
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and
before.st_size <= 128 * 1024, 'reviewed_root_controller_file')
raw = stream.read(128 * 1024 + 1)
stable = lambda s: tuple(getattr(s, 'st_' + k) for k in
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns'))
require(stable(before) == stable(os.fstat(stream.fileno())) ==
stable(os.stat(PIN_CONTROLLER.name, dir_fd=fd, follow_symlinks=False)) and
len(raw) == before.st_size and sha(raw) == PIN_CONTROLLER_SHA, 'exact_pin_controller_bytes')
finally:
os.close(fd)
pin = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_pin_guard', loader=None))
pin.__file__ = str(PIN_CONTROLLER)
exec(compile(raw, str(PIN_CONTROLLER), 'exec'), pin.__dict__)
held = pin.read_file(PIN_CONTROLLER, 128 * 1024)
require(held[0] == raw, 'same_loaded_pin_controller')
return pin, lambda: require(pin.read_file(PIN_CONTROLLER, 128 * 1024) == held, 'pin_controller_unchanged')
def acl(fd, name='system.posix_acl_access'):
try:
value = os.getxattr(fd, name)
require(len(value) <= 256, 'bounded_acl_metadata')
return value
except OSError as error:
require(error.errno == errno.ENODATA, 'acl_read_requires_exact_enodata_or_value')
return None
def expected_acl():
# Linux POSIX ACL v2: owner rwx; original owning group --x; named989 --x;
# effective group mask --x; other none. No write/read permission is added.
entries = ((1, 7, 0xffffffff), (4, 1, 0xffffffff), (8, 1, 989),
(16, 1, 0xffffffff), (32, 0, 0xffffffff))
return struct.pack('<I', 2) + b''.join(struct.pack('<HHI', *entry) for entry in entries)
def parser_args(load=False):
return [PARSER, '--replace' if load else '--skip-kernel-load', '--skip-cache', str(MAIN)]
def profile_state(pid):
# Kernel-managed, fixed proc/sysfs paths; never process arguments/environ.
def read(path, limit):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
try:
value = bytearray()
while len(value) <= limit:
part = os.read(fd, min(65536, limit + 1 - len(value)))
if not part:
break
value.extend(part)
require(len(value) <= limit, 'bounded_kernel_profile_read')
return bytes(value)
finally:
os.close(fd)
label = read('/proc/' + str(pid) + '/attr/current', 4096).strip()
profiles = read('/sys/kernel/security/apparmor/profiles', 1024 * 1024).splitlines()
require(label == b'/usr/sbin/chronyd (enforce)' and label in profiles, 'same_chronyd_profile_enforcing')
return dict(chronyd_label=label.decode('ascii'), enforcing=True)
def host_read(pin):
records = {}
for leaf in ('intent.json', 'before.json', 'local-replace-intent.json', 'local-replaced.json',
'offline-intent.json', 'offline-result.json', 'acl-intent.json', 'acl-applied.json',
'reload-intent.json', 'reload-result.json', 'after.json', 'result.json', 'failure.json',
'offline.log', 'acl.log', 'reload.log'):
try:
raw, proof = pin.read_file(BASE / PHASE / leaf, 16384)
records[leaf] = dict(sha256=sha(raw), metadata=proof,
record=raw.decode('ascii') if leaf.endswith('.log') else pin.parsed(raw))
except FileNotFoundError:
records[leaf] = None
except pin.Denied:
records[leaf] = dict(inspection_denied=True)
print(pin.encoded(dict(original_case=CASE, phase=PHASE, read_only=True, records=records)).decode('ascii'), end='')
def host_apply(pin, pin_guard):
case_fd = pin.directory(BASE)
phase_fd = parent_fd = local_fd = -1
try:
pin.absence(case_fd, PHASE)
operator, operator_guard = pin.load_operator()
original = pin.Original(BASE, operator, operator_guard)
pin_raw, pin_proof = pin.read_file(BASE / 'pin/result.json')
require(sha(pin_raw) == PIN_RESULT_SHA, 'actual_original_pin_result')
pin_result = pin.parsed(pin_raw)
main = pin.read_file(MAIN, 65536, 0o644)
old_local = pin.read_file(LOCAL, 65536, 0o644)
require(sha(main[0]) == MAIN_SHA and
b'#include <local/usr.sbin.chronyd>' in [x.strip() for x in main[0].splitlines()] and
old_local[0] == b'', 'exact_main_profile_and_empty_local_override')
parent_fd = pin.directory(PARENT)
parent_identity = pin.stable_directory(os.fstat(parent_fd))
recorded = pin_result['targets'][str(PARENT)]
require(parent_identity == {k: recorded[k] for k in parent_identity} and
os.fstat(parent_fd).st_uid == 0 and os.fstat(parent_fd).st_gid == 10001 and
stat.S_IMODE(os.fstat(parent_fd).st_mode) == 0o710 and
acl(parent_fd) is None and acl(parent_fd, 'system.posix_acl_default') is None,
'original_parent_0710_without_existing_acl')
local_fd = pin.directory(LOCAL.parent)
local_parent_identity = pin.stable_directory(os.fstat(local_fd))
pin.absence(local_fd, TEMP)
tools = {path: pin.read_file(Path(path), 16 * 1024 * 1024, 0o755) for path in (PARSER, SETFACL)}
def fresh(local_expected, acl_expected):
pin_guard()
actual_pin = original.fresh()
require(pin.read_file(BASE / 'pin/result.json') == (pin_raw, pin_proof), 'original_pin_result_unchanged')
public_raw, public_proof = pin.read_file(pin.ETC / 'chrony-pin.json', 8192)
require(sha(public_raw) == PUBLIC_PIN_SHA == pin_result['public_pin_sha256'] and
public_raw == pin.encoded(actual_pin) and public_proof == pin_result['public_pin_metadata'],
'original_public_pin_unchanged')
require(pin.read_file(MAIN, 65536, 0o644) == main and pin.read_file(LOCAL, 65536, 0o644) == local_expected,
'exact_held_main_and_expected_local_profile')
current_parent = pin.directory(PARENT)
try:
require(pin.stable_directory(os.fstat(current_parent)) == parent_identity ==
pin.stable_directory(os.fstat(parent_fd)) and acl(current_parent) == acl_expected and
acl(current_parent, 'system.posix_acl_default') is None,
'same_parent_identity_mode_and_exact_acl')
finally:
os.close(current_parent)
require(pin.stable_directory(os.fstat(local_fd)) == local_parent_identity,
'same_protected_local_profile_directory')
for path, retained in tools.items():
require(pin.read_file(Path(path), 16 * 1024 * 1024, 0o755) == retained, 'same_existing_tool_bytes')
return dict(original=original.expected, public_pin_sha256=PUBLIC_PIN_SHA,
parent_identity=parent_identity, parent_access_acl_hex=None if acl_expected is None else acl_expected.hex(),
main_profile_sha256=MAIN_SHA, local_profile_sha256=sha(local_expected[0]),
profile=profile_state(actual_pin['daemon_pid']))
before = fresh(old_local, None)
os.mkdir(PHASE, mode=0o700, dir_fd=case_fd)
os.fsync(case_fd)
phase_fd = os.open(PHASE, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case_fd)
own_raw, _ = pin.read_file(Path(__file__).absolute(), 128 * 1024)
binding = dict(profile=PROFILE, original_case=CASE, phase=PHASE, controller_sha256=sha(own_raw),
operator_sha256=pin.OPERATOR_SHA, pin_controller_sha256=PIN_CONTROLLER_SHA,
source_tar_sha256=original.source_sha, manifest_sha256=original.manifest_sha,
public_pin_sha256=PUBLIC_PIN_SHA, original_main_profile_sha256=MAIN_SHA,
old_local_profile_sha256=sha(old_local[0]), new_local_profile_sha256=sha(LOCAL_BYTES),
precondition_receipt_sha256=PRECONDITION_RECEIPT_SHA, parser_help_receipt_sha256=PARSER_HELP_RECEIPT_SHA)
def save(name, value):
pin.exclusive(phase_fd, name, pin.encoded(value))
save('intent.json', dict(binding, once=True, no_retry=True, automatic_rollback=False))
save('before.json', dict(binding, witness=before, old_local_metadata=old_local[1]))
pin.exclusive(phase_fd, 'original-local-profile.bin', old_local[0])
save('local-replace-intent.json', dict(binding, exact_empty_original_only=True))
fresh(old_local, None)
fd = os.open(TEMP, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=local_fd)
try:
view = memoryview(LOCAL_BYTES)
while view:
count = os.write(fd, view)
require(count > 0, 'complete_new_local_snippet_write')
view = view[count:]
os.fsync(fd)
require(os.fstat(fd).st_uid == os.fstat(fd).st_gid == 0 and os.fstat(fd).st_nlink == 1,
'own_single_link_root_snippet')
os.fchmod(fd, 0o644) # Only our new file, never an existing daemon directory/socket.
os.fsync(fd)
finally:
os.close(fd)
os.fsync(local_fd)
fresh(old_local, None)
require(pin.read_file(LOCAL.parent / TEMP, 16384, 0o644)[0] == LOCAL_BYTES, 'exact_new_snippet_bytes')
os.replace(TEMP, LOCAL.name, src_dir_fd=local_fd, dst_dir_fd=local_fd)
os.fsync(local_fd)
new_local = pin.read_file(LOCAL, 16384, 0o644)
require(new_local[0] == LOCAL_BYTES, 'exact_atomic_local_override')
save('local-replaced.json', dict(binding, local_metadata=new_local[1]))
fresh(new_local, None)
save('offline-intent.json', dict(binding, skip_kernel=True, skip_cache=True))
code = operator.long_command(parser_args(), BASE / PHASE / 'offline.log', 10)
log, _ = pin.read_file(BASE / PHASE / 'offline.log', 16384)
save('offline-result.json', dict(binding, exit_code=code, log_sha256=sha(log)))
require(code == 0, 'offline_profile_validation_required')
fresh(new_local, None)
save('acl-intent.json', dict(binding, named_group=989, permissions='--x', mask='--x'))
code = operator.long_command([SETFACL, '--no-mask', '--modify=group:989:--x,mask::--x', '--', str(PARENT)],
BASE / PHASE / 'acl.log', 10)
log, _ = pin.read_file(BASE / PHASE / 'acl.log', 16384)
save('acl-applied.json', dict(binding, exit_code=code, log_sha256=sha(log)))
require(code == 0, 'named_parent_traverse_acl_required')
fresh(new_local, expected_acl())
save('reload-intent.json', dict(binding, exact_main_profile_only=True, skip_cache=True))
fresh(new_local, expected_acl())
code = operator.long_command(parser_args(load=True), BASE / PHASE / 'reload.log', 10)
log, _ = pin.read_file(BASE / PHASE / 'reload.log', 16384)
save('reload-result.json', dict(binding, exit_code=code, log_sha256=sha(log)))
require(code == 0, 'actual_profile_replace_exit_zero_required')
after = fresh(new_local, expected_acl())
require(before['original'] == after['original'] and before['profile'] == after['profile'],
'same_chrony_process_boot_and_runtime_enforcing_profile')
save('after.json', dict(binding, witness=after, new_local_metadata=new_local[1]))
links = {}
for name in ('before', 'after', 'offline-result', 'reload-result', 'acl-applied'):
raw, _ = pin.read_file(BASE / PHASE / (name + '.json'), 16384)
links[name.replace('-', '_')] = dict(filename=name + '.json', sha256=sha(raw))
result = dict(binding, records=links, peer_namespace_configured=True, runtime_boot_chrony_preserved=True,
apparmor_enforcing=True, actual_parser_replace_exit_code=0, source_quality_sampled=False,
clock_authority=False, signer_created=False, broker_started=False, services_restarted=False)
save('result.json', result)
print(pin.encoded(result).decode('ascii'), end='')
except Exception as error:
if phase_fd >= 0:
pin.exclusive(phase_fd, 'failure.json', pin.encoded(dict(profile=PROFILE, original_case=CASE,
failed=True, exception_type=type(error).__name__, read_original_phase_only=True,
automatic_rollback=False)))
raise
finally:
for fd in (local_fd, parent_fd, phase_fd, case_fd):
if fd >= 0:
os.close(fd)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=('host-apply', 'host-read'))
args = parser.parse_args()
require(sys.flags.isolated == 1 and os.geteuid() == 0 and os.uname().sysname == 'Linux' and
os.uname().machine == 'aarch64', 'isolated_root_linux_aarch64_only')
os.umask(0o077)
pin, guard = load_pin_controller()
host_read(pin) if args.command == 'host-read' else host_apply(pin, guard)
if __name__ == '__main__':
try:
main()
except Exception:
print(json.dumps(dict(failed=True, read_original_phase_only=True, automatic_rollback=False)), flush=True)
raise SystemExit(1)
@@ -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()
+14
View File
@@ -1,5 +1,19 @@
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
**Namespacebootstrap auf dem permanenten Server bestanden:** exakte Such-ACL
und enger Chrony-Localoverride eingerichtet, tatsächlicher Parser-Replace0 und
separater Read belegt; Enforce, Chronyprozess, Boot und RMM-Runtime erhalten.
[Ergebnis](server-time-source-peer-namespace-bootstrap.md). Noch keine reale
Sourcequalität, Schlüssel oder Clock-/Jobfreigabe.
**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,130 @@
# Enger Projekt-Namespace für den Chrony-Peersocket
`deploy/server_time_source_peer_namespace_bootstrap.py` implementiert einen
einzigen neuen Root-Bootstrap im Originalfall
`5b358997-3abc-43db-945f-f41855b4e3c0`, Phase `peer-namespace-bootstrap-v1`.
Er erhebt keine reale Sourcequalität, startet keinen Broker, erzeugt keine
Schlüssel und führt keine RMM-Jobs aus. Alle alten fehlgeschlagenen Proben und
Diagnosen bleiben unverändert. Root führt diesen gesonderten Plan erst nach
unabhängigem Quellenreview aus; dieser Implementierungsschritt hat keinen
Zielaufruf ausgeführt.
## Tatsächlicher Befund und Zweck beider Änderungen
Die native Fehlerdiagnose meldete ausschließlich `TIME_CHRONY_CONNECT`.
Ein ungebundener Python-Unixsocket konnte im gleichen Root989-/2-Cap-Profil
verbinden; ein bereits im Projektclientverzeichnis gebundener Socket erhielt
EACCES13 und wurde anschließend ausschließlich selbst bereinigt. Keine
Datagramme wurden gesendet. Der getrennte Readonlybefund zeigte zwei Grenzen:
1. Der Chronyprozess als UID/GID989 kann den Parent
`/run/rmm-time-source` Root:10001/0710 nicht durchlaufen. Ausschließlich
eine benannte Access-ACL `group:989:--x` mit ebenfalls `mask::--x` erlaubt
diese Suche. Kein Lesen, Schreiben oder Auflisten wird hinzugefügt;
Owner0, GID10001 und Modus0710 bleiben unverändert. Keine Default-ACL.
2. Das aktiv erzwungene Profil `/usr/sbin/chronyd` erlaubt seine bestehenden
`/run/chrony`-Pfade, nicht den gebundenen Projektpeer. Ausschließlich im
vorhandenen leeren Localoverride kommt die markierte Regel
`@{run}/rmm-time-source/clients/*.sock rw,` hinzu. Sie erlaubt den Peersocket
im bereits Root-geschützten Projektclientnamespace. Weder `/run/chrony`
noch dessen Socketrechte ändern sich. Kein Profil wird deaktiviert, kein
globaler Pfad oder Capabilitybereich freigegeben.
Die feste Quellenprüfung bindet den tatsächlichen Readonlybeleg2087ff0f,
Receipt-SHA256
`d33e5a11cbc5ac779112762c58dc80b43217786f2570deaaf01eefdf730c180e`:
Mainprofil Root:Root0644/Singlelink, SHA256
`214e509af9ab9b713e89b09bf6440c4b4248e97c64d4b0d884d2f869d406e1e2`,
aktives `#include <local/usr.sbin.chronyd>`, exakt leeres Localoverride ebenfalls
Root:Root0644/Singlelink und kein erweitertes Parent-ACL (ENODATA61).
Vorhandene andere ACLs, Localregeln oder abweichende Dateien werden nicht adoptiert.
## Fester Ablauf und Fehlergrenze
Der Controller lädt ausschließlich gehaltene, Root600-/Singlelink-/Hash-geprüfte
Bytes des bereits reviewten fac85-Pincontrollers. Dessen geschützter ecb72-
Originaloperator prüft weiter vollständige ursprüngliche Sources/Artefakte,
Chrony-PID/Birth/Image/Socket/Unit, Boot und RMM-Containermetadaten. Pinresultd0a9
und tatsächlicher öffentlicher Pin203f63 bleiben unverändert gebunden.
Chronys Kernelprozesslabel und das geladene Profil müssen vor/nach auf
`/usr/sbin/chronyd (enforce)` stehen. Setfacl/Parserbytes werden gehalten und
vor den Schritten erneut auf Root0755/Singlelink/Unverändertheit geprüft.
1. Existierende neue Phase verweigern. Aktuelle Originalzeugen, Mainprofil,
Leeroverride und Parent-Identität/ACL-Abwesenheit prüfen. Eigene Root700-
Phase, create-only/fsync-Intent und exakten privaten Altbackup erzeugen.
2. Eigener Local-Replace-Intent. Eine feste neue Root-Singlelink-Tempdatei mit
markiertem Regeltext schreiben und fsyncen; ausschließlich diese neue Datei
erhält0644. Nach erneuter Originalprüfung atomar über genau das alte leere
Localoverride ersetzen; Elternverzeichnis fsyncen. Kein Append/Overwrite
fremder Regeln und keine Änderung des Hauptprofils.
3. Eigener Offline-Intent und exakt
`/usr/sbin/apparmor_parser --skip-kernel-load --skip-cache /etc/apparmor.d/usr.sbin.chronyd`.
Exit0 ist Pflicht vor weiteren Freigaben. Es entsteht kein Kernelreload und
kein Cachewrite. Die Syntax ist durch tatsächlichen Root-Helpbeleg
`185c3e51b415b7d4847f0cc4f78034af409fe037d5ba839590a795ea433896e5`
bestätigt, nicht geraten.
4. Eigener ACL-Intent. Exakt
`/usr/bin/setfacl --no-mask --modify=group:989:--x,mask::--x -- /run/rmm-time-source`.
Der tatsächliche Linux-POSIX-ACL-v2-Xattr muss anschließend exakt Owner-rwx,
ursprüngliche Gruppe--x, benannte989--x, Mask--x und Other--- enthalten.
Mode/Owner/GID/Inode bleiben gleich; keine Default-ACL und keine weiteren ACEs.
5. Eigener Reload-Intent, unmittelbar zuvor frische Main-/Localhash- und
Originalprüfung. Ausschließlich
`/usr/sbin/apparmor_parser --replace --skip-cache /etc/apparmor.d/usr.sbin.chronyd`.
Das ist der autorisierte MAC-Profilreload, kein Dienstneustart und kein
NTP-/Uhrsetter. Beide Parserphasen und Setfacl haben eigene Logs/Exitbelege,
äußerer10s-Wächter, begrenzte Erfassung und keine automatische Wiederholung.
6. Erfolgsrecord erst nach tatsächlich beobachtetem Replace-Exit0 sowie erneut
erhaltenem Mainprofil, genau neuem Localhash, exakter Parent-ACL/Identität,
Enforcezustand und gleichem Chronyprozess/Boot/Runtime. Vorher-/Nachher- und
Unterphasenrecords werden per Hash verlinkt.
Ein Fehler kann neuen Diskpolicytext oder eine teilweise Freigabe hinterlassen.
Das bleibt im eigenen Fall als fehlgeschlagen/unklar erhalten. Keine automatische
Rücknahme, kein blindes Reload-/ACL-Retry und kein Überschreiben alter Records.
Ein nur wieder sichtbares Enforcelabel beweist nicht nachträglich die Ausführung
eines verlorenen Replace-Aufrufs. `host-read` liest ausschließlich vorhandene
eigene Records/Logs und löst weder Prüfungskommandos noch einen Reload aus.
Geplant, hier **nicht ausgeführt**:
```text
python3 -I /reviewter/geschuetzter/pfad/peer_namespace_bootstrap.py host-apply
python3 -I /reviewter/geschuetzter/pfad/peer_namespace_bootstrap.py host-read
```
Keine reale Providerprobe/Signatur oder Clock-/Jobbereitschaft folgt allein aus
dieser Namespacefreigabe. Alle RMM-Jobs benötigen weiterhin ihren unveränderlichen
WebUI-Plan. Alte Source-/GROUP-/DAC-Proben bleiben fehlgeschlagen.
## Tatsächlich lokaler Quellenstand
Controller-SHA256
`2f1dafece1e5cd1b9be11078edee5f67fbdaef013defa10c527367b42dce9265`.
Im privaten Fall `2b5751a9-e49c-453d-96fe-725c4813d9f7` bestanden AST und zwei
enge reine Fixturefälle: exakte44Byte-POSIX-ACL-v2 für named989--x/Mask--x,
ausschließlich ENODATA als ACL-Abwesenheit sowie exakt die zwei bestätigten
Parserargumentvektoren/skip-cache und eine einzige markierte Socketregel.
Fixture-Receipt-SHA256
`177b4fa5a0042755d9d137c81ab94d3c31d13f3d5dd871aaf991dcf39dc87efd`.
Sie bindet die Dokumentfassung vor diesem Ergebnisnachtrag. Kein setfacl,
Parser, Kernelprofil-/NSS-/Zeitgetter, Build, SSH oder Zielaufruf wurde durch
diese Fixtures ausgeführt. Unabhängiger Review und tatsächlicher Bootstrap
sind noch keine hier erbrachten Nachweise.
## Tatsächlich auf dem permanenten Cloud-Server ausgeführt
Am 2026-11-15 wurde ausschließlich dieser Namespacebootstrap erfolgreich
ausgeführt. Rootreceipt
`1dc76b5a9673f9e08e59f91f05d586cb9335ffd0a33e697d5170823a6f053619`,
separater lesender Rückabruf
`129584f296b53614e10a9e5eac2bab0a1e70b1c51f7fd70eb31bdf907ce767b3`,
ursprüngliches Serverresult
`cb1665cb14086d3ba79089a2eb9e01a532dd779bdcf577eafca0e343b5cc6a8b`.
Offlineparser und tatsächlicher Profil-Replace meldeten Exit0. Exakte benannte
Such-ACL und Localprofilhash27e3708a sind nachgelesen; AppArmor bleibt Enforce.
Chronyprozess, Boot, bestehende RMM-Runtime und öffentlicher Pin sind erhalten.
Keine Quelle wurde dabei abgefragt, kein Dienst neu gestartet und kein
Signierschlüssel oder Broker erzeugt. Die separate reale Qualitätsprobe bleibt
der nächste Schritt; frühere fehlgeschlagene Proben bleiben fehlgeschlagen.
+62
View File
@@ -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`.