From 6b03b222e65f7958e41680c8a216576219af26d2 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 11:48:02 +0100 Subject: [PATCH] Trace native Windows clock RPC failure without changing trust checks --- .../agent-windows/examples/clock_readiness.rs | 5 +- crates/agent-windows/native/clock_rpc.c | 52 ++++++++++-- crates/agent-windows/src/clock.rs | 82 +++++++++++++++++++ docs/windows-clock-status-diagnostic.md | 36 ++++++++ 4 files changed, 167 insertions(+), 8 deletions(-) create mode 100644 docs/windows-clock-status-diagnostic.md diff --git a/crates/agent-windows/examples/clock_readiness.rs b/crates/agent-windows/examples/clock_readiness.rs index fde600e..317c501 100644 --- a/crates/agent-windows/examples/clock_readiness.rs +++ b/crates/agent-windows/examples/clock_readiness.rs @@ -157,6 +157,7 @@ mod service { let clock = super::clock::NativeClock::new(); STAGE.store(30, Ordering::SeqCst); let pipe = super::clock::named_pipe_diagnostic(); + let status_rpc = super::clock::status_rpc_diagnostic(); let first = clock.report(); std::thread::sleep(Duration::from_millis(750)); STAGE.store(31, Ordering::SeqCst); @@ -164,7 +165,7 @@ mod service { let identity_controls = super::clock::identity_controls(); STAGE.store(40, Ordering::SeqCst); let data = serde_json::to_vec_pretty( - &serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}), + &serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"status_rpc_diagnostic":status_rpc,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}), )?; ensure!(data.len() < 16384, "READINESS_REPORT_SIZE"); STAGE.store(41, Ordering::SeqCst); @@ -259,6 +260,6 @@ fn main() -> anyhow::Result<()> { fn main() { println!( "{}", - serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap() + serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"status_rpc_diagnostic":clock::status_rpc_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap() ); } diff --git a/crates/agent-windows/native/clock_rpc.c b/crates/agent-windows/native/clock_rpc.c index dca1f1e..977b2a1 100644 --- a/crates/agent-windows/native/clock_rpc.c +++ b/crates/agent-windows/native/clock_rpc.c @@ -71,20 +71,47 @@ typedef struct { } RmmClockStatus; _Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI"); _Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI"); -static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) { +/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays + * leave C. A zero native return is meaningful only when return_present is1. + * Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena, + * 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped, + * 90 contained RPC/SEH exception. Never used by the clock trust evaluator. + */ +typedef struct { + uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception; + uint32_t status_present, ul_size, c_entries, p_entries_present; +} RmmClockTrace; +_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI"); +static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace) { RMM_W32TIME_STATUS *status = NULL; unsigned long result = 0; Arena arena = {0}; + if (trace) trace->stage = 50; if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY; if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY; if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError(); if (!result) { RpcTryExcept { + if (trace) trace->stage = 60; result = RmmW32TimeQueryStatus(binding, &status); + if (trace) { + trace->stage = 61; trace->native_rpc_return_present = 1; + trace->native_rpc_return = result; + } if (!result) { - if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) + if (trace) { + trace->stage = 62; trace->status_present = status != NULL; + if (status) { + trace->ul_size = status->ulSize; trace->c_entries = status->cEntries; + trace->p_entries_present = status->pEntries != NULL; + } + } + if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) { + if (trace) trace->stage = 70; result = RPC_X_BAD_STUB_DATA; + } else { + if (trace) trace->stage = 80; out->leap = status->eLeapIndicator; out->stratum = status->nStratum; out->state = status->ulLcState; out->flags = status->ulTSFlags; out->last_result = status->eLastSyncResult; out->size = status->ulSize; @@ -95,21 +122,24 @@ static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) { } } RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { result = RpcExceptionCode(); + if (trace) {trace->stage = 90; trace->rpc_exception = result;} } RpcEndExcept release_allocations(&arena); TlsSetValue(arena_index, NULL); } return result; } -uint32_t rmm_clock_query(RmmClockStatus *out) { +static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace) { RPC_WSTR text = NULL; RPC_BINDING_HANDLE binding = NULL; RPC_SECURITY_QOS qos = {0}; unsigned long result; memset(out, 0, sizeof(*out)); + if (trace) trace->stage = 10; result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL, (RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text); if (result) return result; + if (trace) trace->stage = 20; result = RpcBindingFromStringBindingW(text, &binding); RpcStringFreeW(&text); if (result) return result; @@ -117,13 +147,23 @@ uint32_t rmm_clock_query(RmmClockStatus *out) { qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + if (trace) trace->stage = 30; result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos); - if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); - if (!result) result = invoke_status(binding, out); + if (!result) { + if (trace) trace->stage = 40; + result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500); + } + if (!result) result = invoke_status(binding, out, trace); RpcBindingFree(&binding); return result; } +uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL); } +uint32_t rmm_clock_query_trace(RmmClockTrace *trace) { + RmmClockStatus ignored = {0}; + memset(trace, 0, sizeof(*trace)); + return pipe_query(&ignored, trace); +} /* Kernel-authenticated ALPC only. No automatic fallback to named pipes. * The expected SID is fixed locally, never adopted from endpoint metadata. */ @@ -188,7 +228,7 @@ static uint32_t alpc_query(RmmClockStatus *out, unsigned control) { qos.ServerSecurityDescriptor = &descriptor; result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos); - if (!result) result = invoke_status(binding, out); + if (!result) result = invoke_status(binding, out, NULL); } RpcBindingFree(&binding); break; /* no retry, alternate identity, endpoint or weaker transport */ diff --git a/crates/agent-windows/src/clock.rs b/crates/agent-windows/src/clock.rs index 4db1572..e649e1c 100644 --- a/crates/agent-windows/src/clock.rs +++ b/crates/agent-windows/src/clock.rs @@ -259,6 +259,87 @@ pub fn named_pipe_diagnostic() -> ClockReport { } .report() } +/// Diagnostic-only ABI captured before the existing C layout guard. Presence +/// flags are numeric0/1; no remote pointers, names or returned entries escape. +#[derive(Clone, Copy, Debug, Default, Serialize)] +#[repr(C)] +pub struct StatusRpcTrace { + pub stage: u32, + pub native_rpc_return: u32, + pub native_rpc_return_present: u32, + pub rpc_exception: u32, + pub status_present: u32, + pub ul_size: u32, + pub c_entries: u32, + pub p_entries_present: u32, +} +#[derive(Debug, Serialize)] +pub struct StatusRpcDiagnostic { + pub rpc_code: u32, + pub independent_call: bool, + pub trace: Option, + pub diagnostic_only: bool, + pub adapter_qualified: bool, + pub trusted: bool, +} +/// The fixed authenticated named-pipe call is observed separately. It never +/// selects a production transport or supplies a trusted timestamp. One worker, +/// one outstanding call and no replacement/retry after a local timeout. +pub fn status_rpc_diagnostic() -> StatusRpcDiagnostic { + #[cfg(windows)] + let (rpc_code, trace) = { + type Reply = std::sync::mpsc::SyncSender<(u32, StatusRpcTrace)>; + type Requests = std::sync::mpsc::SyncSender; + static WORKER: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let worker = WORKER.get_or_init(|| { + let (sender, receiver) = std::sync::mpsc::sync_channel::(1); + let created = std::thread::Builder::new() + .name("rmm-clock-status-diag".into()) + .spawn(move || { + #[link(name = "rmm_clock_rpc", kind = "static")] + #[link(name = "rpcrt4")] + #[link(name = "advapi32")] + unsafe extern "C" { + fn rmm_clock_query_trace(trace: *mut StatusRpcTrace) -> u32; + } + while let Ok(reply) = receiver.recv() { + let mut trace = StatusRpcTrace::default(); + // SAFETY: fixed8*u32 C ABI; SEH stays contained inside C. + let code = unsafe { rmm_clock_query_trace(&mut trace) }; + let _ = reply.send((code, trace)); + } + }) + .is_ok(); + Mutex::new(created.then_some(sender)) + }); + if let Ok(mut worker) = worker.try_lock() { + let (reply, receiver) = std::sync::mpsc::sync_channel(1); + let sent = worker + .as_ref() + .is_some_and(|sender| sender.try_send(reply).is_ok()); + if sent + && let Ok((code, trace)) = receiver.recv_timeout(std::time::Duration::from_secs(2)) + { + (code, Some(trace)) + } else { + *worker = None; + (1818, None) + } + } else { + (170, None) + } + }; + #[cfg(not(windows))] + let (rpc_code, trace) = (50, None); + StatusRpcDiagnostic { + rpc_code, + independent_call: true, + trace, + diagnostic_only: true, + adapter_qualified: false, + trusted: false, + } +} /// Read-only negative controls for the separate native readiness program. /// Neither control can produce clock authority, even if the OS accepts it. /// Rejection without a successful genuine status query is not identity proof. @@ -443,6 +524,7 @@ mod tests { } #[test] fn production_clock_stays_closed_until_native_adapter_qualification() { + assert_eq!(std::mem::size_of::(), 32); assert_eq!( NativeClock::new().now().unwrap_err().to_string(), "CLOCK_ADAPTER_UNQUALIFIED" diff --git a/docs/windows-clock-status-diagnostic.md b/docs/windows-clock-status-diagnostic.md new file mode 100644 index 0000000..a072059 --- /dev/null +++ b/docs/windows-clock-status-diagnostic.md @@ -0,0 +1,36 @@ +# Numerische Windows-Zeitdienstdiagnose + +Stand2026-11-14: Diagnosequelle implementiert und unabhängig vom Produktions- +Clockpfad gebaut. Keine Lockerung von Statusguard, ALPC-/Identitätsprüfung, +`NativeClock.now()` oder `ADAPTER_QUALIFIED=false`. Keine neue Clockauthority. +Die feste zusätzliche Named-Pipe-Statusabfrage liefert ausschließlich acht +numerische Felder: Phase, tatsächliche RPC-Rückgabe samt Presenceflag, +aufgefangene Ausnahme und Strukturgrößen-/Zeigerpräsenz. Keine Quellen-/Peer- +Namen, Pointerwerte oder zusätzlichen Rückgabeeinträge werden veröffentlicht. +Eigener begrenzter Diagnoseworker; nach Timeout kein Ersatz/Retry. + +Lokal tatsächlich bestanden: Windows-Example-Clippy mit Warnungen als Fehler, +fünf Linux-Clocktests, Windows-Testlink (nicht nativ ausgeführt) und Release- +Link.125Quellinputs vorher/nachher identisch. Originale Werkzeugabweichung +(Buildimage ohne WIDL) privat erhalten; erfolgreicher Build mit vorhandenem +unveränderlichem Clockimage. Artefakt `ecad703ad7208d55681c63ba9513fcf4c73b671951d4d1b5db1af9df49f43bdf`, +1779541Bytes. Privater Build `release-ca9a63b8-127c-4933-a45d-9e82449d6980`, +Qualifikation `36ce552e…`. + +Danach tatsächlich auf der Windows-VM unter dem separaten LocalService- +Bootstrapdienst ausgeführt, Fall `2996df8c-b261-466a-8963-a526babf7f67`. +NativeReport und getrennter Readback identisch, eigener Dienst entfernt. +ALPC weiter1753/kein Endpunkt, keine erfolgreichen Identitätsnegativkontrollen. +Zusätzliche unabhängige Abfrage:1783, `stage=90`, `rpc_exception=1783`, +`native_rpc_return_present=0`, `status_present=0`. **Eine aufgefangene RPC-/ +NDR-Ausnahme vor normaler Stub-Rückkehr ist belegt; der eigene nachgelagerte +Strukturguard wurde nicht erreicht.** Das Nullwertfeld `native_rpc_return=0` +ist ohne Presenceflag ausdrücklich kein erfolgreicher nativer Return. + +Die genaue RPC-/NDR-Ursache bleibt offen. Source-/IDL-Prüfung folgt anhand +des [Microsoft-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a). +W32Time wurde für diese Diagnose nicht umkonfiguriert, keine Uhr gesetzt und +kein RMM-Job ausgeführt. Zentrale Windows0/0/0/0 und Linux30/30/26/0 samt +geschlossenen Testhooks/Rootpolicy erhalten. Dieses Ergebnis qualifiziert +weder Named-Pipe-Serveridentität noch eine vertrauenswürdige Uhr. Erst recht +öffnet es keinen Grant-/Jobpfad.