Merge live Windows agent 0.1.27 source into the deployed server state
Rust development slice / linux (push) Failing after 14s
Rust development slice / linux (push) Failing after 14s
main now matches what runs on discovery.ease-technologies.de on 2026-11-20: - Server, gateway, public API and WebUI: image rmm-dev-server:79f236b (schema 47), plus the follow-up docs commitfb35dbd. - Windows agent and helper 0.1.27: signed release build 28 from 52c352c; hashes verified on the Windows test guest. - Linux agent 0.1.0-mvp.14 (62cb52b) and OPNsense agent 0.1.0-opnsense.6 are already ancestors of79f236b. Conflict in crates/agent-windows/src/native.rs resolved to the released Windows side (os_inventory with missing DisplayVersion handling). cargo check passes for the Linux workspace and for rmm-agent-windows on x86_64-pc-windows-gnu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -205,6 +205,7 @@ pub struct HelperSync<V = DefaultVerifier> {
|
||||
born: DateTime<Utc>,
|
||||
capture: Option<Capture>,
|
||||
lease: Option<Lease>,
|
||||
integrity: Option<crate::ledger::IntegrityMonitor>,
|
||||
}
|
||||
impl HelperSync<DefaultVerifier> {
|
||||
/// No persisted ready bit can open a newly started helper.
|
||||
@@ -222,6 +223,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
born: clock.now()?,
|
||||
capture: None,
|
||||
lease: None,
|
||||
integrity: None,
|
||||
})
|
||||
}
|
||||
/// Select exactly one protected helper execution identity, closing leases.
|
||||
@@ -230,6 +232,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
self.identity = identity;
|
||||
self
|
||||
}
|
||||
/// Use with one protected SQLite connection retained for this instance.
|
||||
/// The native owner must run a full check before any new host effect.
|
||||
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
|
||||
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
|
||||
self
|
||||
}
|
||||
pub fn close(&mut self) {
|
||||
self.lease = None;
|
||||
self.capture = None;
|
||||
@@ -288,7 +296,8 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
ledger_fingerprint: lease.fingerprint.clone(),
|
||||
captured_at: capture.captured_at,
|
||||
};
|
||||
self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?;
|
||||
let audit_history = self.integrity.is_none();
|
||||
self.verify_no_start_anchor(db, guard, &anchor, clock, boot, audit_history)?;
|
||||
Ok(anchor)
|
||||
}
|
||||
/// Consume exactly the approved update attempt and delegate its ORIGINAL
|
||||
@@ -389,9 +398,9 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
tx.commit()?;
|
||||
return Ok(outcome);
|
||||
}
|
||||
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
|
||||
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
|
||||
let observation = guard.verify_no_dispatch(request, anchor)?;
|
||||
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
|
||||
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
|
||||
ensure!(
|
||||
!observation.intent_id.is_nil()
|
||||
&& digest(&observation.intent_sha256)
|
||||
@@ -421,6 +430,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
anchor: &NoStartAnchor,
|
||||
clock: &impl Clock,
|
||||
boot: &impl BootSource,
|
||||
audit_history: bool,
|
||||
) -> Result<DateTime<Utc>> {
|
||||
guard.check(db)?;
|
||||
let now = clock.now()?;
|
||||
@@ -445,15 +455,18 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
&& ledger_fingerprint(db)? == anchor.ledger_fingerprint,
|
||||
"DENIAL_HELPER_LINEAGE_CHANGED"
|
||||
);
|
||||
// Exact equality is deliberate: a first implementation refuses even
|
||||
// legitimate intervening progress rather than inventing lineage links.
|
||||
verify_checkpoint_repair_history_with(
|
||||
db,
|
||||
&self.binding,
|
||||
None,
|
||||
self.identity,
|
||||
&self.verifier,
|
||||
)?;
|
||||
// Idle anchor capture checks the current signed head. The native
|
||||
// executor audits the full history before execution, and abandonment
|
||||
// always audits it under the same transaction before recording evidence.
|
||||
if audit_history {
|
||||
verify_checkpoint_repair_history_with(
|
||||
db,
|
||||
&self.binding,
|
||||
None,
|
||||
self.identity,
|
||||
&self.verifier,
|
||||
)?;
|
||||
}
|
||||
let (response, raw): (Vec<u8>, Vec<u8>) = db.query_row(
|
||||
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
|
||||
[anchor.decision_id.to_string()],
|
||||
@@ -483,8 +496,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
&& decision.helper_journal_id == Some(anchor.journal_id)
|
||||
&& decision.helper_checkpoint == anchor.checkpoint
|
||||
&& decision.connection_generation == anchor.connection_generation
|
||||
&& decision.request_hash == anchor.sync_request_sha256
|
||||
&& capture.journal_id == anchor.journal_id
|
||||
&& capture.checkpoint == anchor.checkpoint
|
||||
&& capture.captured_at == anchor.captured_at
|
||||
&& capture.boot_id == anchor.boot_id
|
||||
&& capture.captured_at <= decision.issued_at
|
||||
&& capture.captured_at <= now,
|
||||
"DENIAL_CONFIRMED_READY_REQUIRED"
|
||||
);
|
||||
@@ -523,7 +540,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
);
|
||||
let boot_id = boot.current_boot()?;
|
||||
ensure!(!boot_id.is_nil(), "BOOT_ID_REQUIRED");
|
||||
initialize(db, &self.binding)?;
|
||||
if let Some(integrity) = &mut self.integrity {
|
||||
integrity.check(db, false, "ROOT_LEDGER_INTEGRITY")?;
|
||||
initialize_schema(db, &self.binding)?;
|
||||
} else {
|
||||
initialize(db, &self.binding)?;
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let meta = metadata(&tx)?;
|
||||
ensure!(meta.fault.is_none(), "HELPER_MANUAL_RECOVERY_REQUIRED");
|
||||
@@ -1031,13 +1053,17 @@ struct Meta {
|
||||
agent_checkpoint: u64,
|
||||
}
|
||||
fn initialize(db: &Connection, binding: &Binding) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "ROOT_LEDGER_INTEGRITY");
|
||||
crate::ledger::check_integrity(db, "ROOT_LEDGER_INTEGRITY")?;
|
||||
initialize_schema(db, binding)
|
||||
}
|
||||
|
||||
fn initialize_schema(db: &Connection, binding: &Binding) -> Result<()> {
|
||||
db.execute_batch("PRAGMA synchronous=FULL;
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,binding_sha256 TEXT NOT NULL,last_decision TEXT,fault TEXT,agent_journal_id TEXT,agent_checkpoint INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,fingerprint TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_captures(checkpoint INTEGER PRIMARY KEY,snapshot BLOB NOT NULL,fingerprint TEXT NOT NULL,captured_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);")?;
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS helper_sync_decisions_checkpoint ON helper_sync_decisions(checkpoint);")?;
|
||||
let legacy_captures: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='helper_sync_captures')",
|
||||
[], |row| row.get(0),
|
||||
@@ -1175,23 +1201,23 @@ pub fn verify_checkpoint_repair_history_with(
|
||||
) -> Result<()> {
|
||||
let meta = metadata(db)?;
|
||||
validate_history(db, binding, &meta, meta.generation, verifier)?;
|
||||
let entry_count: u64 = db.query_row(
|
||||
"SELECT count(*) FROM helper_sync_decisions",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
ensure!(entry_count <= 100000, "REPAIR_HISTORY_LIMIT");
|
||||
let mut statement = db.prepare(
|
||||
"SELECT response,request,checkpoint FROM helper_sync_decisions ORDER BY checkpoint",
|
||||
)?;
|
||||
let entries = statement
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, Vec<u8>>(0)?,
|
||||
r.get::<_, Vec<u8>>(1)?,
|
||||
r.get::<_, u64>(2)?,
|
||||
))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(entries.len() <= 100000, "REPAIR_HISTORY_LIMIT");
|
||||
let mut entries = statement.query([])?;
|
||||
let mut previous = None;
|
||||
let mut previous_checkpoint = 0;
|
||||
let mut previous_agent_checkpoint = 0;
|
||||
for (signed, raw, checkpoint) in entries {
|
||||
while let Some(entry) = entries.next()? {
|
||||
let signed: Vec<u8> = entry.get(0)?;
|
||||
let raw: Vec<u8> = entry.get(1)?;
|
||||
let checkpoint: u64 = entry.get(2)?;
|
||||
let response: SignedResponse = serde_json::from_slice(&signed)?;
|
||||
let parsed: ReconcileDecisionPayload = serde_json::from_slice(&response.decision_bytes)?;
|
||||
let decision = verify(verifier, binding, &response, parsed.issued_at)?;
|
||||
|
||||
@@ -7,7 +7,8 @@ use rmm_domain::{
|
||||
jobs::hash,
|
||||
reconciliation::{ReconciledOutcome, canonical_outcome_bytes},
|
||||
};
|
||||
use rusqlite::{OptionalExtension, TransactionBehavior, params};
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use std::time::{Duration, Instant};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
|
||||
@@ -29,11 +30,48 @@ pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
|
||||
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
|
||||
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "JOURNAL_INTEGRITY");
|
||||
check_integrity(db, "JOURNAL_INTEGRITY")
|
||||
}
|
||||
|
||||
pub fn check_integrity(db: &Connection, error_code: &'static str) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |row| row.get(0))?;
|
||||
ensure!(check == "ok", "{error_code}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Full integrity scans for an owner holding one protected, long-lived SQLite
|
||||
/// connection. External commits and schema changes require another scan even
|
||||
/// when the interval has not elapsed. No cached result authorizes an effect.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IntegrityMonitor {
|
||||
checked: Option<(u64, u64, Instant)>,
|
||||
}
|
||||
|
||||
impl IntegrityMonitor {
|
||||
pub(crate) fn check(
|
||||
&mut self,
|
||||
db: &Connection,
|
||||
required: bool,
|
||||
error_code: &'static str,
|
||||
) -> Result<()> {
|
||||
let data: u64 = db.query_row("PRAGMA data_version", [], |row| row.get(0))?;
|
||||
let schema: u64 = db.query_row("PRAGMA schema_version", [], |row| row.get(0))?;
|
||||
if !required
|
||||
&& self.checked.is_some_and(|(previous_data, previous_schema, checked)| {
|
||||
data == previous_data
|
||||
&& schema == previous_schema
|
||||
&& checked.elapsed() < Duration::from_secs(300)
|
||||
})
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
self.checked = None;
|
||||
check_integrity(db, error_code)?;
|
||||
self.checked = Some((data, schema, Instant::now()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a human WebUI closure replaces the unresolved local outcome, keep the
|
||||
/// exact original outcome bytes once. A differing second copy fails closed.
|
||||
pub(crate) fn retain_closure_original(
|
||||
@@ -379,3 +417,34 @@ pub fn start_witness_bytes(
|
||||
"reauthentication_required":true,"postconditions_passed":false});
|
||||
Ok(serde_json::to_vec(&evidence)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod integrity_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn idle_integrity_reuses_the_check_but_reaudits_external_changes_and_expiry() {
|
||||
let path = std::env::temp_dir().join(format!("rmm-integrity-{}.sqlite", Uuid::new_v4()));
|
||||
{
|
||||
let db = Connection::open(&path).unwrap();
|
||||
db.execute_batch("CREATE TABLE sample(id INTEGER PRIMARY KEY);").unwrap();
|
||||
let mut monitor = IntegrityMonitor::default();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
let first = monitor.checked.unwrap();
|
||||
db.execute("INSERT INTO sample VALUES (1)", []).unwrap();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
assert_eq!(monitor.checked, Some(first));
|
||||
|
||||
let peer = Connection::open(&path).unwrap();
|
||||
peer.execute("INSERT INTO sample VALUES (2)", []).unwrap();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
let changed = monitor.checked.unwrap();
|
||||
assert_ne!(changed.0, first.0);
|
||||
|
||||
monitor.checked = Some((changed.0, changed.1, changed.2 - Duration::from_secs(300)));
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
assert!(monitor.checked.unwrap().2 >= changed.2);
|
||||
}
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ pub struct ClientSync<V = DefaultVerifier> {
|
||||
verifier: V,
|
||||
helper_identity: HelperIdentity,
|
||||
pending: Option<PreparedSync>,
|
||||
integrity: Option<crate::ledger::IntegrityMonitor>,
|
||||
channel: Option<Channel>,
|
||||
gate: Option<Gate>,
|
||||
}
|
||||
@@ -117,6 +118,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
verifier,
|
||||
helper_identity: HelperIdentity::Root,
|
||||
pending: None,
|
||||
integrity: None,
|
||||
channel: None,
|
||||
gate: None,
|
||||
}
|
||||
@@ -127,6 +129,11 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
self.helper_identity = identity;
|
||||
self
|
||||
}
|
||||
/// Use with one protected SQLite connection retained for this instance.
|
||||
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
|
||||
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
|
||||
self
|
||||
}
|
||||
/// Invoke on every authenticated/fenced ServerHello or transport loss.
|
||||
pub fn close(&mut self) {
|
||||
self.gate = None;
|
||||
@@ -606,7 +613,17 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
|
||||
"UNAUTHENTICATED_CHANNEL"
|
||||
);
|
||||
initialize(db)?;
|
||||
if let Some(integrity) = &mut self.integrity {
|
||||
let work_pending: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
integrity.check(db, work_pending, "JOURNAL_INTEGRITY")?;
|
||||
initialize_schema(db)?;
|
||||
} else {
|
||||
initialize(db)?;
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let meta = metadata(&tx)?;
|
||||
ensure!(meta.fault.is_none(), "SYNC_MANUAL_RECOVERY_REQUIRED");
|
||||
@@ -1147,8 +1164,11 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
}
|
||||
|
||||
pub fn initialize(db: &Connection) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "JOURNAL_INTEGRITY");
|
||||
crate::ledger::check_integrity(db, "JOURNAL_INTEGRITY")?;
|
||||
initialize_schema(db)
|
||||
}
|
||||
|
||||
fn initialize_schema(db: &Connection) -> Result<()> {
|
||||
db.execute_batch("PRAGMA synchronous=FULL;
|
||||
CREATE TABLE IF NOT EXISTS reconcile_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,high_sequence INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,last_decision TEXT,pending_request TEXT,helper_id TEXT,helper_checkpoint INTEGER NOT NULL DEFAULT 0,fault TEXT);
|
||||
CREATE TABLE IF NOT EXISTS reconcile_requests(id TEXT PRIMARY KEY,request BLOB NOT NULL,envelope BLOB NOT NULL,generation INTEGER NOT NULL,response BLOB);
|
||||
|
||||
@@ -466,6 +466,31 @@ struct Fixture {
|
||||
identity: HelperIdentity,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_anchor_checks_the_head_but_abandonment_rejects_damaged_history() {
|
||||
let (mut f, sync, _, request, mut guard) = denial_case();
|
||||
let mut sync = sync.with_periodic_idle_integrity_checks();
|
||||
f.clock.now += Duration::seconds(1);
|
||||
let capture = f.snapshot(&mut sync, 7);
|
||||
let raw = f.request(&capture);
|
||||
let ready = f.decision(&capture, &raw, 7, true);
|
||||
assert!(f.apply(&mut sync, &ready, &raw).unwrap().ready);
|
||||
guard.intent_recorded_at = f.clock.now;
|
||||
f.db.execute(
|
||||
"UPDATE helper_sync_decisions SET response=X'00' WHERE checkpoint < ?1",
|
||||
[capture.checkpoint],
|
||||
).unwrap();
|
||||
|
||||
let anchor = sync.no_start_anchor(&f.db, &guard, 7, &f.clock, &f.boot).unwrap();
|
||||
guard.anchor_sha256 = hash(&serde_json::to_vec(&anchor).unwrap());
|
||||
let before = denial_ledger_bytes(&f.db);
|
||||
assert!(
|
||||
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(denial_ledger_bytes(&f.db), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor() {
|
||||
let mut f = Fixture::new();
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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();
|
||||
|
||||
@@ -899,13 +899,15 @@ 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()?;
|
||||
let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock)
|
||||
.ok()
|
||||
.map(|s| s.with_helper_identity(HelperIdentity::System));
|
||||
Ok(Self {
|
||||
settings,
|
||||
pin,
|
||||
@@ -914,7 +916,8 @@ impl SystemHelper {
|
||||
db,
|
||||
clock,
|
||||
boot,
|
||||
sync,
|
||||
// The initial connection creates the reconciler using its own qualified time.
|
||||
sync: None,
|
||||
last_diagnostic: None,
|
||||
last_apply_diagnostic: None,
|
||||
unsettled_msi: None,
|
||||
@@ -1008,14 +1011,17 @@ impl SystemHelper {
|
||||
}
|
||||
fn sync(&mut self) -> Result<&mut HelperSync<DalekVerifier>> {
|
||||
if self.sync.is_none() {
|
||||
self.sync = Some(
|
||||
HelperSync::with_verifier(
|
||||
self.settings.binding.clone(),
|
||||
DalekVerifier,
|
||||
&self.clock,
|
||||
)?
|
||||
.with_helper_identity(HelperIdentity::System),
|
||||
);
|
||||
let sync = HelperSync::with_verifier(
|
||||
self.settings.binding.clone(),
|
||||
DalekVerifier,
|
||||
&self.clock,
|
||||
)?
|
||||
.with_helper_identity(HelperIdentity::System);
|
||||
self.sync = Some(if self.settings.managed_scripts() {
|
||||
sync.with_periodic_idle_integrity_checks()
|
||||
} else {
|
||||
sync
|
||||
});
|
||||
}
|
||||
self.sync.as_mut().context("SYSTEM_SYNC_CLOSED")
|
||||
}
|
||||
@@ -1290,6 +1296,16 @@ impl SystemHelper {
|
||||
}
|
||||
ensure!(self.settings.enable_effects, "SYSTEM_EFFECTS_DISABLED");
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
if self.settings.managed_scripts() {
|
||||
ledger::check_integrity(&self.db, "ROOT_LEDGER_INTEGRITY")?;
|
||||
rmm_agent_core::helper_reconcile::verify_checkpoint_repair_history_with(
|
||||
&self.db,
|
||||
&self.settings.binding,
|
||||
None,
|
||||
HelperIdentity::System,
|
||||
&DalekVerifier,
|
||||
)?;
|
||||
}
|
||||
self.sync()?;
|
||||
ensure!(
|
||||
self.sync.as_ref().unwrap().can_start(
|
||||
@@ -1795,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) {
|
||||
@@ -1879,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()
|
||||
|
||||
@@ -227,28 +227,51 @@ pub fn private_path(path: &Path, directory: bool) -> Result<()> {
|
||||
}
|
||||
fn registry_string(name: &str) -> Result<String> {
|
||||
let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
|
||||
let name = wide(name);
|
||||
let value_name = wide(name);
|
||||
let mut bytes = vec![0u16; 2048];
|
||||
let mut size = (bytes.len() * 2) as u32;
|
||||
let status = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
value_name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
ptr::null_mut(),
|
||||
bytes.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "OS_REGISTRY {name} (Win32 {status})");
|
||||
ensure!(
|
||||
unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
ptr::null_mut(),
|
||||
bytes.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
} == 0,
|
||||
"OS_REGISTRY"
|
||||
size >= 2 && size % 2 == 0 && size as usize <= bytes.len() * 2,
|
||||
"OS_REGISTRY_SIZE {name}"
|
||||
);
|
||||
ensure!(
|
||||
size >= 2 && size as usize <= bytes.len() * 2,
|
||||
"OS_REGISTRY_SIZE"
|
||||
);
|
||||
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
|
||||
String::from_utf16(&bytes[..size as usize / 2 - 1])
|
||||
.with_context(|| format!("OS_REGISTRY_ENCODING {name}"))
|
||||
}
|
||||
|
||||
fn os_inventory(read: impl Fn(&str) -> Result<String>) -> Result<(String, Value)> {
|
||||
let product = read("ProductName")?;
|
||||
let build = read("CurrentBuildNumber")?;
|
||||
// Older Windows releases can omit DisplayVersion. Both version labels are
|
||||
// optional; the product and build still identify the OS without either.
|
||||
let version = |name| read(name).ok().filter(|s| !s.trim().is_empty());
|
||||
let display = version("DisplayVersion");
|
||||
let release = if display.is_none() {
|
||||
version("ReleaseId")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let os = match (&display, &release) {
|
||||
(Some(display), _) => format!("{product}; DisplayVersion={display}; Build={build}"),
|
||||
(None, Some(release)) => format!("{product}; ReleaseId={release}; Build={build}"),
|
||||
(None, None) => format!("{product}; Build={build}"),
|
||||
};
|
||||
let mut data = json!({"product_name":product,"display_version":display,"build":build});
|
||||
if let Some(release) = release {
|
||||
data["release_id"] = json!(release);
|
||||
}
|
||||
Ok((os, data))
|
||||
}
|
||||
pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
|
||||
let mut name = [0u16; 256];
|
||||
@@ -307,15 +330,14 @@ pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
|
||||
let system = std::env::var("SystemDrive").context("SYSTEM_DRIVE")?.to_ascii_uppercase();
|
||||
let (available, total) = disk_space(&wide(format!("{system}\\"))).context("VOLUME_QUERY")?;
|
||||
let volumes = fixed_volumes(&system, available, total);
|
||||
let product = registry_string("ProductName")?;
|
||||
let display = registry_string("DisplayVersion")?;
|
||||
let build = registry_string("CurrentBuildNumber")?;
|
||||
let os = format!("{product}; DisplayVersion={display}; Build={build}");
|
||||
let (os, mut os_data) = os_inventory(registry_string)?;
|
||||
os_data["installed_at"] = json!(install_date());
|
||||
os_data["booted_at"] = json!(booted_at);
|
||||
let completed = Utc::now();
|
||||
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
|
||||
"collection_started_at":started,"collection_completed_at":completed,
|
||||
"observations":[
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":os_data},
|
||||
{"scope":"windows.volumes","source_id":"windows.win32:GetLogicalDrives;GetDriveTypeW;GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available,"drives":volumes}},
|
||||
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||
]});
|
||||
@@ -374,6 +396,47 @@ pub async fn boot_id() -> Result<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
fn os_fixture(display: Option<&str>, release: Option<&str>) -> (String, serde_json::Value) {
|
||||
super::os_inventory(|name| {
|
||||
match name {
|
||||
"ProductName" => Some("Windows 10 Enterprise LTSC"),
|
||||
"CurrentBuildNumber" => Some("17763"),
|
||||
"DisplayVersion" => display,
|
||||
"ReleaseId" => release,
|
||||
_ => panic!("unexpected registry value: {name}"),
|
||||
}
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing {name}"))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_prefers_display_version() {
|
||||
let (os, data) = os_fixture(Some("22H2"), Some("2009"));
|
||||
assert!(os.contains("DisplayVersion=22H2"));
|
||||
assert_eq!(data["display_version"], "22H2");
|
||||
assert!(data.get("release_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_uses_legacy_release_id_when_display_version_is_missing() {
|
||||
let (os, data) = os_fixture(None, Some("1809"));
|
||||
assert_eq!(os, "Windows 10 Enterprise LTSC; ReleaseId=1809; Build=17763");
|
||||
assert!(data["display_version"].is_null());
|
||||
assert_eq!(data["release_id"], "1809");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_keeps_product_and_build_without_version_labels() {
|
||||
for display in [None, Some(" ")] {
|
||||
let (os, data) = os_fixture(display, None);
|
||||
assert_eq!(os, "Windows 10 Enterprise LTSC; Build=17763");
|
||||
assert!(data["display_version"].is_null());
|
||||
assert_eq!(data["build"], "17763");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_inventory_has_real_windows_sources_and_no_fake_inodes() {
|
||||
let v = super::snapshot().unwrap();
|
||||
|
||||
@@ -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();
|
||||
@@ -1291,8 +1294,8 @@ impl Agent {
|
||||
&& !self.helper_apply_unconfirmed
|
||||
&& !self.prepared
|
||||
&& self.running.is_none()
|
||||
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
|
||||
&& self.helper_probe_at.elapsed() >= Duration::from_secs(30)
|
||||
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
|
||||
{
|
||||
let agent = self.identity.agent_id.clone();
|
||||
let asset = self.identity.asset_id.clone();
|
||||
@@ -2663,8 +2666,9 @@ impl Agent {
|
||||
let mut heartbeat = Instant::now() - Duration::from_secs(60);
|
||||
let mut previous_cpu = None;
|
||||
let mut heartbeat_after = Duration::from_secs(30);
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let active_tick = Duration::from_millis(20);
|
||||
let idle_tick = Duration::from_millis(250);
|
||||
let mut next_tick = tokio::time::Instant::now();
|
||||
let mut readiness_at = Instant::now() - Duration::from_secs(5);
|
||||
#[cfg(feature = "system-helper")]
|
||||
let mut update_control_at = Instant::now() - Duration::from_secs(2);
|
||||
@@ -2675,9 +2679,19 @@ impl Agent {
|
||||
running.cancel.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let control_pending = self.running.is_some()
|
||||
|| self.prepared
|
||||
|| self.deferred_sync.is_some()
|
||||
|| self.deferred_permit.is_some()
|
||||
|| self.helper_control_pending();
|
||||
#[cfg(feature = "system-helper")]
|
||||
let control_pending = control_pending || self.helper_probe.is_some();
|
||||
let cadence = if control_pending { active_tick } else { idle_tick };
|
||||
next_tick = next_tick.min(tokio::time::Instant::now() + cadence);
|
||||
tokio::select! {
|
||||
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
|
||||
_=tick.tick()=>{
|
||||
_=tokio::time::sleep_until(next_tick)=>{
|
||||
next_tick = tokio::time::Instant::now() + cadence;
|
||||
if !stop.load(Ordering::SeqCst) && self.poll_sync_apply(generation,true).is_err(){self.close_gate();needs_sync=true;}
|
||||
#[cfg(feature = "system-helper")]
|
||||
if !stop.load(Ordering::SeqCst) && self.poll_helper(&channel,generation).await.is_err() {self.close_gate();needs_sync=self.sync.is_some();}
|
||||
@@ -2709,7 +2723,9 @@ impl Agent {
|
||||
if self.sync.is_some() && !self.prepared && !self.helper_control_busy_for_sync() && rmm_agent_windows::job_readiness::refresh_due(needs_sync,sync_at.elapsed(),self.sync.as_ref().and_then(|s|s.validity_deadline()),self.clock.reading().ok().map(|r|r.upper)) {
|
||||
if self.start_sync(&channel,generation).await.is_err(){self.close_gate();needs_sync=true;}else{needs_sync=false;}sync_at=Instant::now();
|
||||
}
|
||||
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
|
||||
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.config.enable_jobs
|
||||
&& self.journal.connection().prepare_cached("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state='accepted' AND cancel_requested=0)")?.query_row([], |row| row.get::<_, bool>(0))?
|
||||
&& self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
|
||||
// A transiently stale clock skips this tick; it must not end the session.
|
||||
if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
|
||||
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
|
||||
@@ -3059,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 {
|
||||
@@ -3078,7 +3101,19 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
|
||||
ensure!(rmm_agent_windows::echo_probe::protected_scope()? == *scope, "WINDOWS_ECHO_CONFIGURATION_CHANGED");
|
||||
}
|
||||
}
|
||||
let sync=if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
|
||||
let sync = if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {
|
||||
binding.clone().map(|binding| {
|
||||
let sync = reconcile::ClientSync::new(binding)
|
||||
.with_helper_identity(reconcile::HelperIdentity::System);
|
||||
if config.localservice_time_policy.is_some() {
|
||||
sync.with_periodic_idle_integrity_checks()
|
||||
} else {
|
||||
sync
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
|
||||
let mut agent = Agent {
|
||||
config,
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user