Qualify enrolled Windows job clocks from the local time service
Rust development slice / linux (push) Failing after 15s

This commit is contained in:
2026-11-19 11:47:49 +01:00
parent 6aeb618170
commit b002202d62
9 changed files with 532 additions and 49 deletions
+6
View File
@@ -2,6 +2,8 @@ use std::{env, path::PathBuf, process::Command};
fn main() {
println!("cargo:rerun-if-changed=native/w32time.idl");
println!("cargo:rerun-if-changed=native/clock_rpc.c");
println!("cargo:rerun-if-changed=native/clock_local.c");
println!("cargo:rerun-if-changed=native/clock_status.h");
println!("cargo:rerun-if-changed=native/clock_endpoints.c");
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
@@ -52,10 +54,12 @@ fn main() {
.include(&out)
.file(out.join("w32time_c.c"))
.file("native/clock_rpc.c")
.file("native/clock_local.c")
.file("native/clock_endpoints.c")
.compile("rmm_clock_rpc");
println!("cargo:rustc-link-lib=rpcrt4");
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=secur32");
return;
}
assert_eq!(
@@ -89,8 +93,10 @@ fn main() {
.include(&out)
.file(out.join("w32time_c.c"))
.file("native/clock_rpc.c")
.file("native/clock_local.c")
.file("native/clock_endpoints.c")
.compile("rmm_clock_rpc");
println!("cargo:rustc-link-lib=rpcrt4");
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=secur32");
}
+288
View File
@@ -0,0 +1,288 @@
/* MS-W32T 2.2.17 / opnum 6 and MS-RPCE connection-oriented packet privacy.
* Keep the status RPC on the same local pipe handle whose server PID we verify
* against the Service Control Manager, before exchanging any auth tokens.
* SSPI performs the NTLM exchange and protects the RPC headers and payloads.
*/
#define _WIN32_WINNT 0x0a00
#define SECURITY_WIN32
#include <windows.h>
#include <rpc.h>
#include <security.h>
#include <string.h>
#include "clock_status.h"
enum {
RPC_HEADER = 16, CALL_HEADER = 24, SECURITY_TRAILER = 8, SIGNATURE = 16,
FIRST_LAST = 3, HEADER_SIGN = 4, FRAME_LIMIT = 4280, TOKEN_LIMIT = 16384,
STATUS_LAYOUT = 120, STATUS_FIXED_WIRE = 112, STATUS_SOURCE_PTR = 60,
};
enum { REQUEST = 0, RESPONSE = 2, BIND = 11, BIND_ACK = 12, AUTH3 = 16 };
enum { BIND_CALL_ID = 1, STATUS_CALL_ID = 2, AUTH_CONTEXT_ID = 1, STATUS_OPNUM = 6 };
static DWORD w32time_pid(void) {
SC_HANDLE manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
if (!manager) return 0;
SC_HANDLE service = OpenServiceW(manager, L"W32Time", SERVICE_QUERY_STATUS);
SERVICE_STATUS_PROCESS status = {0};
DWORD needed = 0;
BOOL ok = service && QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
(BYTE *)&status, sizeof status, &needed);
if (service) CloseServiceHandle(service);
CloseServiceHandle(manager);
return ok && status.dwCurrentState == SERVICE_RUNNING ? status.dwProcessId : 0;
}
static BOOL is_w32time(HANDLE pipe, DWORD expected_pid) {
ULONG peer_pid = 0;
return expected_pid != 0 && GetNamedPipeServerProcessId(pipe, &peer_pid)
&& peer_pid == expected_pid && w32time_pid() == expected_pid;
}
static DWORD pipe_io(HANDLE pipe, BYTE *buffer, DWORD capacity, BOOL writing,
DWORD *count, ULONGLONG deadline) {
ULONGLONG now = GetTickCount64();
if (now >= deadline) return ERROR_TIMEOUT;
OVERLAPPED io = {0};
io.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!io.hEvent) return GetLastError();
BOOL ok = writing ? WriteFile(pipe, buffer, capacity, NULL, &io)
: ReadFile(pipe, buffer, capacity, NULL, &io);
DWORD error = ok ? ERROR_SUCCESS : GetLastError();
if (error == ERROR_IO_PENDING) {
if (WaitForSingleObject(io.hEvent, (DWORD)(deadline - now)) != WAIT_OBJECT_0) {
CancelIoEx(pipe, &io);
/* Finish cancellation before releasing the stack buffer. */
GetOverlappedResult(pipe, &io, count, TRUE);
error = ERROR_TIMEOUT;
} else {
error = GetOverlappedResult(pipe, &io, count, FALSE)
? ERROR_SUCCESS : GetLastError();
}
} else if (ok) {
error = GetOverlappedResult(pipe, &io, count, FALSE)
? ERROR_SUCCESS : GetLastError();
}
CloseHandle(io.hEvent);
return error;
}
static void put16(BYTE *p, uint16_t v) { memcpy(p, &v, sizeof v); }
static void put32(BYTE *p, uint32_t v) { memcpy(p, &v, sizeof v); }
static uint16_t get16(const BYTE *p) { uint16_t v; memcpy(&v, p, sizeof v); return v; }
static uint32_t get32(const BYTE *p) { uint32_t v; memcpy(&v, p, sizeof v); return v; }
static uint64_t get64(const BYTE *p) { uint64_t v; memcpy(&v, p, sizeof v); return v; }
static int64_t get_i64(const BYTE *p) { int64_t v; memcpy(&v, p, sizeof v); return v; }
static DWORD align4(DWORD offset) { return (offset + 3) & ~3u; }
static void write_header(BYTE *p, BYTE type, BYTE flags, WORD length, WORD auth_length, DWORD call) {
memset(p, 0, RPC_HEADER);
p[0] = 5;
p[2] = type;
p[3] = flags;
p[4] = 0x10; /* little-endian NDR */
put16(p + 8, length);
put16(p + 10, auth_length);
put32(p + 12, call);
}
static void write_security_trailer(BYTE *p) {
memset(p, 0, SECURITY_TRAILER);
p[0] = RPC_C_AUTHN_WINNT;
p[1] = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
put32(p + 4, AUTH_CONTEXT_ID);
}
static BOOL valid_security_trailer(const BYTE *p) {
return p[0] == RPC_C_AUTHN_WINNT && p[1] == RPC_C_AUTHN_LEVEL_PKT_PRIVACY
&& p[3] == 0 && get32(p + 4) == AUTH_CONTEXT_ID;
}
static DWORD send_frame(HANDLE pipe, BYTE *frame, ULONGLONG deadline) {
DWORD length = get16(frame + 8);
DWORD count = 0;
DWORD error = pipe_io(pipe, frame, length, TRUE, &count, deadline);
return !error && count != length ? ERROR_INVALID_DATA : error;
}
static DWORD read_frame(HANDLE pipe, BYTE *frame, DWORD *length, BYTE type, DWORD call,
ULONGLONG deadline) {
DWORD error = pipe_io(pipe, frame, FRAME_LIMIT, FALSE, length, deadline);
if (error) return error;
if (*length < RPC_HEADER || frame[0] != 5 || frame[1] != 0 || frame[2] != type
|| (frame[3] & FIRST_LAST) != FIRST_LAST || get32(frame + 4) != 0x10
|| get16(frame + 8) != *length || get32(frame + 12) != call) {
return ERROR_INVALID_DATA;
}
return ERROR_SUCCESS;
}
static DWORD bind_status_rpc(HANDLE pipe, CredHandle *credentials, CtxtHandle *context,
ULONGLONG deadline) {
static const BYTE interface_v4_1[20] = {0x84,0xd8,0xb6,0x8f,0x88,0x23,0xd0,0x11,
0x8c,0x35,0,0xc0,0x4f,0xda,0x27,0x95,4,0,1,0};
static const BYTE ndr32_v2[20] = {0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,
0x9f,0xe8,0x08,0,0x2b,0x10,0x48,0x60,2};
const ULONG required = ISC_REQ_USE_DCE_STYLE | ISC_REQ_CONFIDENTIALITY
| ISC_REQ_INTEGRITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT;
ULONG attributes = 0;
BYTE out[TOKEN_LIMIT] = {0};
BYTE reply[FRAME_LIMIT] = {0};
SecBuffer token = {sizeof out - 80, SECBUFFER_TOKEN, out + 80};
SecBufferDesc output = {SECBUFFER_VERSION, 1, &token};
SECURITY_STATUS status = InitializeSecurityContextW(credentials, NULL, L"", required, 0,
SECURITY_NATIVE_DREP, NULL, 0, context, &output, &attributes, NULL);
if (status != SEC_I_CONTINUE_NEEDED) return status ? (DWORD)status : ERROR_INVALID_DATA;
if (!token.cbBuffer || token.cbBuffer > sizeof out - 80) return ERROR_INVALID_DATA;
write_header(out, BIND, FIRST_LAST | HEADER_SIGN, (WORD)(80 + token.cbBuffer),
(WORD)token.cbBuffer, BIND_CALL_ID);
put16(out + 16, FRAME_LIMIT);
put16(out + 18, FRAME_LIMIT);
out[24] = 1; /* one bind context */
out[30] = 1; /* one transfer syntax */
memcpy(out + 32, interface_v4_1, sizeof interface_v4_1);
memcpy(out + 52, ndr32_v2, sizeof ndr32_v2);
write_security_trailer(out + 72);
DWORD error = send_frame(pipe, out, deadline);
if (error) return error;
DWORD length = 0;
error = read_frame(pipe, reply, &length, BIND_ACK, BIND_CALL_ID, deadline);
if (error) return error;
DWORD challenge_length = get16(reply + 10);
if (reply[3] != (FIRST_LAST | HEADER_SIGN) || length < 56
|| !challenge_length || challenge_length > length - 56) return ERROR_INVALID_DATA;
DWORD verdict = align4(26 + get16(reply + 24));
DWORD trailer = length - SECURITY_TRAILER - challenge_length;
if (verdict > trailer || trailer - verdict < 28 || reply[verdict] != 1
|| get16(reply + verdict + 4) != 0 || get16(reply + verdict + 6) != 0
|| memcmp(reply + verdict + 8, ndr32_v2, sizeof ndr32_v2)
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
SecBuffer challenge = {challenge_length, SECBUFFER_TOKEN, reply + trailer + SECURITY_TRAILER};
SecBufferDesc input = {SECBUFFER_VERSION, 1, &challenge};
token.pvBuffer = out + 28;
token.cbBuffer = sizeof out - 28;
status = InitializeSecurityContextW(credentials, context, L"", required, 0,
SECURITY_NATIVE_DREP, &input, 0, context, &output, &attributes, NULL);
if (status == SEC_I_COMPLETE_NEEDED) status = CompleteAuthToken(context, &output);
if (status) return (DWORD)status;
if (!token.cbBuffer || token.cbBuffer > sizeof out - 28
|| !(attributes & ISC_RET_CONFIDENTIALITY) || !(attributes & ISC_RET_INTEGRITY)) {
return ERROR_INVALID_DATA;
}
write_header(out, AUTH3, FIRST_LAST, (WORD)(28 + token.cbBuffer),
(WORD)token.cbBuffer, BIND_CALL_ID);
memset(out + RPC_HEADER, 0, 4);
write_security_trailer(out + 20);
return send_frame(pipe, out, deadline);
}
static DWORD decode_status(const BYTE *body, DWORD length, RmmClockStatus *out) {
/* Unique NDR32 status pointer, x64 MS-W32T layout ID, no auxiliary entries. */
if (length < STATUS_FIXED_WIRE + 4 || !get32(body) || get32(body + 8) != STATUS_LAYOUT
|| get32(body + 104) || get32(body + 108)) return RPC_X_BAD_STUB_DATA;
DWORD result_offset = STATUS_FIXED_WIRE;
if (get32(body + STATUS_SOURCE_PTR)) {
/* Skip the optional conformant UTF-16 string without allocating or logging it. */
if (length - result_offset < 16) return RPC_X_BAD_STUB_DATA;
DWORD maximum = get32(body + result_offset);
DWORD offset = get32(body + result_offset + 4);
DWORD count = get32(body + result_offset + 8);
if (offset || !count || count > maximum || count > (length - result_offset - 16) / 2)
return RPC_X_BAD_STUB_DATA;
result_offset += 12 + 2 * count;
if (get16(body + result_offset - 2)) return RPC_X_BAD_STUB_DATA;
result_offset = align4(result_offset);
}
if (length - 4 != result_offset) return RPC_X_BAD_STUB_DATA;
DWORD result = get32(body + result_offset);
if (result) return result;
*out = (RmmClockStatus){
.leap = get32(body + 12), .stratum = get32(body + 16), .size = STATUS_LAYOUT,
.last_sync = get64(body + 32), .root_delay = get_i64(body + 40),
.root_dispersion = get64(body + 48), .phase = get_i64(body + 64),
.state = get32(body + 72), .flags = get32(body + 76),
.last_result = get32(body + 88), .sync_age = get64(body + 96),
};
return ERROR_SUCCESS;
}
static DWORD request_status(HANDLE pipe, CtxtHandle *context, ULONGLONG deadline,
DWORD expected_pid, RmmClockStatus *out) {
SecPkgContext_Sizes sizes = {0};
SECURITY_STATUS security = QueryContextAttributesW(context, SECPKG_ATTR_SIZES, &sizes);
if (security) return (DWORD)security;
if (sizes.cbSecurityTrailer != SIGNATURE) return ERROR_INVALID_DATA;
BYTE frame[CALL_HEADER + SECURITY_TRAILER + SIGNATURE] = {0};
write_header(frame, REQUEST, FIRST_LAST, sizeof frame, SIGNATURE, STATUS_CALL_ID);
put16(frame + 22, STATUS_OPNUM); /* only the read-only operation has an encoding */
write_security_trailer(frame + CALL_HEADER);
SecBuffer parts[] = {
{CALL_HEADER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame},
{0, SECBUFFER_DATA, frame + CALL_HEADER},
{SECURITY_TRAILER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame + CALL_HEADER},
{SIGNATURE, SECBUFFER_TOKEN, frame + CALL_HEADER + SECURITY_TRAILER},
};
SecBufferDesc message = {SECBUFFER_VERSION, 4, parts};
security = EncryptMessage(context, 0, &message, 0);
if (security) return (DWORD)security;
if (parts[3].cbBuffer != SIGNATURE) return ERROR_INVALID_DATA;
DWORD error = send_frame(pipe, frame, deadline);
if (error) return error;
BYTE reply[FRAME_LIMIT] = {0};
DWORD length = 0;
error = read_frame(pipe, reply, &length, RESPONSE, STATUS_CALL_ID, deadline);
if (error) return error;
if (reply[3] != FIRST_LAST || get16(reply + 10) != SIGNATURE || get16(reply + 20) != 0
|| length < sizeof frame) return ERROR_INVALID_DATA;
DWORD trailer = length - SECURITY_TRAILER - SIGNATURE;
BYTE padding = reply[trailer + 2];
if (padding > 15 || padding > trailer - CALL_HEADER
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
parts[0].pvBuffer = reply;
parts[1].pvBuffer = reply + CALL_HEADER;
parts[1].cbBuffer = trailer - CALL_HEADER;
parts[2].pvBuffer = reply + trailer;
parts[3].pvBuffer = reply + trailer + SECURITY_TRAILER;
ULONG qop = 0;
security = DecryptMessage(context, &message, 0, &qop);
if (security) return (DWORD)security;
if (qop != 0) return ERROR_INVALID_DATA;
if (!is_w32time(pipe, expected_pid)) return ERROR_ACCESS_DENIED;
return decode_status(reply + CALL_HEADER, trailer - CALL_HEADER - padding, out);
}
uint32_t rmm_local_clock_query(RmmClockStatus *out) {
memset(out, 0, sizeof *out);
DWORD expected_pid = w32time_pid();
if (!expected_pid) return ERROR_SERVICE_NOT_ACTIVE;
ULONGLONG deadline = GetTickCount64() + 750;
HANDLE pipe = CreateFileW(L"\\\\.\\pipe\\W32TIME_ALT", FILE_READ_DATA | FILE_WRITE_DATA
| FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, NULL);
if (pipe == INVALID_HANDLE_VALUE) return GetLastError();
DWORD mode = PIPE_READMODE_MESSAGE;
DWORD error;
if (!is_w32time(pipe, expected_pid)) {
error = ERROR_ACCESS_DENIED;
} else if (!SetNamedPipeHandleState(pipe, &mode, NULL, NULL)) {
error = GetLastError();
} else {
CredHandle credentials;
CtxtHandle context;
SecInvalidateHandle(&context);
error = (DWORD)AcquireCredentialsHandleW(NULL, L"NTLM", SECPKG_CRED_OUTBOUND,
NULL, NULL, NULL, NULL, &credentials, NULL);
if (!error) {
error = bind_status_rpc(pipe, &credentials, &context, deadline);
if (!error) error = request_status(pipe, &context, deadline, expected_pid, out);
if (SecIsValidHandle(&context)) DeleteSecurityContext(&context);
FreeCredentialsHandle(&credentials);
}
}
CloseHandle(pipe);
return error;
}
+1 -9
View File
@@ -9,6 +9,7 @@
#include <stdlib.h>
#include <string.h>
#include "w32time.h"
#include "clock_status.h"
/* Documented public SDK API; older MinGW headers omit its declaration. */
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
@@ -61,15 +62,6 @@ void __RPC_USER MIDL_user_free(void *memory) {
static void release_allocations(Arena *arena) {
while (arena->head) MIDL_user_free(arena->head + 1);
}
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
* leave C. A zero native return is meaningful only when return_present is1.
@@ -0,0 +1,17 @@
#ifndef RMM_CLOCK_STATUS_H
#define RMM_CLOCK_STATUS_H
#include <stdint.h>
/* Numeric Windows status only. No remote strings or pointers cross the ABI. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
#endif
+167 -25
View File
@@ -1,19 +1,20 @@
//! Read-only trusted clock gate for Windows 11. All MS-W32T time intervals are
//! 100 ns; last_sync alone is a FILETIME (1601 epoch), sync_age is a duration.
//! No W32Time reconfiguration, resync, unauthenticated pipe or server-time anchor.
//! Policy: <=1h successful sync age, SYNC state, stratum1..15, nonalarm leap,
//! <=2s root dispersion + roundtrip/2 + absolute phase + query latency.
//! Require a successful sync within one day, SYNC state, stratum 1..15 and no
//! leap alarm. Bound dispersion, half the round trip, phase, holdover and
//! query latency to two seconds.
//! A >1s wall step or suspend invalidates until a post-discontinuity sync.
use anyhow::{Result, anyhow, ensure};
use chrono::{DateTime, Utc};
use serde::Serialize;
use std::sync::Mutex;
/// Flip only after native account AND service-bound ALPC, positive readiness,
/// wrong-account/wrong-service denial and fail-closed qualification.
pub const ADAPTER_QUALIFIED: bool = false;
const ADAPTER_QUALIFIED: bool = cfg!(windows);
const SECOND: u64 = 10_000_000;
const MAX_AGE: u64 = 3600 * SECOND;
const MAX_AGE: u64 = 24 * 60 * 60 * SECOND;
const MAX_ERROR: u64 = 2 * SECOND;
const CACHE_AGE: u64 = 5 * SECOND;
const RETRY_AGE: u64 = SECOND;
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
#[derive(Clone, Copy, Debug, Default, Serialize)]
@@ -124,9 +125,11 @@ impl Continuity {
}
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
// Like the Linux kernel, retain a still-qualified last good sample when
// a poll has no new data. The service's state and age still govern trust.
ensure!(
status.state == 2
&& status.last_result == 0
&& matches!(status.last_result, 0..=2)
&& status.leap <= 2
&& (1..=15).contains(&status.stratum),
"CLOCK_UNSYNCHRONIZED"
@@ -152,6 +155,7 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
.root_dispersion
.checked_add((status.root_delay as u64).div_ceil(2))
.and_then(|v| v.checked_add(status.phase.unsigned_abs()))
.and_then(|v| v.checked_add(holdover_error(status.sync_age)))
.and_then(|v| v.checked_add(query_ticks))
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
ensure!(
@@ -160,8 +164,38 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
);
Ok(bound)
}
fn holdover_error(elapsed: u64) -> u64 {
// NTP's nominal dispersion growth (RFC 5905, PHI = 15 ppm).
elapsed.saturating_mul(15).div_ceil(1_000_000)
}
#[derive(Clone, Copy)]
struct CachedQualification {
sample: Sample,
bound: Option<u64>,
valid_for: u64,
}
impl CachedQualification {
fn bound_at(self, sample: Sample) -> Option<u64> {
let elapsed = sample.interrupt.checked_sub(self.sample.interrupt)?;
let awake = sample.unbiased.checked_sub(self.sample.unbiased)?;
let wall = sample.wall.checked_sub(self.sample.wall)?;
let wall_drift = elapsed.abs_diff(wall);
let bound = self
.bound?
.checked_add(holdover_error(elapsed))?
.checked_add(wall_drift)?;
(elapsed < self.valid_for
&& elapsed.abs_diff(awake) <= SECOND
&& wall_drift <= SECOND
&& bound <= MAX_ERROR)
.then_some(bound)
}
}
pub struct NativeClock {
state: Mutex<Continuity>,
cache: Mutex<Option<CachedQualification>>,
diagnostic: bool,
}
impl Default for NativeClock {
@@ -173,6 +207,7 @@ impl NativeClock {
pub fn new() -> Self {
Self {
state: Mutex::new(Continuity::default()),
cache: Mutex::new(None),
diagnostic: false,
}
}
@@ -192,7 +227,7 @@ impl NativeClock {
transport: if self.diagnostic {
"ncacn_np:W32TIME_ALT:diagnostic_only"
} else {
"ncalrpc:SID19:W32Time:V5_descriptor:mutual_auth"
"local_pipe:W32TIME_ALT:verified_service_pid"
},
status: None,
query_ticks: ticks,
@@ -222,7 +257,7 @@ impl NativeClock {
report.status = Some(raw);
match state.validate(&raw, after, ticks) {
Ok(bound) => {
report.trusted = !self.diagnostic;
report.trusted = ADAPTER_QUALIFIED && !self.diagnostic;
report.reason = if self.diagnostic {
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
} else {
@@ -235,26 +270,66 @@ impl NativeClock {
}
report
}
pub fn now(&self) -> Result<DateTime<Utc>> {
fn qualified_sample(&self) -> Result<(Sample, u64)> {
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
let mut cache = self
.cache
.lock()
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?;
let current = sample();
let observed = self
.state
.lock()
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?
.observe(current);
if observed.is_err() {
*cache = None;
observed?;
}
if let Some(cached) = *cache {
if let Some(bound) = cached.bound_at(current) {
return Ok((current, bound));
}
ensure!(
cached.bound.is_some()
|| current.interrupt.saturating_sub(cached.sample.interrupt) >= RETRY_AGE,
"CLOCK_RETRY_PENDING"
);
}
let report = self.report();
ensure!(report.trusted, "CLOCK_UNTRUSTED: {}", report.reason);
let ticks = report
.sample
.wall
.checked_sub(FILETIME_UNIX)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
DateTime::from_timestamp(
(ticks / SECOND).try_into()?,
((ticks % SECOND) * 100) as u32,
)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
let bound = report.error_bound_ticks.filter(|_| report.trusted);
*cache = Some(CachedQualification {
sample: report.sample,
bound,
valid_for: report.status.map_or(0, |status| {
CACHE_AGE.min(MAX_AGE.saturating_sub(status.sync_age))
}),
});
Ok((
report.sample,
bound.ok_or_else(|| anyhow!("CLOCK_UNTRUSTED: {}", report.reason))?,
))
}
pub fn now(&self) -> Result<DateTime<Utc>> {
utc(self.qualified_sample()?.0.wall)
}
}
fn utc(wall: u64) -> Result<DateTime<Utc>> {
let ticks = wall
.checked_sub(FILETIME_UNIX)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
DateTime::from_timestamp(
(ticks / SECOND).try_into()?,
((ticks % SECOND) * 100) as u32,
)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
}
/// Named-pipe diagnostics can never open the production clock gate.
pub fn named_pipe_diagnostic() -> ClockReport {
NativeClock {
state: Mutex::new(Continuity::default()),
cache: Mutex::new(None),
diagnostic: true,
}
.report()
@@ -376,6 +451,17 @@ impl rmm_agent_core::reconcile::SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
NativeClock::now(self)
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
let (sample, bound) = self.qualified_sample()?;
Ok(rmm_agent_core::reconcile::ClockReading {
own_wall: utc(sample.wall)?,
upper: utc(sample.wall + bound)?,
})
}
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let (sample, bound) = self.qualified_sample()?;
Ok((utc(sample.wall - bound)?, utc(sample.wall + bound)?))
}
}
#[cfg(windows)]
fn sample() -> Sample {
@@ -401,7 +487,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
#[link(name = "advapi32")]
unsafe extern "C" {
fn rmm_clock_query(status: *mut Status) -> u32;
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
fn rmm_local_clock_query(status: *mut Status) -> u32;
}
let mut status = Status::default();
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
@@ -409,7 +495,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
if diagnostic {
rmm_clock_query(&mut status)
} else {
rmm_clock_alpc_query(&mut status)
rmm_local_clock_query(&mut status)
}
};
(code, status)
@@ -522,8 +608,9 @@ mod tests {
},
)
}
#[cfg(not(windows))]
#[test]
fn production_clock_stays_closed_until_native_adapter_qualification() {
fn production_windows_clock_is_unavailable_on_other_platforms() {
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
assert_eq!(
NativeClock::new().now().unwrap_err().to_string(),
@@ -559,7 +646,7 @@ mod tests {
Status { state: 1, ..s },
Status { leap: 3, ..s },
Status {
last_result: 2,
last_result: 3,
..s
},
Status { stratum: 16, ..s },
@@ -585,6 +672,61 @@ mod tests {
}
}
#[test]
fn missed_poll_keeps_a_bounded_last_good_sample() {
let (s, v) = good();
let age = 2 * 3600 * SECOND;
for last_result in [1, 2] {
let held = Status {
last_result,
last_sync: v.wall - age,
sync_age: age,
..s
};
assert!(evaluate(&held, v.wall, 100).is_ok());
}
let old = Status {
last_result: 2,
last_sync: v.wall - MAX_AGE - 1,
sync_age: MAX_AGE + 1,
..s
};
assert!(evaluate(&old, v.wall, 100).is_err());
}
#[test]
fn cached_bound_expires_and_rejects_wall_step_and_suspend() {
let (_, mut sample) = good();
let cache = CachedQualification {
sample,
bound: Some(SECOND),
valid_for: CACHE_AGE,
};
sample.wall += SECOND;
sample.interrupt += SECOND;
sample.unbiased += SECOND;
assert_eq!(cache.bound_at(sample), Some(SECOND + 150));
assert_eq!(
cache.bound_at(Sample {
wall: sample.wall + 2 * SECOND,
..sample
}),
None
);
assert_eq!(
cache.bound_at(Sample {
unbiased: sample.unbiased - 2 * SECOND,
..sample
}),
None
);
let elapsed = CACHE_AGE;
let expired = Sample {
wall: cache.sample.wall + elapsed,
interrupt: cache.sample.interrupt + elapsed,
unbiased: cache.sample.unbiased + elapsed,
};
assert_eq!(cache.bound_at(expired), None);
}
#[test]
fn suspend_closes_until_actual_post_resume_sync() {
let (s, v) = good();
let mut c = Continuity::default();
+19 -10
View File
@@ -899,9 +899,14 @@ 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 = if settings.windows_update_only() || settings.managed_scripts() {
let role = rmm_time_attestation::Role::SystemHelper;
let clock = if settings.managed_scripts() {
RuntimeClock::local(role)
} else if settings.windows_update_only() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
} else {
RuntimeClock::new(role)
}.for_generation(0);
let boot = WindowsBoot::capture()?;
Ok(Self {
settings,
@@ -1806,14 +1811,18 @@ 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 update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
.map(crate::update_control_ipc::Server::bind).transpose()?;
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))?;
let time_worker = if time_clock.uses_local_clock() {
None
} else {
let time_pin = helper.pin().clone();
let time_server = ipc::Server::bind_time(time_pin.clone())?;
Some(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);
let mut next_update_unknown=Instant::now();
while !STOP.load(Ordering::SeqCst) {
@@ -1890,9 +1899,9 @@ 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"))??;
if let Some(worker) = time_worker {
worker.join().map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
}
Ok(())
})();
scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
@@ -53,6 +53,7 @@ pub fn clock_code(error: &anyhow::Error) -> &'static str {
"TIME_RUNTIME_NO_CONNECTION",
"TIME_LOCAL_WALL_OUTSIDE_BOUND",
"TIME_SOURCE_AGE_AT_CHECK",
"TIME_WINDOWS_LOCAL_CLOCK",
];
error
.chain()
+15 -5
View File
@@ -839,6 +839,10 @@ impl Agent {
) -> Result<()> {
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
let clock = self.clock.native.source();
if clock.uses_local_clock() {
return Ok(());
}
// Presence opts into sampling only. Each role opens and verifies the
// protected profile and signed response itself before accepting time.
let Some(mode) = SamplingMode::configured(self.config.enable_jobs, Path::new(CONFIG_PATH))?
@@ -860,7 +864,6 @@ impl Agent {
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();
@@ -3072,10 +3075,17 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
let clock=JobClock::new(config.enable_jobs);
#[cfg(feature = "system-helper")]
let clock = if let Some(policy) = &config.localservice_time_policy {
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
).for_generation(0) }
use rmm_agent_windows::signed_clock::RuntimeClock;
let source = if config.windows_update_helper {
RuntimeClock::enrolled_local_service(
binding.clone().context("JOB_BINDING_REQUIRED")?,
policy.clone(),
installed_tenant.context("INSTALLED_TENANT_REQUIRED")?,
)
} else {
RuntimeClock::local(rmm_time_attestation::Role::Agent)
};
JobClock { enabled: true, native: source.for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
+18
View File
@@ -1410,6 +1410,7 @@ mod installed {
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
native: Option<Arc<crate::clock::NativeClock>>,
enrolled_helper: Option<ipc::PeerPin>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
@@ -1423,11 +1424,20 @@ mod installed {
pub fn new(role: Role) -> Self {
Self {
role,
native: None,
enrolled_helper: None,
local_policy: None,
state: Arc::new(Mutex::new(None)),
}
}
pub fn local(role: Role) -> Self {
let mut clock = Self::new(role);
clock.native = Some(Arc::new(crate::clock::NativeClock::new()));
clock
}
pub fn uses_local_clock(&self) -> bool {
self.native.is_some()
}
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
@@ -1528,6 +1538,10 @@ mod installed {
}
fn bounds(&self) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::bounds(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state
@@ -1544,6 +1558,10 @@ mod installed {
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::reading(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state