Preserve Windows runtime state and qualify native guarded adapters
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -4,6 +4,15 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
system-helper = []
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rmm-helper-windows"
|
||||||
|
path = "src/bin/rmm-helper-windows.rs"
|
||||||
|
required-features = ["system-helper"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
chrono.workspace = true
|
chrono.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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_endpoints.c");
|
||||||
|
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
env::var("CARGO_CFG_TARGET_ARCH").as_deref(),
|
||||||
|
Ok("x86_64"),
|
||||||
|
"Windows clock RPC is qualified only for x86-64"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
env::var("CARGO_CFG_TARGET_ENV").as_deref(),
|
||||||
|
Ok("gnu"),
|
||||||
|
"Windows clock RPC currently requires the qualified GNU/clang toolchain"
|
||||||
|
);
|
||||||
|
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||||
|
let idl = env::current_dir().unwrap().join("native/w32time.idl");
|
||||||
|
for args in [
|
||||||
|
vec!["-h", "-H", "w32time.h"],
|
||||||
|
vec!["-c", "-o", "w32time_c.c"],
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
Command::new("x86_64-w64-mingw32-widl")
|
||||||
|
.current_dir(&out)
|
||||||
|
.args(["--win64", "-Oif"])
|
||||||
|
.args(args)
|
||||||
|
.arg(&idl)
|
||||||
|
.status()
|
||||||
|
.expect("Install mingw-w64-tools for the generated read-only RPC stub")
|
||||||
|
.success(),
|
||||||
|
"WIDL clock stub generation failed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Clang implements x64 Windows SEH in the C boundary. MinGW GCC's __try
|
||||||
|
// spelling is not sufficient; do not let an RPC exception unwind into Rust.
|
||||||
|
cc::Build::new()
|
||||||
|
.compiler("clang")
|
||||||
|
.flag("--target=x86_64-w64-windows-gnu")
|
||||||
|
.flag("-fms-extensions")
|
||||||
|
.flag("-Werror")
|
||||||
|
.include(&out)
|
||||||
|
.file(out.join("w32time_c.c"))
|
||||||
|
.file("native/clock_rpc.c")
|
||||||
|
.file("native/clock_endpoints.c")
|
||||||
|
.compile("rmm_clock_rpc");
|
||||||
|
println!("cargo:rustc-link-lib=rpcrt4");
|
||||||
|
println!("cargo:rustc-link-lib=advapi32");
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Temporary, read-only readiness service. Separate from the permanent agent;
|
||||||
|
//! no network/RMM jobs, no clock setting, no W32Time ACL/service changes.
|
||||||
|
#[path = "../src/clock.rs"]
|
||||||
|
mod clock;
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod service {
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use std::{
|
||||||
|
io::Write,
|
||||||
|
mem::{size_of, zeroed},
|
||||||
|
path::PathBuf,
|
||||||
|
ptr,
|
||||||
|
sync::{
|
||||||
|
OnceLock,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::CloseHandle,
|
||||||
|
Security::*,
|
||||||
|
System::{
|
||||||
|
Services::*,
|
||||||
|
Threading::{GetCurrentProcess, OpenProcessToken},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const NAME: &str = "RmmWindowsClockReadiness";
|
||||||
|
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
|
||||||
|
static HANDLE: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
static STAGE: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
fn wide(s: &str) -> Vec<u16> {
|
||||||
|
s.encode_utf16().chain(Some(0)).collect()
|
||||||
|
}
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct TokenEvidence {
|
||||||
|
user_sid: &'static str,
|
||||||
|
elevation_flag: u32,
|
||||||
|
elevation_type: i32,
|
||||||
|
administrator_member: bool,
|
||||||
|
system_user: bool,
|
||||||
|
}
|
||||||
|
fn token() -> Result<TokenEvidence> {
|
||||||
|
STAGE.store(10, Ordering::SeqCst);
|
||||||
|
let mut handle = ptr::null_mut();
|
||||||
|
ensure!(
|
||||||
|
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle) } != 0,
|
||||||
|
"READINESS_TOKEN"
|
||||||
|
);
|
||||||
|
let result = (|| {
|
||||||
|
STAGE.store(11, Ordering::SeqCst);
|
||||||
|
let mut size = 0;
|
||||||
|
unsafe {
|
||||||
|
GetTokenInformation(handle, TokenUser, ptr::null_mut(), 0, &mut size);
|
||||||
|
}
|
||||||
|
ensure!(size > 0 && size <= 4096, "READINESS_TOKEN_SIZE");
|
||||||
|
let mut user = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
GetTokenInformation(
|
||||||
|
handle,
|
||||||
|
TokenUser,
|
||||||
|
user.as_mut_ptr().cast(),
|
||||||
|
size,
|
||||||
|
&mut size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"READINESS_TOKEN_USER"
|
||||||
|
);
|
||||||
|
STAGE.store(12, Ordering::SeqCst);
|
||||||
|
let info = unsafe { &*user.as_ptr().cast::<TOKEN_USER>() };
|
||||||
|
ensure!(
|
||||||
|
unsafe { IsWellKnownSid(info.User.Sid, WinLocalServiceSid) } != 0,
|
||||||
|
"READINESS_NOT_LOCAL_SERVICE"
|
||||||
|
);
|
||||||
|
STAGE.store(13, Ordering::SeqCst);
|
||||||
|
let mut elevation: TOKEN_ELEVATION = unsafe { zeroed() };
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
GetTokenInformation(
|
||||||
|
handle,
|
||||||
|
TokenElevation,
|
||||||
|
(&mut elevation as *mut TOKEN_ELEVATION).cast(),
|
||||||
|
size_of::<TOKEN_ELEVATION>() as u32,
|
||||||
|
&mut size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"READINESS_ELEVATED"
|
||||||
|
);
|
||||||
|
STAGE.store(14, Ordering::SeqCst);
|
||||||
|
let mut elevation_type: TOKEN_ELEVATION_TYPE = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
GetTokenInformation(
|
||||||
|
handle,
|
||||||
|
TokenElevationType,
|
||||||
|
(&mut elevation_type as *mut TOKEN_ELEVATION_TYPE).cast(),
|
||||||
|
size_of::<TOKEN_ELEVATION_TYPE>() as u32,
|
||||||
|
&mut size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"READINESS_ELEVATION_TYPE"
|
||||||
|
);
|
||||||
|
let mut admin_sid = [0u64; 9];
|
||||||
|
let mut admin_size = 72;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
CreateWellKnownSid(
|
||||||
|
WinBuiltinAdministratorsSid,
|
||||||
|
ptr::null_mut(),
|
||||||
|
admin_sid.as_mut_ptr().cast(),
|
||||||
|
&mut admin_size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"READINESS_ADMIN_SID"
|
||||||
|
);
|
||||||
|
let mut admin = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
CheckTokenMembership(ptr::null_mut(), admin_sid.as_mut_ptr().cast(), &mut admin)
|
||||||
|
} != 0,
|
||||||
|
"READINESS_ADMIN_CHECK"
|
||||||
|
);
|
||||||
|
Ok(TokenEvidence {
|
||||||
|
user_sid: "S-1-5-19",
|
||||||
|
elevation_flag: elevation.TokenIsElevated,
|
||||||
|
elevation_type,
|
||||||
|
administrator_member: admin != 0,
|
||||||
|
system_user: unsafe { IsWellKnownSid(info.User.Sid, WinLocalSystemSid) } != 0,
|
||||||
|
})
|
||||||
|
})();
|
||||||
|
unsafe {
|
||||||
|
CloseHandle(handle);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
fn run() -> Result<()> {
|
||||||
|
let token = token()?;
|
||||||
|
STAGE.store(20, Ordering::SeqCst);
|
||||||
|
let case = CASE.get().unwrap();
|
||||||
|
let root =
|
||||||
|
PathBuf::from(r"C:\ProgramData\RustDiscoveryClockReadiness").join(case.to_string());
|
||||||
|
ensure!(root.is_dir() && !root.is_symlink(), "READINESS_ROOT");
|
||||||
|
// Preserve the actual token proof before entering foreign RPC code.
|
||||||
|
let mut token_file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(root.join("token.json"))?;
|
||||||
|
token_file.write_all(&serde_json::to_vec(&token)?)?;
|
||||||
|
token_file.sync_all()?;
|
||||||
|
let endpoints = super::clock::endpoint_report();
|
||||||
|
let mut endpoint_file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(root.join("endpoints.json"))?;
|
||||||
|
endpoint_file.write_all(&serde_json::to_vec(&endpoints)?)?;
|
||||||
|
endpoint_file.sync_all()?;
|
||||||
|
let clock = super::clock::NativeClock::new();
|
||||||
|
STAGE.store(30, Ordering::SeqCst);
|
||||||
|
let pipe = super::clock::named_pipe_diagnostic();
|
||||||
|
let first = clock.report();
|
||||||
|
std::thread::sleep(Duration::from_millis(750));
|
||||||
|
STAGE.store(31, Ordering::SeqCst);
|
||||||
|
let second = clock.report();
|
||||||
|
STAGE.store(40, Ordering::SeqCst);
|
||||||
|
let data = serde_json::to_vec_pretty(
|
||||||
|
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
||||||
|
)?;
|
||||||
|
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
|
||||||
|
STAGE.store(41, Ordering::SeqCst);
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(root.join("result.json"))?;
|
||||||
|
STAGE.store(42, Ordering::SeqCst);
|
||||||
|
file.write_all(&data)?;
|
||||||
|
STAGE.store(43, Ordering::SeqCst);
|
||||||
|
file.sync_all()?;
|
||||||
|
STAGE.store(44, Ordering::SeqCst);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn status(state: u32, error: u32) {
|
||||||
|
let handle = HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
||||||
|
if handle.is_null() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let value = SERVICE_STATUS {
|
||||||
|
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||||
|
dwCurrentState: state,
|
||||||
|
dwControlsAccepted: 0,
|
||||||
|
dwWin32ExitCode: error,
|
||||||
|
dwServiceSpecificExitCode: if error == 1066 {
|
||||||
|
STAGE.load(Ordering::SeqCst) as u32
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
},
|
||||||
|
dwCheckPoint: 0,
|
||||||
|
dwWaitHint: 10000,
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
SetServiceStatus(handle, &value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unsafe extern "system" fn control(
|
||||||
|
_: u32,
|
||||||
|
_: u32,
|
||||||
|
_: *mut std::ffi::c_void,
|
||||||
|
_: *mut std::ffi::c_void,
|
||||||
|
) -> u32 {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
unsafe extern "system" fn main(_: u32, _: *mut *mut u16) {
|
||||||
|
let name = wide(NAME);
|
||||||
|
let handle =
|
||||||
|
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
||||||
|
if handle.is_null() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
HANDLE.store(handle as usize, Ordering::SeqCst);
|
||||||
|
status(SERVICE_RUNNING, 0);
|
||||||
|
let result = run();
|
||||||
|
if result.is_ok() {
|
||||||
|
std::thread::sleep(Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||||
|
}
|
||||||
|
pub fn dispatch() -> Result<()> {
|
||||||
|
let args: Vec<_> = std::env::args().collect();
|
||||||
|
ensure!(
|
||||||
|
args.len() == 3 && args[1] == "--service",
|
||||||
|
"READINESS_SERVICE_ONLY"
|
||||||
|
);
|
||||||
|
let case = uuid::Uuid::parse_str(&args[2])?;
|
||||||
|
ensure!(case.get_version_num() == 4, "READINESS_CASE_UUID");
|
||||||
|
CASE.set(case).unwrap();
|
||||||
|
let mut name = wide(NAME);
|
||||||
|
let table = [
|
||||||
|
SERVICE_TABLE_ENTRYW {
|
||||||
|
lpServiceName: name.as_mut_ptr(),
|
||||||
|
lpServiceProc: Some(main),
|
||||||
|
},
|
||||||
|
SERVICE_TABLE_ENTRYW {
|
||||||
|
lpServiceName: ptr::null_mut(),
|
||||||
|
lpServiceProc: None,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
ensure!(
|
||||||
|
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
||||||
|
"READINESS_SCM"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
service::dispatch()
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn main() {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic()})).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
//! Fixed guest read-only persistence witness. No keys, job, grants or clock query.
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
use anyhow::ensure;
|
||||||
|
use serde_json::json;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::{fs, os::windows::io::AsRawHandle, path::Path};
|
||||||
|
use windows_sys::Win32::Storage::FileSystem::{
|
||||||
|
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
|
||||||
|
};
|
||||||
|
let state = Path::new(r"C:\ProgramData\RustDiscovery\state");
|
||||||
|
rmm_agent_windows::native::private_path(state, true)?;
|
||||||
|
let path = state.join("telemetry.sqlite");
|
||||||
|
rmm_agent_windows::native::private_path(&path, false)?;
|
||||||
|
let file = fs::File::open(&path)?;
|
||||||
|
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
|
||||||
|
// SAFETY: live read-only file handle and correctly sized writable structure.
|
||||||
|
ensure!(
|
||||||
|
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0,
|
||||||
|
"DATABASE_FILE_ID"
|
||||||
|
);
|
||||||
|
let db =
|
||||||
|
rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
|
||||||
|
db.execute_batch("BEGIN DEFERRED")?;
|
||||||
|
ensure!(
|
||||||
|
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||||
|
"JOURNAL_INTEGRITY"
|
||||||
|
);
|
||||||
|
let sequence: i64 =
|
||||||
|
db.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| {
|
||||||
|
r.get(0)
|
||||||
|
})?;
|
||||||
|
let agent: String = db.query_row("SELECT agent FROM identity", [], |r| r.get(0))?;
|
||||||
|
ensure!(
|
||||||
|
agent == "63ea15b2-0643-403d-b5b4-cba1288dbea3" && sequence >= 0,
|
||||||
|
"FIXED_EXISTING_IDENTITY"
|
||||||
|
);
|
||||||
|
let identity: Vec<String> = db
|
||||||
|
.prepare("SELECT agent FROM identity ORDER BY agent")?
|
||||||
|
.query_map([], |r| r.get(0))?
|
||||||
|
.collect::<rusqlite::Result<_>>()?;
|
||||||
|
let metadata: Vec<(String, i64)> = db
|
||||||
|
.prepare("SELECT key,value FROM metadata ORDER BY key")?
|
||||||
|
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
|
||||||
|
.collect::<rusqlite::Result<_>>()?;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for row in db
|
||||||
|
.prepare("SELECT id,payload FROM events ORDER BY id")?
|
||||||
|
.query_map([], |r| {
|
||||||
|
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
|
||||||
|
})?
|
||||||
|
{
|
||||||
|
let (id, bytes) = row?;
|
||||||
|
ensure!(
|
||||||
|
events.len() < 8 && bytes.len() <= 512 * 1024,
|
||||||
|
"LEGACY_EVENT_LIMIT"
|
||||||
|
);
|
||||||
|
events.push(json!({"id":id,"payload_sha256":format!("{:x}",Sha256::digest(&bytes)),"bytes":bytes.len()}));
|
||||||
|
}
|
||||||
|
let schema:Vec<(String,String,String)>=db.prepare("SELECT type,name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name")?.query_map([],|r|Ok((r.get(0)?,r.get(1)?,r.get::<_,Option<String>>(2)?.unwrap_or_default())))?.collect::<rusqlite::Result<_>>()?;
|
||||||
|
ensure!(schema.len() <= 64, "SCHEMA_LIMIT");
|
||||||
|
let mut counts = serde_json::Map::new();
|
||||||
|
for table in [
|
||||||
|
"job_attempts",
|
||||||
|
"job_events",
|
||||||
|
"reconcile_requests",
|
||||||
|
"reconcile_results",
|
||||||
|
"reconcile_receipts",
|
||||||
|
"reconcile_outcomes",
|
||||||
|
] {
|
||||||
|
if schema
|
||||||
|
.iter()
|
||||||
|
.any(|(kind, name, _)| kind == "table" && name == table)
|
||||||
|
{
|
||||||
|
let count: i64 =
|
||||||
|
db.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0))?;
|
||||||
|
counts.insert(table.into(), json!(count));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let counter = if schema.iter().any(|(_, name, _)| name == "counter") {
|
||||||
|
Some(db.query_row("SELECT seq FROM counter WHERE id=1", [], |r| {
|
||||||
|
r.get::<_, i64>(0)
|
||||||
|
})?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(counter) = counter {
|
||||||
|
ensure!(counter == sequence, "COUNTER_ALIAS");
|
||||||
|
}
|
||||||
|
let page_size: i64 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
|
||||||
|
let page_count: i64 = db.query_row("PRAGMA page_count", [], |r| r.get(0))?;
|
||||||
|
ensure!(
|
||||||
|
page_size == 4096 && page_count > 0 && page_count <= 262144,
|
||||||
|
"FINITE_FILE_BUDGET"
|
||||||
|
);
|
||||||
|
db.execute_batch("ROLLBACK")?;
|
||||||
|
let hash = |value: &serde_json::Value| -> anyhow::Result<String> {
|
||||||
|
Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(value)?)))
|
||||||
|
};
|
||||||
|
let value = json!({"read_only":true,"integrity":"ok","agent_id":agent,"sequence":sequence,
|
||||||
|
"pending_inventory_events":events.len(),"legacy_events":events,"identity_sha256":hash(&json!(identity))?,
|
||||||
|
"metadata_sha256":hash(&json!(metadata))?,"events_sha256":hash(&json!(events))?,
|
||||||
|
"schema":schema,"core_counts":counts,"counter":counter,"page_size":page_size,"page_count":page_count,
|
||||||
|
"database_file_id":{"volume":info.dwVolumeSerialNumber,"high":info.nFileIndexHigh,"low":info.nFileIndexLow},
|
||||||
|
"database_creation":{"high":info.ftCreationTime.dwHighDateTime,"low":info.ftCreationTime.dwLowDateTime},
|
||||||
|
"consumption_exists":state.join("consumption.sqlite").try_exists()?,"jobs_directory_exists":state.join("jobs").try_exists()?,
|
||||||
|
"private_key_read":false,"clock_queried":false,"jobs_created":false});
|
||||||
|
let encoded = serde_json::to_string(&value)?;
|
||||||
|
ensure!(encoded.len() <= 32768, "WITNESS_OUTPUT_LIMIT");
|
||||||
|
println!("{encoded}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn main() {
|
||||||
|
eprintln!("Native Windows-only read-only state witness");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/* Read-only local endpoint discovery for precisely the MS-W32T interface.
|
||||||
|
* No status invocation, no endpoint names/annotations leave this boundary.
|
||||||
|
*/
|
||||||
|
#define _WIN32_WINNT 0x0a00
|
||||||
|
#include <windows.h>
|
||||||
|
#include <rpc.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint32_t result, scanned, named_pipe, alpc, other, truncated;
|
||||||
|
} RmmClockEndpoints;
|
||||||
|
uint32_t rmm_clock_endpoints(RmmClockEndpoints *out) {
|
||||||
|
RPC_IF_ID interface_id = {0};
|
||||||
|
RPC_EP_INQ_HANDLE inquiry = NULL;
|
||||||
|
RPC_STATUS result;
|
||||||
|
memset(out, 0, sizeof(*out));
|
||||||
|
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &interface_id.Uuid);
|
||||||
|
if (result) return out->result = result;
|
||||||
|
interface_id.VersMajor = 4; interface_id.VersMinor = 1;
|
||||||
|
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &interface_id,
|
||||||
|
RPC_C_VERS_EXACT, NULL, &inquiry);
|
||||||
|
if (result) return out->result = result;
|
||||||
|
for (unsigned i = 0; i < 16; ++i) {
|
||||||
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
|
RPC_IF_ID actual = {0};
|
||||||
|
UUID object = {0};
|
||||||
|
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
|
||||||
|
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
|
||||||
|
if (annotation) RpcStringFreeW(&annotation);
|
||||||
|
if (result == RPC_X_NO_MORE_ENTRIES) { result = 0; break; }
|
||||||
|
if (result) break;
|
||||||
|
++out->scanned;
|
||||||
|
result = RpcBindingToStringBindingW(binding, &text);
|
||||||
|
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
|
||||||
|
if (!result) {
|
||||||
|
if (!wcscmp((wchar_t *)protocol, L"ncalrpc")) ++out->alpc;
|
||||||
|
else if (!wcscmp((wchar_t *)protocol, L"ncacn_np")) ++out->named_pipe;
|
||||||
|
else ++out->other;
|
||||||
|
}
|
||||||
|
if (protocol) RpcStringFreeW(&protocol);
|
||||||
|
if (text) RpcStringFreeW(&text);
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
if (result) break;
|
||||||
|
if (i == 15) out->truncated = 1;
|
||||||
|
}
|
||||||
|
RpcMgmtEpEltInqDone(&inquiry);
|
||||||
|
return out->result = result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
/* Only the authenticated local MS-W32T status operation is reachable here.
|
||||||
|
* NDR code is generated by WIDL; SEH must terminate inside C, never in Rust.
|
||||||
|
*/
|
||||||
|
#define _WIN32_WINNT 0x0a00
|
||||||
|
#include <windows.h>
|
||||||
|
#include <rpc.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include "w32time.h"
|
||||||
|
/* Documented public SDK API; older MinGW headers omit its declaration. */
|
||||||
|
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
|
||||||
|
|
||||||
|
typedef struct Allocation { struct Allocation *next; size_t size; } Allocation;
|
||||||
|
typedef struct { Allocation *head; size_t total; } Arena;
|
||||||
|
/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS
|
||||||
|
* in the mixed Rust/MinGW PE did not initialize such a thread's storage. */
|
||||||
|
static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT;
|
||||||
|
static DWORD arena_index = TLS_OUT_OF_INDEXES;
|
||||||
|
static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) {
|
||||||
|
(void)once; (void)parameter; (void)context;
|
||||||
|
arena_index = TlsAlloc();
|
||||||
|
return arena_index != TLS_OUT_OF_INDEXES;
|
||||||
|
}
|
||||||
|
void *__RPC_USER MIDL_user_allocate(size_t size) {
|
||||||
|
Arena *arena = TlsGetValue(arena_index);
|
||||||
|
if (!arena || size > 65536 || arena->total > 65536 - size) return NULL;
|
||||||
|
Allocation *p = calloc(1, sizeof(*p) + size);
|
||||||
|
if (!p) return NULL;
|
||||||
|
p->size = size; p->next = arena->head; arena->head = p; arena->total += size;
|
||||||
|
return p + 1;
|
||||||
|
}
|
||||||
|
void __RPC_USER MIDL_user_free(void *memory) {
|
||||||
|
Arena *arena = TlsGetValue(arena_index);
|
||||||
|
if (!memory || !arena) return;
|
||||||
|
Allocation **link = &arena->head;
|
||||||
|
while (*link && (*link + 1) != memory) link = &(*link)->next;
|
||||||
|
if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); }
|
||||||
|
}
|
||||||
|
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");
|
||||||
|
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
|
||||||
|
RMM_W32TIME_STATUS *status = NULL;
|
||||||
|
unsigned long result = 0;
|
||||||
|
Arena arena = {0};
|
||||||
|
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
|
||||||
|
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
|
||||||
|
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
|
||||||
|
if (!result) {
|
||||||
|
RpcTryExcept {
|
||||||
|
result = RmmW32TimeQueryStatus(binding, &status);
|
||||||
|
if (!result) {
|
||||||
|
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries)
|
||||||
|
result = RPC_X_BAD_STUB_DATA;
|
||||||
|
else {
|
||||||
|
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
|
||||||
|
out->state = status->ulLcState; out->flags = status->ulTSFlags;
|
||||||
|
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
|
||||||
|
out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync;
|
||||||
|
out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion;
|
||||||
|
out->phase = status->toSysPhaseOffset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
||||||
|
result = RpcExceptionCode();
|
||||||
|
} RpcEndExcept
|
||||||
|
release_allocations(&arena);
|
||||||
|
TlsSetValue(arena_index, NULL);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
uint32_t rmm_clock_query(RmmClockStatus *out) {
|
||||||
|
RPC_WSTR text = NULL;
|
||||||
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
|
RPC_SECURITY_QOS qos = {0};
|
||||||
|
unsigned long result;
|
||||||
|
memset(out, 0, sizeof(*out));
|
||||||
|
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
|
||||||
|
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
|
||||||
|
if (result) return result;
|
||||||
|
result = RpcBindingFromStringBindingW(text, &binding);
|
||||||
|
RpcStringFreeW(&text);
|
||||||
|
if (result) return result;
|
||||||
|
qos.Version = RPC_C_SECURITY_QOS_VERSION;
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||||
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
|
||||||
|
if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||||
|
if (!result) result = invoke_status(binding, out);
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
|
||||||
|
* The expected SID is fixed locally, never adopted from endpoint metadata.
|
||||||
|
*/
|
||||||
|
uint32_t rmm_clock_alpc_query(RmmClockStatus *out) {
|
||||||
|
RPC_IF_ID id = {0};
|
||||||
|
RPC_EP_INQ_HANDLE inquiry = NULL;
|
||||||
|
RPC_STATUS result;
|
||||||
|
memset(out, 0, sizeof(*out));
|
||||||
|
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &id.Uuid);
|
||||||
|
if (result) return result;
|
||||||
|
id.VersMajor = 4; id.VersMinor = 1;
|
||||||
|
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &id, RPC_C_VERS_EXACT, NULL, &inquiry);
|
||||||
|
if (result) return result;
|
||||||
|
for (unsigned i=0; i<16; ++i) {
|
||||||
|
RPC_IF_ID actual = {0};
|
||||||
|
RPC_BINDING_HANDLE binding = NULL;
|
||||||
|
UUID object = {0};
|
||||||
|
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
|
||||||
|
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
|
||||||
|
if (annotation) RpcStringFreeW(&annotation);
|
||||||
|
if (result) break;
|
||||||
|
result = RpcBindingToStringBindingW(binding, &text);
|
||||||
|
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
|
||||||
|
int local = !result && !wcscmp((wchar_t *)protocol, L"ncalrpc");
|
||||||
|
if (protocol) RpcStringFreeW(&protocol);
|
||||||
|
if (text) RpcStringFreeW(&text);
|
||||||
|
if (result) {RpcBindingFree(&binding);break;}
|
||||||
|
if (local) {
|
||||||
|
_Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE];
|
||||||
|
DWORD sid_size = sizeof(expected_sid);
|
||||||
|
RPC_SECURITY_QOS_V3_W qos = {0};
|
||||||
|
if (!CreateWellKnownSid(WinLocalServiceSid, NULL, expected_sid, &sid_size)) result = GetLastError();
|
||||||
|
if (!result) {
|
||||||
|
qos.Version = RPC_C_SECURITY_QOS_VERSION_3;
|
||||||
|
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
|
||||||
|
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||||
|
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||||
|
qos.Sid = expected_sid;
|
||||||
|
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||||
|
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
|
||||||
|
if (!result) result = invoke_status(binding, out);
|
||||||
|
}
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
break; /* no retry, alternate identity, endpoint or weaker transport */
|
||||||
|
}
|
||||||
|
RpcBindingFree(&binding);
|
||||||
|
result = EPT_S_NOT_REGISTERED;
|
||||||
|
}
|
||||||
|
RpcMgmtEpEltInqDone(&inquiry);
|
||||||
|
return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/* Narrow read-only MS-W32T client, interface v4.1, Opnum6.
|
||||||
|
* Wire layout derived from Microsoft Open Specifications MS-W32T 2.2.5, 3.1.5.7.
|
||||||
|
* https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a
|
||||||
|
* Slots 0..5 preserve the ordinal only. No code calls or exposes these slots;
|
||||||
|
* they are deliberately NOT definitions of the real mutating RPC operations.
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
unsigned long ulSize;
|
||||||
|
[string, unique] wchar_t *wszName;
|
||||||
|
[string, unique] wchar_t *wszValue;
|
||||||
|
[string, unique] wchar_t *wszHelp;
|
||||||
|
} RMM_W32TIME_ENTRY;
|
||||||
|
typedef struct {
|
||||||
|
unsigned long ulSize;
|
||||||
|
unsigned long eLeapIndicator;
|
||||||
|
unsigned long nStratum;
|
||||||
|
long nPollInterval;
|
||||||
|
unsigned long refidSource;
|
||||||
|
unsigned hyper qwLastSyncTicks;
|
||||||
|
hyper toRootDelay;
|
||||||
|
unsigned hyper tpRootDispersion;
|
||||||
|
long nClockPrecision;
|
||||||
|
[string, unique] wchar_t *wszSource;
|
||||||
|
hyper toSysPhaseOffset;
|
||||||
|
unsigned long ulLcState;
|
||||||
|
unsigned long ulTSFlags;
|
||||||
|
unsigned long ulClockRate;
|
||||||
|
unsigned long ulNetlogonServiceBits;
|
||||||
|
unsigned long eLastSyncResult;
|
||||||
|
unsigned hyper tpTimeLastGoodSync;
|
||||||
|
unsigned long cEntries;
|
||||||
|
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
|
||||||
|
} RMM_W32TIME_STATUS;
|
||||||
|
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
|
||||||
|
interface RmmW32Time {
|
||||||
|
unsigned long RmmUnusedSlot0([in] handle_t binding);
|
||||||
|
unsigned long RmmUnusedSlot1([in] handle_t binding);
|
||||||
|
unsigned long RmmUnusedSlot2([in] handle_t binding);
|
||||||
|
unsigned long RmmUnusedSlot3([in] handle_t binding);
|
||||||
|
unsigned long RmmUnusedSlot4([in] handle_t binding);
|
||||||
|
unsigned long RmmUnusedSlot5([in] handle_t binding);
|
||||||
|
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out, ref] RMM_W32TIME_STATUS **status);
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
//! Windows platform effects only. Acceptance, signatures, sync and durable
|
||||||
|
//! consumption are supplied by the shared core and the runtime, never bypassed.
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use rmm_agent_core::auth::Outcome;
|
||||||
|
use rmm_domain::jobs::{Action, JobPayload, hash};
|
||||||
|
use std::{
|
||||||
|
ffi::OsString,
|
||||||
|
fs::{File, OpenOptions},
|
||||||
|
io::Write,
|
||||||
|
os::windows::fs::OpenOptionsExt,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::atomic::AtomicBool,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Storage::FileSystem::{
|
||||||
|
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
|
||||||
|
},
|
||||||
|
System::SystemInformation::GetSystemDirectoryW,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn powershell() -> Result<PathBuf> {
|
||||||
|
let mut buffer = [0u16; 32768];
|
||||||
|
let length = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize;
|
||||||
|
ensure!(length > 0 && length < buffer.len(), "SYSTEM_DIRECTORY");
|
||||||
|
let executable = PathBuf::from(String::from_utf16(&buffer[..length])?)
|
||||||
|
.join("WindowsPowerShell/v1.0/powershell.exe");
|
||||||
|
ensure!(executable.is_file(), "POWERSHELL_51_NOT_AVAILABLE");
|
||||||
|
Ok(executable)
|
||||||
|
}
|
||||||
|
pub fn supported(job: &JobPayload) -> bool {
|
||||||
|
crate::native::require_local_service().is_ok()
|
||||||
|
&& job.execution_identity == "agent_service"
|
||||||
|
&& job.action.validate()
|
||||||
|
&& match &job.action {
|
||||||
|
Action::RunScript { interpreter, .. } => {
|
||||||
|
interpreter == "powershell" && powershell().is_ok()
|
||||||
|
}
|
||||||
|
Action::RefreshInventory { scope } => scope == "windows.base",
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Script {
|
||||||
|
executable: PathBuf,
|
||||||
|
path: PathBuf,
|
||||||
|
/// Denies write/delete replacement while PowerShell opens the approved file.
|
||||||
|
_file: File,
|
||||||
|
cwd: PathBuf,
|
||||||
|
arguments: Vec<OsString>,
|
||||||
|
}
|
||||||
|
impl Script {
|
||||||
|
/// Preparation creates only a protected copy of approved bytes, no child.
|
||||||
|
/// Only the runtime may call run after committing one-time consumption.
|
||||||
|
pub fn prepare(job: &JobPayload, directory: &Path, grant: uuid::Uuid) -> Result<Self> {
|
||||||
|
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
|
||||||
|
let Action::RunScript {
|
||||||
|
interpreter,
|
||||||
|
script_utf8,
|
||||||
|
arguments,
|
||||||
|
..
|
||||||
|
} = &job.action
|
||||||
|
else {
|
||||||
|
anyhow::bail!("SCRIPT_REQUIRED")
|
||||||
|
};
|
||||||
|
ensure!(
|
||||||
|
interpreter == "powershell" && !grant.is_nil(),
|
||||||
|
"WINDOWS_SCRIPT_BINDING"
|
||||||
|
);
|
||||||
|
crate::native::private_path(directory, true)?;
|
||||||
|
let path = directory.join(format!("{}-{}.ps1", job.attempt_id, grant));
|
||||||
|
let mut file = OpenOptions::new()
|
||||||
|
.create_new(true)
|
||||||
|
.write(true)
|
||||||
|
.read(true)
|
||||||
|
.share_mode(FILE_SHARE_READ)
|
||||||
|
.open(&path)?;
|
||||||
|
file.write_all(script_utf8.as_bytes())?;
|
||||||
|
file.sync_all()?;
|
||||||
|
drop(file);
|
||||||
|
// Retain a READ handle, not the writer: Windows sharing rules would
|
||||||
|
// otherwise prevent PowerShell's own read-only file open.
|
||||||
|
let file = OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.share_mode(FILE_SHARE_READ)
|
||||||
|
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||||
|
.open(&path)?;
|
||||||
|
use std::os::windows::fs::MetadataExt;
|
||||||
|
ensure!(
|
||||||
|
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
|
||||||
|
"SCRIPT_REPARSE_POINT"
|
||||||
|
);
|
||||||
|
crate::native::private_path(&path, false)?;
|
||||||
|
// Never add a BOM, prolog or change line endings after the plan hash.
|
||||||
|
ensure!(
|
||||||
|
hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()),
|
||||||
|
"SCRIPT_BYTES_CHANGED"
|
||||||
|
);
|
||||||
|
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"]
|
||||||
|
.into_iter()
|
||||||
|
.map(OsString::from)
|
||||||
|
.collect();
|
||||||
|
args.push(path.clone().into_os_string());
|
||||||
|
args.extend(arguments.iter().map(OsString::from));
|
||||||
|
Ok(Self {
|
||||||
|
executable: powershell()?,
|
||||||
|
path,
|
||||||
|
_file: file,
|
||||||
|
cwd: directory.to_path_buf(),
|
||||||
|
arguments: args,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||||
|
ensure!(supported(job), "LOCAL_SERVICE_EXECUTOR_NOT_READY");
|
||||||
|
crate::native::private_path(&self.path, false)?;
|
||||||
|
let Action::RunScript {
|
||||||
|
script_utf8,
|
||||||
|
expected_stdout,
|
||||||
|
..
|
||||||
|
} = &job.action
|
||||||
|
else {
|
||||||
|
anyhow::bail!("SCRIPT_REQUIRED")
|
||||||
|
};
|
||||||
|
ensure!(
|
||||||
|
std::fs::read(&self.path)? == script_utf8.as_bytes(),
|
||||||
|
"SCRIPT_BYTES_CHANGED"
|
||||||
|
);
|
||||||
|
let output = crate::process::run(
|
||||||
|
&self.executable,
|
||||||
|
&self.arguments,
|
||||||
|
&self.cwd,
|
||||||
|
job.max_runtime_seconds,
|
||||||
|
job.max_output_bytes as usize,
|
||||||
|
cancel,
|
||||||
|
)?;
|
||||||
|
let expected = expected_stdout
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|expected| output.stdout == expected.as_bytes());
|
||||||
|
let success =
|
||||||
|
!output.interrupted && output.exit_code == Some(0) && expected && !output.truncated;
|
||||||
|
let state = if output.interrupted {
|
||||||
|
"unknown"
|
||||||
|
} else if success {
|
||||||
|
"succeeded"
|
||||||
|
} else {
|
||||||
|
"failed"
|
||||||
|
};
|
||||||
|
let code = if output.interrupted {
|
||||||
|
if output.cancelled {
|
||||||
|
"CANCELLED_EFFECT_UNKNOWN"
|
||||||
|
} else {
|
||||||
|
"TIMEOUT_EFFECT_UNKNOWN"
|
||||||
|
}
|
||||||
|
} else if output.truncated {
|
||||||
|
"OUTPUT_LIMIT_REACHED"
|
||||||
|
} else if output.exit_code != Some(0) {
|
||||||
|
"POWERSHELL_PROCESS_FAILED"
|
||||||
|
} else if !expected {
|
||||||
|
"STDOUT_POSTCONDITION_FAILED"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
Ok(Outcome {
|
||||||
|
state: state.into(),
|
||||||
|
stdout: output.stdout,
|
||||||
|
stderr: output.stderr,
|
||||||
|
exit_code: output.exit_code,
|
||||||
|
output_truncated: output.truncated,
|
||||||
|
reboot_required: false,
|
||||||
|
error_code: code.into(),
|
||||||
|
evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
|
||||||
|
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
|
||||||
|
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
|
||||||
|
"execution_policy":"inherited","process_tree_bounded":true,
|
||||||
|
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn inventory(job: &JobPayload) -> Result<Outcome> {
|
||||||
|
ensure!(
|
||||||
|
supported(job)
|
||||||
|
&& matches!(&job.action, Action::RefreshInventory {scope} if scope=="windows.base"),
|
||||||
|
"WINDOWS_INVENTORY_BINDING"
|
||||||
|
);
|
||||||
|
let data = crate::native::snapshot()?;
|
||||||
|
let stdout = serde_json::to_vec(&data)?;
|
||||||
|
ensure!(
|
||||||
|
stdout.len() <= job.max_output_bytes as usize,
|
||||||
|
"INVENTORY_OUTPUT_LIMIT"
|
||||||
|
);
|
||||||
|
Ok(Outcome {
|
||||||
|
state: "succeeded".into(),
|
||||||
|
stdout,
|
||||||
|
stderr: vec![],
|
||||||
|
exit_code: None,
|
||||||
|
output_truncated: false,
|
||||||
|
reboot_required: false,
|
||||||
|
error_code: String::new(),
|
||||||
|
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"windows.base",
|
||||||
|
"observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//! Separate SCM binary. The network agent always remains LocalService.
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
rmm_agent_windows::helper_system::dispatch()
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn main() {
|
||||||
|
eprintln!("Windows SCM helper requires a Windows target");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
//! 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.
|
||||||
|
//! 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 SID-bound ALPC, readiness and fail-closed qualification.
|
||||||
|
pub const ADAPTER_QUALIFIED: bool = false;
|
||||||
|
const SECOND: u64 = 10_000_000;
|
||||||
|
const MAX_AGE: u64 = 3600 * SECOND;
|
||||||
|
const MAX_ERROR: u64 = 2 * SECOND;
|
||||||
|
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct Status {
|
||||||
|
pub leap: u32,
|
||||||
|
pub stratum: u32,
|
||||||
|
pub state: u32,
|
||||||
|
pub flags: u32,
|
||||||
|
pub last_result: u32,
|
||||||
|
pub size: u32,
|
||||||
|
pub last_sync: u64,
|
||||||
|
pub sync_age: u64,
|
||||||
|
pub root_delay: i64,
|
||||||
|
pub root_dispersion: u64,
|
||||||
|
pub phase: i64,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||||
|
pub struct Sample {
|
||||||
|
pub wall: u64,
|
||||||
|
pub interrupt: u64,
|
||||||
|
pub unbiased: u64,
|
||||||
|
}
|
||||||
|
/// Diagnostic endpoint counts only; never a trusted clock or server identity.
|
||||||
|
#[derive(Debug, Default, Serialize)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct EndpointReport {
|
||||||
|
pub result: u32,
|
||||||
|
pub scanned: u32,
|
||||||
|
pub named_pipe: u32,
|
||||||
|
pub alpc: u32,
|
||||||
|
pub other: u32,
|
||||||
|
pub truncated: u32,
|
||||||
|
}
|
||||||
|
pub fn endpoint_report() -> EndpointReport {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
#[link(name = "rmm_clock_rpc", kind = "static")]
|
||||||
|
#[link(name = "rpcrt4")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn rmm_clock_endpoints(out: *mut EndpointReport) -> u32;
|
||||||
|
}
|
||||||
|
let mut report = EndpointReport::default();
|
||||||
|
// SAFETY: fixed 6*u32 C ABI; bounded exact-interface local enumeration.
|
||||||
|
unsafe {
|
||||||
|
rmm_clock_endpoints(&mut report);
|
||||||
|
}
|
||||||
|
report
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
EndpointReport {
|
||||||
|
result: 50,
|
||||||
|
..EndpointReport::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ClockReport {
|
||||||
|
pub trusted: bool,
|
||||||
|
pub adapter_qualified: bool,
|
||||||
|
pub reason: String,
|
||||||
|
pub rpc_code: u32,
|
||||||
|
pub transport: &'static str,
|
||||||
|
pub status: Option<Status>,
|
||||||
|
pub query_ticks: u64,
|
||||||
|
pub error_bound_ticks: Option<u64>,
|
||||||
|
pub sample: Sample,
|
||||||
|
}
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Continuity {
|
||||||
|
previous: Option<Sample>,
|
||||||
|
require_sync_after: Option<u64>,
|
||||||
|
}
|
||||||
|
impl Continuity {
|
||||||
|
fn observe(&mut self, sample: Sample) -> Result<()> {
|
||||||
|
if let Some(p) = self.previous {
|
||||||
|
let wall = sample.wall.checked_sub(p.wall);
|
||||||
|
let interrupt = sample.interrupt.checked_sub(p.interrupt);
|
||||||
|
let unbiased = sample.unbiased.checked_sub(p.unbiased);
|
||||||
|
let continuous = match (wall, interrupt, unbiased) {
|
||||||
|
(Some(w), Some(i), Some(u)) => w.abs_diff(i) <= SECOND && i.abs_diff(u) <= SECOND,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !continuous {
|
||||||
|
// A backward step can make the prior wall timestamp too strict;
|
||||||
|
// require successful sync after the NEW observed wall value.
|
||||||
|
self.require_sync_after = Some(sample.wall);
|
||||||
|
self.previous = Some(sample);
|
||||||
|
return Err(anyhow!("CLOCK_DISCONTINUITY"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.previous = Some(sample);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn validate(&mut self, status: &Status, sample: Sample, query_ticks: u64) -> Result<u64> {
|
||||||
|
self.observe(sample)?;
|
||||||
|
let bound = evaluate(status, sample.wall, query_ticks)?;
|
||||||
|
if let Some(after) = self.require_sync_after {
|
||||||
|
ensure!(
|
||||||
|
status.last_sync > after,
|
||||||
|
"CLOCK_AWAITING_POST_DISCONTINUITY_SYNC"
|
||||||
|
);
|
||||||
|
self.require_sync_after = None;
|
||||||
|
}
|
||||||
|
Ok(bound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||||
|
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
|
||||||
|
ensure!(
|
||||||
|
status.state == 2
|
||||||
|
&& status.last_result == 0
|
||||||
|
&& status.leap <= 2
|
||||||
|
&& (1..=15).contains(&status.stratum),
|
||||||
|
"CLOCK_UNSYNCHRONIZED"
|
||||||
|
);
|
||||||
|
// MS-W32T hardware flag is reserved/unused, all bits above2 are reserved.
|
||||||
|
// Authenticated MS-SNTP is reported, not demanded above Linux NTP policy.
|
||||||
|
ensure!(status.flags & !6 == 0, "CLOCK_UNKNOWN_FLAGS");
|
||||||
|
ensure!(
|
||||||
|
status.last_sync > FILETIME_UNIX && status.last_sync <= wall,
|
||||||
|
"CLOCK_SYNC_TIMESTAMP"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
wall - status.last_sync <= MAX_AGE && status.sync_age <= MAX_AGE,
|
||||||
|
"CLOCK_STALE_SYNC"
|
||||||
|
);
|
||||||
|
// These independent representations should agree within sampling latency.
|
||||||
|
ensure!(
|
||||||
|
(wall - status.last_sync).abs_diff(status.sync_age) <= SECOND.saturating_add(query_ticks),
|
||||||
|
"CLOCK_INCONSISTENT_SYNC_AGE"
|
||||||
|
);
|
||||||
|
ensure!(status.root_delay >= 0, "CLOCK_NEGATIVE_DELAY");
|
||||||
|
let bound = status
|
||||||
|
.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(query_ticks))
|
||||||
|
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
|
||||||
|
ensure!(
|
||||||
|
query_ticks <= SECOND && bound <= MAX_ERROR,
|
||||||
|
"CLOCK_UNCERTAINTY"
|
||||||
|
);
|
||||||
|
Ok(bound)
|
||||||
|
}
|
||||||
|
pub struct NativeClock {
|
||||||
|
state: Mutex<Continuity>,
|
||||||
|
diagnostic: bool,
|
||||||
|
}
|
||||||
|
impl Default for NativeClock {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl NativeClock {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
state: Mutex::new(Continuity::default()),
|
||||||
|
diagnostic: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn report(&self) -> ClockReport {
|
||||||
|
let before = sample();
|
||||||
|
let (rpc_code, raw) = query(self.diagnostic);
|
||||||
|
let after = sample();
|
||||||
|
let ticks = after
|
||||||
|
.interrupt
|
||||||
|
.checked_sub(before.interrupt)
|
||||||
|
.unwrap_or(u64::MAX);
|
||||||
|
let mut report = ClockReport {
|
||||||
|
trusted: false,
|
||||||
|
adapter_qualified: ADAPTER_QUALIFIED,
|
||||||
|
reason: "CLOCK_UNTRUSTED".into(),
|
||||||
|
rpc_code,
|
||||||
|
transport: if self.diagnostic {
|
||||||
|
"ncacn_np:W32TIME_ALT:diagnostic_only"
|
||||||
|
} else {
|
||||||
|
"ncalrpc:SID19:mutual_auth"
|
||||||
|
},
|
||||||
|
status: None,
|
||||||
|
query_ticks: ticks,
|
||||||
|
error_bound_ticks: None,
|
||||||
|
sample: after,
|
||||||
|
};
|
||||||
|
let Ok(mut state) = self.state.lock() else {
|
||||||
|
report.reason = "CLOCK_STATE_POISONED".into();
|
||||||
|
return report;
|
||||||
|
};
|
||||||
|
// Observe both sides even when RPC fails, so errors cannot hide resume.
|
||||||
|
if let Err(e) = state.observe(before) {
|
||||||
|
report.reason = e.to_string();
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
if rpc_code != 0 {
|
||||||
|
let _ = state.observe(after);
|
||||||
|
report.reason = match rpc_code {
|
||||||
|
5 | 1326 | 1747 => "CLOCK_PERMISSION_DENIED",
|
||||||
|
50 | 1717 | 1722 | 1753 => "CLOCK_UNSUPPORTED",
|
||||||
|
1818 => "CLOCK_RPC_TIMEOUT",
|
||||||
|
_ => "CLOCK_RPC_ERROR",
|
||||||
|
}
|
||||||
|
.into();
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
report.status = Some(raw);
|
||||||
|
match state.validate(&raw, after, ticks) {
|
||||||
|
Ok(bound) => {
|
||||||
|
report.trusted = !self.diagnostic;
|
||||||
|
report.reason = if self.diagnostic {
|
||||||
|
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
|
||||||
|
} else {
|
||||||
|
"CLOCK_TRUSTED"
|
||||||
|
}
|
||||||
|
.into();
|
||||||
|
report.error_bound_ticks = Some(bound);
|
||||||
|
}
|
||||||
|
Err(e) => report.reason = e.to_string(),
|
||||||
|
}
|
||||||
|
report
|
||||||
|
}
|
||||||
|
pub fn now(&self) -> Result<DateTime<Utc>> {
|
||||||
|
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
|
||||||
|
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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Named-pipe diagnostics can never open the production clock gate.
|
||||||
|
pub fn named_pipe_diagnostic() -> ClockReport {
|
||||||
|
NativeClock {
|
||||||
|
state: Mutex::new(Continuity::default()),
|
||||||
|
diagnostic: true,
|
||||||
|
}
|
||||||
|
.report()
|
||||||
|
}
|
||||||
|
impl rmm_agent_core::reconcile::SyncClock for NativeClock {
|
||||||
|
fn now(&self) -> Result<DateTime<Utc>> {
|
||||||
|
NativeClock::now(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn sample() -> Sample {
|
||||||
|
#[link(name = "kernel32")]
|
||||||
|
unsafe extern "system" {
|
||||||
|
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
|
||||||
|
fn QueryInterruptTimePrecise(value: *mut u64);
|
||||||
|
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
|
||||||
|
}
|
||||||
|
let mut v = Sample::default();
|
||||||
|
// SAFETY: three fixed kernel getters writing valid aligned u64 outputs.
|
||||||
|
unsafe {
|
||||||
|
GetSystemTimePreciseAsFileTime(&mut v.wall);
|
||||||
|
QueryInterruptTimePrecise(&mut v.interrupt);
|
||||||
|
QueryUnbiasedInterruptTimePrecise(&mut v.unbiased);
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn raw_query(diagnostic: bool) -> (u32, Status) {
|
||||||
|
#[link(name = "rmm_clock_rpc", kind = "static")]
|
||||||
|
#[link(name = "rpcrt4")]
|
||||||
|
#[link(name = "advapi32")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn rmm_clock_query(status: *mut Status) -> u32;
|
||||||
|
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
|
||||||
|
}
|
||||||
|
let mut status = Status::default();
|
||||||
|
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
|
||||||
|
let code = unsafe {
|
||||||
|
if diagnostic {
|
||||||
|
rmm_clock_query(&mut status)
|
||||||
|
} else {
|
||||||
|
rmm_clock_alpc_query(&mut status)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(code, status)
|
||||||
|
}
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
type RpcReply = std::sync::mpsc::SyncSender<(u32, Status)>;
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
type RpcRequest = (bool, RpcReply);
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
struct RpcWorker {
|
||||||
|
sender: Option<std::sync::mpsc::SyncSender<RpcRequest>>,
|
||||||
|
poisoned: bool,
|
||||||
|
}
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
impl RpcWorker {
|
||||||
|
fn new(run: fn(bool) -> (u32, Status)) -> Self {
|
||||||
|
let (sender, receiver) = std::sync::mpsc::sync_channel::<RpcRequest>(1);
|
||||||
|
let created = std::thread::Builder::new()
|
||||||
|
.name("rmm-clock-rpc".into())
|
||||||
|
.spawn(move || {
|
||||||
|
while let Ok((mode, reply)) = receiver.recv() {
|
||||||
|
let _ = reply.send(run(mode));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.is_ok();
|
||||||
|
Self {
|
||||||
|
sender: created.then_some(sender),
|
||||||
|
poisoned: !created,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn call(&mut self, mode: bool, timeout: std::time::Duration) -> (u32, Status) {
|
||||||
|
if self.poisoned {
|
||||||
|
return (1818, Status::default());
|
||||||
|
}
|
||||||
|
let (reply, receiver) = std::sync::mpsc::sync_channel(1);
|
||||||
|
let sent = self
|
||||||
|
.sender
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|sender| sender.try_send((mode, reply)).is_ok());
|
||||||
|
if sent && let Ok(value) = receiver.recv_timeout(timeout) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
// No replacement worker or retry, including across NativeClock rebuilds.
|
||||||
|
// At most one stuck read-only call; the service/telemetry thread returns.
|
||||||
|
self.poisoned = true;
|
||||||
|
self.sender = None;
|
||||||
|
(1818, Status::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn query(diagnostic: bool) -> (u32, Status) {
|
||||||
|
static WORKER: std::sync::OnceLock<Mutex<RpcWorker>> = std::sync::OnceLock::new();
|
||||||
|
let worker = WORKER.get_or_init(|| Mutex::new(RpcWorker::new(raw_query)));
|
||||||
|
match worker.try_lock() {
|
||||||
|
Ok(mut worker) => worker.call(diagnostic, std::time::Duration::from_secs(1)),
|
||||||
|
Err(_) => (170, Status::default()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn sample() -> Sample {
|
||||||
|
Sample::default()
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn query(_diagnostic: bool) -> (u32, Status) {
|
||||||
|
(50, Status::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
fn good() -> (Status, Sample) {
|
||||||
|
let wall = FILETIME_UNIX + 1_800_000_000 * SECOND;
|
||||||
|
(
|
||||||
|
Status {
|
||||||
|
size: 120,
|
||||||
|
leap: 0,
|
||||||
|
stratum: 3,
|
||||||
|
state: 2,
|
||||||
|
last_sync: wall - 10 * SECOND,
|
||||||
|
sync_age: 10 * SECOND,
|
||||||
|
root_delay: (SECOND / 10) as i64,
|
||||||
|
root_dispersion: SECOND / 20,
|
||||||
|
phase: 1000,
|
||||||
|
..Status::default()
|
||||||
|
},
|
||||||
|
Sample {
|
||||||
|
wall,
|
||||||
|
interrupt: 100 * SECOND,
|
||||||
|
unbiased: 100 * SECOND,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
||||||
|
assert_eq!(
|
||||||
|
NativeClock::new().now().unwrap_err().to_string(),
|
||||||
|
"CLOCK_ADAPTER_UNQUALIFIED"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn timeout_worker_stays_closed_without_a_second_call() {
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
static CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
fn delayed(_: bool) -> (u32, Status) {
|
||||||
|
CALLS.fetch_add(1, Ordering::SeqCst);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||||
|
(0, Status::default())
|
||||||
|
}
|
||||||
|
let mut worker = RpcWorker::new(delayed);
|
||||||
|
assert_eq!(
|
||||||
|
worker.call(false, std::time::Duration::from_millis(1)).0,
|
||||||
|
1818
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
worker.call(false, std::time::Duration::from_millis(1)).0,
|
||||||
|
1818
|
||||||
|
);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(40));
|
||||||
|
assert_eq!(CALLS.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn gate_requires_all_status_and_uncertainty_evidence() {
|
||||||
|
let (s, v) = good();
|
||||||
|
assert!(evaluate(&s, v.wall, 100).is_ok());
|
||||||
|
for bad in [
|
||||||
|
Status { state: 1, ..s },
|
||||||
|
Status { leap: 3, ..s },
|
||||||
|
Status {
|
||||||
|
last_result: 2,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
Status { stratum: 16, ..s },
|
||||||
|
Status {
|
||||||
|
sync_age: MAX_AGE + 1,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
Status {
|
||||||
|
root_dispersion: MAX_ERROR,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
Status {
|
||||||
|
root_delay: -1,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
Status { flags: 8, ..s },
|
||||||
|
Status {
|
||||||
|
phase: i64::MIN,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
] {
|
||||||
|
assert!(evaluate(&bad, v.wall, 100).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn suspend_closes_until_actual_post_resume_sync() {
|
||||||
|
let (s, v) = good();
|
||||||
|
let mut c = Continuity::default();
|
||||||
|
assert!(c.validate(&s, v, 1).is_ok());
|
||||||
|
let r = Sample {
|
||||||
|
wall: v.wall + 20 * SECOND,
|
||||||
|
interrupt: v.interrupt + 20 * SECOND,
|
||||||
|
unbiased: v.unbiased + SECOND,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
c.validate(&s, r, 1)
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string()
|
||||||
|
.contains("DISCONTINUITY")
|
||||||
|
);
|
||||||
|
let stale = Status {
|
||||||
|
sync_age: 30 * SECOND,
|
||||||
|
..s
|
||||||
|
};
|
||||||
|
assert!(c.validate(&stale, r, 1).is_err());
|
||||||
|
let later = Sample {
|
||||||
|
wall: r.wall + SECOND,
|
||||||
|
interrupt: r.interrupt + SECOND,
|
||||||
|
unbiased: r.unbiased + SECOND,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
c.validate(
|
||||||
|
&Status {
|
||||||
|
last_sync: later.wall,
|
||||||
|
sync_age: 0,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
later,
|
||||||
|
1
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn wall_step_and_overflow_fail_closed() {
|
||||||
|
let (s, v) = good();
|
||||||
|
let mut c = Continuity::default();
|
||||||
|
assert!(c.validate(&s, v, 1).is_ok());
|
||||||
|
assert!(
|
||||||
|
c.observe(Sample {
|
||||||
|
wall: v.wall - SECOND,
|
||||||
|
..v
|
||||||
|
})
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
evaluate(
|
||||||
|
&Status {
|
||||||
|
root_dispersion: u64::MAX,
|
||||||
|
..s
|
||||||
|
},
|
||||||
|
v.wall,
|
||||||
|
100
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(evaluate(&s, v.wall, SECOND + 1).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,219 @@
|
|||||||
|
//! Passive native machine inventory. Never queries Win32_Product or executes
|
||||||
|
//! uninstall commands; registry entries are evidence, not verified MSI state.
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
mem::{size_of, zeroed},
|
||||||
|
ptr,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS},
|
||||||
|
System::{Registry::*, SystemInformation::*},
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Registry(HKEY);
|
||||||
|
impl Drop for Registry {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
RegCloseKey(self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn open(parent: HKEY, name: &str, flags: u32) -> Result<Registry> {
|
||||||
|
let mut key = ptr::null_mut();
|
||||||
|
let name = crate::native::wide(name);
|
||||||
|
ensure!(
|
||||||
|
unsafe { RegOpenKeyExW(parent, name.as_ptr(), 0, KEY_READ | flags, &mut key) }
|
||||||
|
== ERROR_SUCCESS,
|
||||||
|
"REGISTRY_INVENTORY_ACCESS"
|
||||||
|
);
|
||||||
|
Ok(Registry(key))
|
||||||
|
}
|
||||||
|
fn text(key: HKEY, name: &str) -> Result<Option<String>> {
|
||||||
|
let name = crate::native::wide(name);
|
||||||
|
let mut data = [0u16; 512];
|
||||||
|
let mut bytes = size_of::<[u16; 512]>() as u32;
|
||||||
|
let result = unsafe {
|
||||||
|
RegGetValueW(
|
||||||
|
key,
|
||||||
|
ptr::null(),
|
||||||
|
name.as_ptr(),
|
||||||
|
RRF_RT_REG_SZ,
|
||||||
|
ptr::null_mut(),
|
||||||
|
data.as_mut_ptr().cast(),
|
||||||
|
&mut bytes,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if result == ERROR_FILE_NOT_FOUND {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
result == ERROR_SUCCESS
|
||||||
|
&& bytes >= 2
|
||||||
|
&& bytes as usize <= size_of::<[u16; 512]>()
|
||||||
|
&& bytes.is_multiple_of(2),
|
||||||
|
"REGISTRY_INVENTORY_STRING"
|
||||||
|
);
|
||||||
|
let count = bytes as usize / 2;
|
||||||
|
ensure!(
|
||||||
|
data[count - 1] == 0 && !data[..count - 1].contains(&0),
|
||||||
|
"REGISTRY_STRING_TERMINATION"
|
||||||
|
);
|
||||||
|
Ok(Some(String::from_utf16(&data[..count - 1])?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hardware() -> Result<Value> {
|
||||||
|
let mut system: SYSTEM_INFO = unsafe { zeroed() };
|
||||||
|
unsafe {
|
||||||
|
GetNativeSystemInfo(&mut system);
|
||||||
|
}
|
||||||
|
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
|
||||||
|
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
|
||||||
|
ensure!(
|
||||||
|
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
|
||||||
|
&& system.dwNumberOfProcessors > 0
|
||||||
|
&& memory.ullTotalPhys > 0
|
||||||
|
&& memory.ullAvailPhys <= memory.ullTotalPhys
|
||||||
|
&& memory.dwMemoryLoad <= 100,
|
||||||
|
"NATIVE_HARDWARE_QUERY"
|
||||||
|
);
|
||||||
|
Ok(
|
||||||
|
json!({"logical_processors_visible":system.dwNumberOfProcessors,
|
||||||
|
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
|
||||||
|
"memory_load_percent":memory.dwMemoryLoad}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn software() -> Result<Value> {
|
||||||
|
let began = Instant::now();
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let mut errors = 0u32;
|
||||||
|
let mut scanned = 0u32;
|
||||||
|
let mut truncated = false;
|
||||||
|
let mut views = Vec::new();
|
||||||
|
for (view, label) in [
|
||||||
|
(KEY_WOW64_64KEY, "machine_registry_64"),
|
||||||
|
(KEY_WOW64_32KEY, "machine_registry_32"),
|
||||||
|
] {
|
||||||
|
views.push(label);
|
||||||
|
let key = match open(
|
||||||
|
HKEY_LOCAL_MACHINE,
|
||||||
|
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
|
||||||
|
view,
|
||||||
|
) {
|
||||||
|
Ok(key) => key,
|
||||||
|
Err(_) => {
|
||||||
|
errors += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for index in 0..2048 {
|
||||||
|
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
|
||||||
|
truncated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let mut name = [0u16; 256];
|
||||||
|
let mut length = name.len() as u32;
|
||||||
|
let result = unsafe {
|
||||||
|
RegEnumKeyExW(
|
||||||
|
key.0,
|
||||||
|
index,
|
||||||
|
name.as_mut_ptr(),
|
||||||
|
&mut length,
|
||||||
|
ptr::null(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if result == ERROR_NO_MORE_ITEMS {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
scanned += 1;
|
||||||
|
if result != ERROR_SUCCESS || length as usize >= name.len() {
|
||||||
|
errors += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let entry = (|| -> Result<Option<Value>> {
|
||||||
|
let name = String::from_utf16(&name[..length as usize])?;
|
||||||
|
let child = open(key.0, &name, view)?;
|
||||||
|
let Some(display) = text(child.0, "DisplayName")?.filter(|v| !v.is_empty()) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
// No arbitrary path, username, uninstall string or installer
|
||||||
|
// execution is inventoried. Missing version stays null.
|
||||||
|
Ok(Some(
|
||||||
|
json!({"display_name":display,"version":text(child.0,"DisplayVersion")?,
|
||||||
|
"publisher":text(child.0,"Publisher")?,"source":label,
|
||||||
|
"installation_context":"machine","installed_state":"registry_entry_only"}),
|
||||||
|
))
|
||||||
|
})();
|
||||||
|
match entry {
|
||||||
|
Ok(Some(entry)) => {
|
||||||
|
entries.push(entry);
|
||||||
|
if serde_json::to_vec(&entries)?.len() > 12288 {
|
||||||
|
entries.pop();
|
||||||
|
truncated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(_) => errors += 1,
|
||||||
|
}
|
||||||
|
if index == 2047 {
|
||||||
|
truncated = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if truncated {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
errors < 2 || !entries.is_empty(),
|
||||||
|
"SOFTWARE_REGISTRY_UNAVAILABLE"
|
||||||
|
);
|
||||||
|
Ok(
|
||||||
|
json!({"entries":entries,"scanned_keys":scanned,"read_errors":errors,"truncated":truncated,"views_queried":views,
|
||||||
|
"scope":"machine_registry_only","per_user_inventory":"unsupported",
|
||||||
|
"msi_state_verification":"not_collected","appx_inventory":"not_collected"}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each provider is isolated. Missing permissions never fabricate an empty,
|
||||||
|
/// complete software inventory or hide the last valid stored observation.
|
||||||
|
pub fn observations() -> Vec<Value> {
|
||||||
|
type Provider = fn() -> Result<Value>;
|
||||||
|
[
|
||||||
|
(
|
||||||
|
"windows.hardware",
|
||||||
|
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx",
|
||||||
|
hardware as Provider,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"windows.software",
|
||||||
|
"windows.registry:HKLM.Uninstall:64+32",
|
||||||
|
software as Provider,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(scope, source, collect)| {
|
||||||
|
let data = collect();
|
||||||
|
let observed = Utc::now();
|
||||||
|
match data {
|
||||||
|
Ok(data) => {
|
||||||
|
let truncated = data
|
||||||
|
.get("truncated")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false);
|
||||||
|
json!({"scope":scope,"source_id":source,"observed_at":observed,"quality":"valid",
|
||||||
|
"completeness":"partial","truncated":truncated,"error_code":null,"data":data})
|
||||||
|
}
|
||||||
|
Err(_) => json!({"scope":scope,"source_id":source,"observed_at":observed,
|
||||||
|
"quality":"error","completeness":"unknown","truncated":false,
|
||||||
|
"error_code":"NATIVE_PROVIDER_UNAVAILABLE","data":null}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -20,12 +20,32 @@ impl Journal {
|
|||||||
.open(directory.join("agent.lock"))?;
|
.open(directory.join("agent.lock"))?;
|
||||||
lock.try_lock_exclusive()?;
|
lock.try_lock_exclusive()?;
|
||||||
let db = Connection::open(directory.join("telemetry.sqlite"))?;
|
let db = Connection::open(directory.join("telemetry.sqlite"))?;
|
||||||
|
// Bound the existing file without resetting sequence, identity, or
|
||||||
|
// unacknowledged bytes. Unexpected page sizes fail closed.
|
||||||
|
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
|
||||||
db.execute_batch(
|
db.execute_batch(
|
||||||
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;
|
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;
|
||||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL);
|
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL);
|
||||||
INSERT OR IGNORE INTO metadata VALUES('sequence',0);
|
INSERT OR IGNORE INTO metadata VALUES('sequence',0);
|
||||||
CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);",
|
CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);",
|
||||||
)?;
|
)?;
|
||||||
|
// Add the shared durable-job schema to the same database; old inventory
|
||||||
|
// bytes and identity remain in place. Both names reference one sequence
|
||||||
|
// through atomic, monotonic triggers, including old passive clients.
|
||||||
|
db.execute_batch("BEGIN IMMEDIATE;
|
||||||
|
CREATE TABLE IF NOT EXISTS counter(id INTEGER PRIMARY KEY CHECK(id=1),seq INTEGER NOT NULL CHECK(seq>=0));
|
||||||
|
INSERT OR IGNORE INTO counter SELECT 1,value FROM metadata WHERE key='sequence';
|
||||||
|
CREATE TRIGGER IF NOT EXISTS counter_monotonic BEFORE UPDATE OF seq ON counter WHEN NEW.seq<OLD.seq BEGIN SELECT RAISE(ABORT,'SEQUENCE_ROLLBACK'); END;
|
||||||
|
CREATE TRIGGER IF NOT EXISTS metadata_monotonic BEFORE UPDATE OF value ON metadata WHEN NEW.key='sequence' AND NEW.value<OLD.value BEGIN SELECT RAISE(ABORT,'SEQUENCE_ROLLBACK'); END;
|
||||||
|
CREATE TRIGGER IF NOT EXISTS counter_to_metadata AFTER UPDATE OF seq ON counter WHEN NEW.seq!=(SELECT value FROM metadata WHERE key='sequence') BEGIN UPDATE metadata SET value=NEW.seq WHERE key='sequence'; END;
|
||||||
|
CREATE TRIGGER IF NOT EXISTS metadata_to_counter AFTER UPDATE OF value ON metadata WHEN NEW.key='sequence' AND NEW.value!=(SELECT seq FROM counter WHERE id=1) BEGIN UPDATE counter SET seq=NEW.value WHERE id=1; END;
|
||||||
|
CREATE TABLE IF NOT EXISTS job_attempts(job TEXT NOT NULL,attempt TEXT NOT NULL,offer BLOB NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL DEFAULT 0,grant_id TEXT NOT NULL DEFAULT '',cancel_requested INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(job,attempt));
|
||||||
|
CREATE TABLE IF NOT EXISTS job_events(id TEXT PRIMARY KEY,payload BLOB NOT NULL CHECK(length(payload)<=1048576));
|
||||||
|
CREATE TABLE IF NOT EXISTS safety(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
||||||
|
COMMIT;")?;
|
||||||
|
let consistent: bool = db.query_row("SELECT seq>=0 AND seq=(SELECT value FROM metadata WHERE key='sequence') FROM counter WHERE id=1", [], |r|r.get(0))?;
|
||||||
|
ensure!(consistent, "JOURNAL_SEQUENCE_DIVERGED");
|
||||||
|
rmm_agent_core::reconcile::initialize(&db)?;
|
||||||
ensure!(
|
ensure!(
|
||||||
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||||
"JOURNAL_INTEGRITY"
|
"JOURNAL_INTEGRITY"
|
||||||
@@ -34,17 +54,20 @@ impl Journal {
|
|||||||
}
|
}
|
||||||
pub fn next_sequence(&mut self) -> Result<u64> {
|
pub fn next_sequence(&mut self) -> Result<u64> {
|
||||||
let tx = self.db.transaction()?;
|
let tx = self.db.transaction()?;
|
||||||
let sequence: i64 =
|
let sequence: i64 = tx.query_row("SELECT seq FROM counter WHERE id=1", [], |r| r.get(0))?;
|
||||||
tx.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| {
|
|
||||||
r.get(0)
|
|
||||||
})?;
|
|
||||||
let next = sequence
|
let next = sequence
|
||||||
.checked_add(1)
|
.checked_add(1)
|
||||||
.ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?;
|
.ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?;
|
||||||
tx.execute("UPDATE metadata SET value=?1 WHERE key='sequence'", [next])?;
|
tx.execute("UPDATE counter SET seq=?1 WHERE id=1", [next])?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(u64::try_from(next)?)
|
Ok(u64::try_from(next)?)
|
||||||
}
|
}
|
||||||
|
pub fn connection(&self) -> &Connection {
|
||||||
|
&self.db
|
||||||
|
}
|
||||||
|
pub fn connection_mut(&mut self) -> &mut Connection {
|
||||||
|
&mut self.db
|
||||||
|
}
|
||||||
pub fn save(&self, envelope: &Envelope) -> Result<()> {
|
pub fn save(&self, envelope: &Envelope) -> Result<()> {
|
||||||
// This slice never deletes a durable event to make room for telemetry.
|
// This slice never deletes a durable event to make room for telemetry.
|
||||||
// At the fixed cap it stops collecting until concrete ACKs release room.
|
// At the fixed cap it stops collecting until concrete ACKs release room.
|
||||||
@@ -135,4 +158,182 @@ mod tests {
|
|||||||
drop(j);
|
drop(j);
|
||||||
std::fs::remove_dir_all(directory).unwrap();
|
std::fs::remove_dir_all(directory).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes() {
|
||||||
|
let directory =
|
||||||
|
std::env::temp_dir().join(format!("rmm-windows-capacity-{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir(&directory).unwrap();
|
||||||
|
let mut journal = Journal::open(&directory).unwrap();
|
||||||
|
journal.pin_identity("preserved-device").unwrap();
|
||||||
|
let sequence = journal.next_sequence().unwrap();
|
||||||
|
let envelope = Envelope {
|
||||||
|
message_id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
sequence,
|
||||||
|
payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
journal.save(&envelope).unwrap();
|
||||||
|
let original: Vec<u8> = journal
|
||||||
|
.db
|
||||||
|
.query_row(
|
||||||
|
"SELECT payload FROM events WHERE id=?1",
|
||||||
|
[&envelope.message_id],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// Simulate an earlier lower bound; reopening changes only the budget.
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.execute_batch("PRAGMA max_page_count=65536")
|
||||||
|
.unwrap();
|
||||||
|
drop(journal);
|
||||||
|
let mut journal = Journal::open(&directory).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.query_row("PRAGMA max_page_count", [], |r| r.get::<_, u32>(0))
|
||||||
|
.unwrap(),
|
||||||
|
262144
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.query_row("PRAGMA page_size", [], |r| r.get::<_, u32>(0))
|
||||||
|
.unwrap(),
|
||||||
|
4096
|
||||||
|
);
|
||||||
|
journal.pin_identity("preserved-device").unwrap();
|
||||||
|
assert_eq!(journal.next_sequence().unwrap(), sequence + 1);
|
||||||
|
// Core checkpoints and the old passive counter cannot diverge.
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.execute("UPDATE counter SET seq=seq+1 WHERE id=1", [])
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| r
|
||||||
|
.get::<_, i64>(0))
|
||||||
|
.unwrap(),
|
||||||
|
sequence as i64 + 2
|
||||||
|
);
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.execute("UPDATE metadata SET value=value+1 WHERE key='sequence'", [])
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.query_row("SELECT seq FROM counter WHERE id=1", [], |r| r
|
||||||
|
.get::<_, i64>(0))
|
||||||
|
.unwrap(),
|
||||||
|
sequence as i64 + 3
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.execute("UPDATE counter SET seq=0 WHERE id=1", [])
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.execute("UPDATE metadata SET value=0 WHERE key='sequence'", [])
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.db
|
||||||
|
.query_row(
|
||||||
|
"SELECT payload FROM events WHERE id=?1",
|
||||||
|
[&envelope.message_id],
|
||||||
|
|r| r.get::<_, Vec<u8>>(0)
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
original
|
||||||
|
);
|
||||||
|
journal.ack("different-message-id").unwrap();
|
||||||
|
assert_eq!(journal.count().unwrap(), 1);
|
||||||
|
drop(journal);
|
||||||
|
std::fs::remove_dir_all(directory).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_page_size_is_refused_without_mutating_existing_data() {
|
||||||
|
let directory =
|
||||||
|
std::env::temp_dir().join(format!("rmm-windows-page-size-{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir(&directory).unwrap();
|
||||||
|
let path = directory.join("telemetry.sqlite");
|
||||||
|
let db = Connection::open(&path).unwrap();
|
||||||
|
db.execute_batch("PRAGMA page_size=8192; CREATE TABLE retained(value BLOB); INSERT INTO retained VALUES(x'010203');").unwrap();
|
||||||
|
drop(db);
|
||||||
|
let error = Journal::open(&directory).err().expect("must refuse");
|
||||||
|
assert_eq!(error.to_string(), "JOURNAL_PAGE_SIZE_UNSUPPORTED");
|
||||||
|
let db = Connection::open(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
db.query_row("SELECT value FROM retained", [], |r| r.get::<_, Vec<u8>>(0))
|
||||||
|
.unwrap(),
|
||||||
|
vec![1, 2, 3]
|
||||||
|
);
|
||||||
|
drop(db);
|
||||||
|
std::fs::remove_dir_all(directory).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migrates_original_passive_schema_without_rewriting_pending_envelopes() {
|
||||||
|
let directory =
|
||||||
|
std::env::temp_dir().join(format!("rmm-windows-migrate-{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir(&directory).unwrap();
|
||||||
|
let db = Connection::open(directory.join("telemetry.sqlite")).unwrap();
|
||||||
|
db.execute_batch("CREATE TABLE metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL); INSERT INTO metadata VALUES('sequence',42); CREATE TABLE events(id TEXT PRIMARY KEY,payload BLOB NOT NULL); CREATE TABLE identity(agent TEXT PRIMARY KEY); INSERT INTO identity VALUES('original-device');").unwrap();
|
||||||
|
let envelope = Envelope {
|
||||||
|
message_id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
sequence: 42,
|
||||||
|
payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let bytes = envelope.encode_to_vec();
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO events VALUES(?1,?2)",
|
||||||
|
params![envelope.message_id, bytes],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
drop(db);
|
||||||
|
let mut journal = Journal::open(&directory).unwrap();
|
||||||
|
journal.pin_identity("original-device").unwrap();
|
||||||
|
assert_eq!(journal.next_sequence().unwrap(), 43);
|
||||||
|
assert_eq!(journal.events().unwrap()[0].encode_to_vec(), bytes);
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.connection()
|
||||||
|
.query_row("SELECT count(*) FROM job_attempts", [], |r| r
|
||||||
|
.get::<_, i64>(0))
|
||||||
|
.unwrap(),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
let journal_id: String = journal
|
||||||
|
.connection()
|
||||||
|
.query_row(
|
||||||
|
"SELECT journal_id FROM reconcile_meta WHERE id=1",
|
||||||
|
[],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
drop(journal);
|
||||||
|
let journal = Journal::open(&directory).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
journal
|
||||||
|
.connection()
|
||||||
|
.query_row(
|
||||||
|
"SELECT journal_id FROM reconcile_meta WHERE id=1",
|
||||||
|
[],
|
||||||
|
|r| r.get::<_, String>(0)
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
journal_id
|
||||||
|
);
|
||||||
|
drop(journal);
|
||||||
|
std::fs::remove_dir_all(directory).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,19 @@ pub mod journal;
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub mod native;
|
pub mod native;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
pub mod inventory;
|
||||||
|
#[cfg(windows)]
|
||||||
pub mod service;
|
pub mod service;
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub mod process;
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub mod actions;
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub mod clock;
|
||||||
|
#[cfg(all(windows, feature = "system-helper"))]
|
||||||
|
pub mod helper_ipc;
|
||||||
|
#[cfg(all(windows, feature = "system-helper"))]
|
||||||
|
pub mod helper_system;
|
||||||
|
|
||||||
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
|
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
|
||||||
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
|
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
|
||||||
|
|||||||
@@ -37,6 +37,90 @@ fn sid_string(sid: *mut c_void) -> Result<String> {
|
|||||||
}
|
}
|
||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
/// Verify the actual SCM process token; an administrator probe cannot stand in
|
||||||
|
/// for this check. No account switching or SYSTEM fallback exists.
|
||||||
|
pub fn require_local_service() -> Result<()> {
|
||||||
|
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||||
|
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
||||||
|
let mut token = ptr::null_mut();
|
||||||
|
ensure!(
|
||||||
|
unsafe { OpenProcessToken(GetCurrentProcess(), Security::TOKEN_QUERY, &mut token) } != 0,
|
||||||
|
"SERVICE_TOKEN_REQUIRED"
|
||||||
|
);
|
||||||
|
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||||
|
// Native structures require alignment, even though GetTokenInformation
|
||||||
|
// accepts a void pointer. Allocate pointer-aligned storage, with fixed cap.
|
||||||
|
let mut storage = vec![0usize; 256];
|
||||||
|
let mut size = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
Security::GetTokenInformation(
|
||||||
|
token.as_raw_handle(),
|
||||||
|
Security::TokenUser,
|
||||||
|
storage.as_mut_ptr().cast(),
|
||||||
|
(storage.len() * std::mem::size_of::<usize>()) as u32,
|
||||||
|
&mut size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"SERVICE_TOKEN_USER"
|
||||||
|
);
|
||||||
|
let user = unsafe { &*storage.as_ptr().cast::<Security::TOKEN_USER>() };
|
||||||
|
ensure!(
|
||||||
|
sid_string(user.User.Sid)? == "S-1-5-19",
|
||||||
|
"LOCAL_SERVICE_REQUIRED"
|
||||||
|
);
|
||||||
|
// A native SCM probe showed LocalService's unfiltered service token reports
|
||||||
|
// TokenElevation=1, type=Default, while SID19 has no enabled administrator
|
||||||
|
// membership. UAC elevation alone is not an account/administrator check.
|
||||||
|
// Reject thread impersonation before querying effective membership.
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::{ERROR_NO_TOKEN, GetLastError},
|
||||||
|
System::Threading::{GetCurrentThread, OpenThreadToken},
|
||||||
|
};
|
||||||
|
let mut thread_token = ptr::null_mut();
|
||||||
|
if unsafe {
|
||||||
|
OpenThreadToken(
|
||||||
|
GetCurrentThread(),
|
||||||
|
Security::TOKEN_QUERY,
|
||||||
|
1,
|
||||||
|
&mut thread_token,
|
||||||
|
)
|
||||||
|
} != 0
|
||||||
|
{
|
||||||
|
let _thread_token = unsafe { OwnedHandle::from_raw_handle(thread_token) };
|
||||||
|
anyhow::bail!("IMPERSONATED_EXECUTOR_FORBIDDEN");
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
unsafe { GetLastError() } == ERROR_NO_TOKEN,
|
||||||
|
"THREAD_TOKEN_UNVERIFIED"
|
||||||
|
);
|
||||||
|
let mut admin_sid = [0usize; 16];
|
||||||
|
let mut admin_size = std::mem::size_of_val(&admin_sid) as u32;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
Security::CreateWellKnownSid(
|
||||||
|
Security::WinBuiltinAdministratorsSid,
|
||||||
|
ptr::null_mut(),
|
||||||
|
admin_sid.as_mut_ptr().cast(),
|
||||||
|
&mut admin_size,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"ADMINISTRATOR_SID_QUERY"
|
||||||
|
);
|
||||||
|
let mut admin_member = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
Security::CheckTokenMembership(
|
||||||
|
ptr::null_mut(),
|
||||||
|
admin_sid.as_mut_ptr().cast(),
|
||||||
|
&mut admin_member,
|
||||||
|
)
|
||||||
|
} != 0
|
||||||
|
&& admin_member == 0,
|
||||||
|
"ADMINISTRATOR_EXECUTOR_FORBIDDEN"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
pub fn service_sid() -> Result<String> {
|
pub fn service_sid() -> Result<String> {
|
||||||
let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME));
|
let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME));
|
||||||
let mut sid_len = 0;
|
let mut sid_len = 0;
|
||||||
@@ -191,15 +275,19 @@ pub fn snapshot() -> Result<Value> {
|
|||||||
let build = registry_string("CurrentBuildNumber")?;
|
let build = registry_string("CurrentBuildNumber")?;
|
||||||
let os = format!("{product}; DisplayVersion={display}; Build={build}");
|
let os = format!("{product}; DisplayVersion={display}; Build={build}");
|
||||||
let completed = Utc::now();
|
let completed = Utc::now();
|
||||||
Ok(
|
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,
|
||||||
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,
|
||||||
"collection_started_at":started,"collection_completed_at":completed,
|
"observations":[
|
||||||
"observations":[
|
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
|
||||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
|
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
|
||||||
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
|
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||||
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
]});
|
||||||
]}),
|
snapshot["observations"]
|
||||||
)
|
.as_array_mut()
|
||||||
|
.context("INVENTORY_OBSERVATIONS")?
|
||||||
|
.extend(crate::inventory::observations());
|
||||||
|
snapshot["collection_completed_at"] = json!(Utc::now());
|
||||||
|
Ok(snapshot)
|
||||||
}
|
}
|
||||||
pub async fn boot_id() -> Result<String> {
|
pub async fn boot_id() -> Result<String> {
|
||||||
// Fixed passive query only. Never interpolates a job or caller-supplied code.
|
// Fixed passive query only. Never interpolates a job or caller-supplied code.
|
||||||
@@ -235,6 +323,19 @@ mod tests {
|
|||||||
assert!(v["root_total_bytes"].as_u64().unwrap() > 0);
|
assert!(v["root_total_bytes"].as_u64().unwrap() > 0);
|
||||||
assert!(v["root_available_inodes"].is_null());
|
assert!(v["root_available_inodes"].is_null());
|
||||||
assert!(!v["hostname"].as_str().unwrap().is_empty());
|
assert!(!v["hostname"].as_str().unwrap().is_empty());
|
||||||
|
let hardware = v["observations"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|o| o["scope"] == "windows.hardware")
|
||||||
|
.unwrap();
|
||||||
|
assert!(hardware["data"]["memory_total_bytes"].as_u64().unwrap() > 0);
|
||||||
|
assert!(
|
||||||
|
hardware["data"]["logical_processors_visible"]
|
||||||
|
.as_u64()
|
||||||
|
.unwrap()
|
||||||
|
> 0
|
||||||
|
);
|
||||||
assert!(
|
assert!(
|
||||||
v["observations"]
|
v["observations"]
|
||||||
.as_array()
|
.as_array()
|
||||||
|
|||||||
@@ -0,0 +1,406 @@
|
|||||||
|
//! Bounded Windows child process trees. No authorization is conferred here.
|
||||||
|
//! The caller must commit the verified grant/attempt consumption before run.
|
||||||
|
//! Job and handle lists are applied atomically by CreateProcessW (Windows 10+).
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use std::{
|
||||||
|
ffi::{OsStr, OsString},
|
||||||
|
mem::{size_of, size_of_val, zeroed},
|
||||||
|
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||||
|
path::Path,
|
||||||
|
ptr,
|
||||||
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::{
|
||||||
|
ERROR_BROKEN_PIPE, GetLastError, HANDLE, HANDLE_FLAG_INHERIT, STILL_ACTIVE,
|
||||||
|
SetHandleInformation,
|
||||||
|
},
|
||||||
|
Security::SECURITY_ATTRIBUTES,
|
||||||
|
Storage::FileSystem::ReadFile,
|
||||||
|
System::{
|
||||||
|
JobObjects::*,
|
||||||
|
Pipes::{CreatePipe, PeekNamedPipe},
|
||||||
|
Threading::*,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Output {
|
||||||
|
pub stdout: Vec<u8>,
|
||||||
|
pub stderr: Vec<u8>,
|
||||||
|
pub exit_code: Option<i32>,
|
||||||
|
pub truncated: bool,
|
||||||
|
/// A killed process can already have affected the machine: never retry it.
|
||||||
|
pub interrupted: bool,
|
||||||
|
pub cancelled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Windows CRT quoting, not shell escaping. PowerShell receives -File followed
|
||||||
|
/// by individual arguments; none are evaluated as a generated command string.
|
||||||
|
pub fn quote(arg: &OsStr) -> Result<Vec<u16>> {
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
let input: Vec<u16> = arg.encode_wide().collect();
|
||||||
|
ensure!(!input.contains(&0), "ARGUMENT_NUL");
|
||||||
|
let mut out = vec![b'"' as u16];
|
||||||
|
let mut slashes = 0;
|
||||||
|
for ch in input {
|
||||||
|
if ch == b'\\' as u16 {
|
||||||
|
slashes += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.extend(std::iter::repeat_n(
|
||||||
|
b'\\' as u16,
|
||||||
|
slashes * if ch == b'"' as u16 { 2 } else { 1 },
|
||||||
|
));
|
||||||
|
if ch == b'"' as u16 {
|
||||||
|
out.push(b'\\' as u16);
|
||||||
|
}
|
||||||
|
out.push(ch);
|
||||||
|
slashes = 0;
|
||||||
|
}
|
||||||
|
out.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2));
|
||||||
|
out.push(b'"' as u16);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned(raw: HANDLE) -> Result<OwnedHandle> {
|
||||||
|
ensure!(!raw.is_null() && raw != -1isize as HANDLE, "PROCESS_HANDLE");
|
||||||
|
// SAFETY: successful creating API transfers this unique, live handle.
|
||||||
|
Ok(unsafe { OwnedHandle::from_raw_handle(raw) })
|
||||||
|
}
|
||||||
|
fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
|
||||||
|
let mut read = ptr::null_mut();
|
||||||
|
let mut write = ptr::null_mut();
|
||||||
|
let security = SECURITY_ATTRIBUTES {
|
||||||
|
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||||
|
lpSecurityDescriptor: ptr::null_mut(),
|
||||||
|
bInheritHandle: 1,
|
||||||
|
};
|
||||||
|
// SAFETY: initialized output pointers and fixed-size security descriptor.
|
||||||
|
ensure!(
|
||||||
|
unsafe { CreatePipe(&mut read, &mut write, &security, 8192) } != 0,
|
||||||
|
"PROCESS_PIPE"
|
||||||
|
);
|
||||||
|
let read = owned(read)?;
|
||||||
|
let write = owned(write)?;
|
||||||
|
ensure!(
|
||||||
|
unsafe { SetHandleInformation(read.as_raw_handle(), HANDLE_FLAG_INHERIT, 0) } != 0,
|
||||||
|
"PIPE_READ_NOT_INHERITED"
|
||||||
|
);
|
||||||
|
Ok((read, write))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Attributes {
|
||||||
|
storage: Vec<usize>,
|
||||||
|
}
|
||||||
|
impl Attributes {
|
||||||
|
fn new() -> Result<Self> {
|
||||||
|
let mut bytes = 0;
|
||||||
|
unsafe {
|
||||||
|
InitializeProcThreadAttributeList(ptr::null_mut(), 2, 0, &mut bytes);
|
||||||
|
}
|
||||||
|
ensure!(bytes > 0 && bytes < 65536, "PROCESS_ATTRIBUTES_SIZE");
|
||||||
|
let mut storage = vec![0usize; bytes.div_ceil(size_of::<usize>())];
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), 2, 0, &mut bytes)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_ATTRIBUTES"
|
||||||
|
);
|
||||||
|
Ok(Self { storage })
|
||||||
|
}
|
||||||
|
fn pointer(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
|
||||||
|
self.storage.as_mut_ptr().cast()
|
||||||
|
}
|
||||||
|
fn set(&mut self, attribute: u32, handles: &[HANDLE]) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
UpdateProcThreadAttribute(
|
||||||
|
self.pointer(),
|
||||||
|
0,
|
||||||
|
attribute as usize,
|
||||||
|
handles.as_ptr().cast(),
|
||||||
|
std::mem::size_of_val(handles),
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null(),
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_ATTRIBUTE_BINDING"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Attributes {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
DeleteProcThreadAttributeList(self.pointer());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(
|
||||||
|
pipe: &OwnedHandle,
|
||||||
|
output: &mut Vec<u8>,
|
||||||
|
remaining: &mut usize,
|
||||||
|
truncated: &mut bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
// One bounded read per stream/iteration avoids starvation by a noisy child.
|
||||||
|
let mut available = 0;
|
||||||
|
if unsafe {
|
||||||
|
PeekNamedPipe(
|
||||||
|
pipe.as_raw_handle(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
0,
|
||||||
|
ptr::null_mut(),
|
||||||
|
&mut available,
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
} == 0
|
||||||
|
{
|
||||||
|
ensure!(
|
||||||
|
unsafe { GetLastError() } == ERROR_BROKEN_PIPE,
|
||||||
|
"PROCESS_PIPE_PEEK"
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if available == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut buffer = [0u8; 16384];
|
||||||
|
let mut read = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
ReadFile(
|
||||||
|
pipe.as_raw_handle(),
|
||||||
|
buffer.as_mut_ptr(),
|
||||||
|
available.min(buffer.len() as u32),
|
||||||
|
&mut read,
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_PIPE_READ"
|
||||||
|
);
|
||||||
|
let keep = (*remaining).min(read as usize);
|
||||||
|
output.extend_from_slice(&buffer[..keep]);
|
||||||
|
*remaining -= keep;
|
||||||
|
*truncated |= keep < read as usize;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(
|
||||||
|
executable: &Path,
|
||||||
|
arguments: &[OsString],
|
||||||
|
cwd: &Path,
|
||||||
|
seconds: u32,
|
||||||
|
max_bytes: usize,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
) -> Result<Output> {
|
||||||
|
ensure!(
|
||||||
|
executable.is_absolute() && cwd.is_absolute() && seconds > 0 && max_bytes <= 512 * 1024,
|
||||||
|
"PROCESS_LIMITS"
|
||||||
|
);
|
||||||
|
let (stdout, out_write) = pipe()?;
|
||||||
|
let (stderr, err_write) = pipe()?;
|
||||||
|
let (stdin, in_write) = pipe()?;
|
||||||
|
// The child reads immediate EOF. Only its read handle is inheritable.
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
SetHandleInformation(
|
||||||
|
stdin.as_raw_handle(),
|
||||||
|
HANDLE_FLAG_INHERIT,
|
||||||
|
HANDLE_FLAG_INHERIT,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"STDIN_INHERITANCE"
|
||||||
|
);
|
||||||
|
drop(in_write);
|
||||||
|
let job = owned(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) })?;
|
||||||
|
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
|
||||||
|
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
SetInformationJobObject(
|
||||||
|
job.as_raw_handle(),
|
||||||
|
JobObjectExtendedLimitInformation,
|
||||||
|
ptr::addr_of!(limits).cast(),
|
||||||
|
size_of_val(&limits) as u32,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_JOB_LIMITS"
|
||||||
|
);
|
||||||
|
let jobs = [job.as_raw_handle()];
|
||||||
|
let inherited = [
|
||||||
|
stdin.as_raw_handle(),
|
||||||
|
out_write.as_raw_handle(),
|
||||||
|
err_write.as_raw_handle(),
|
||||||
|
];
|
||||||
|
let mut attributes = Attributes::new()?;
|
||||||
|
attributes.set(PROC_THREAD_ATTRIBUTE_JOB_LIST, &jobs)?;
|
||||||
|
attributes.set(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &inherited)?;
|
||||||
|
let mut startup: STARTUPINFOEXW = unsafe { zeroed() };
|
||||||
|
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
|
||||||
|
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
|
||||||
|
startup.StartupInfo.hStdInput = stdin.as_raw_handle();
|
||||||
|
startup.StartupInfo.hStdOutput = out_write.as_raw_handle();
|
||||||
|
startup.StartupInfo.hStdError = err_write.as_raw_handle();
|
||||||
|
startup.lpAttributeList = attributes.pointer();
|
||||||
|
let mut command = quote(executable.as_os_str())?;
|
||||||
|
for arg in arguments {
|
||||||
|
command.push(b' ' as u16);
|
||||||
|
command.extend(quote(arg)?);
|
||||||
|
}
|
||||||
|
ensure!(command.len() < 32766, "PROCESS_ARGUMENT_LIMIT");
|
||||||
|
command.push(0);
|
||||||
|
let application = crate::native::wide(executable);
|
||||||
|
let directory = crate::native::wide(cwd);
|
||||||
|
let mut system_buffer = [0u16; 32768];
|
||||||
|
let system_length = unsafe {
|
||||||
|
windows_sys::Win32::System::SystemInformation::GetSystemWindowsDirectoryW(
|
||||||
|
system_buffer.as_mut_ptr(),
|
||||||
|
system_buffer.len() as u32,
|
||||||
|
)
|
||||||
|
} as usize;
|
||||||
|
ensure!(
|
||||||
|
system_length > 0 && system_length < system_buffer.len(),
|
||||||
|
"SYSTEM_ROOT"
|
||||||
|
);
|
||||||
|
let system = std::path::PathBuf::from(String::from_utf16(&system_buffer[..system_length])?);
|
||||||
|
// Minimal environment: no inherited tokens, proxy secrets, device paths,
|
||||||
|
// PSModulePath overrides, user profile or caller-controlled executable PATH.
|
||||||
|
let mut environment = Vec::new();
|
||||||
|
for value in [
|
||||||
|
format!("PATH={}\\System32;{}", system.display(), system.display()),
|
||||||
|
format!("SystemRoot={}", system.display()),
|
||||||
|
format!("TEMP={}", cwd.display()),
|
||||||
|
format!("TMP={}", cwd.display()),
|
||||||
|
format!("windir={}", system.display()),
|
||||||
|
] {
|
||||||
|
environment.extend(crate::native::wide(value));
|
||||||
|
}
|
||||||
|
environment.push(0);
|
||||||
|
let mut process: PROCESS_INFORMATION = unsafe { zeroed() };
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
CreateProcessW(
|
||||||
|
application.as_ptr(),
|
||||||
|
command.as_mut_ptr(),
|
||||||
|
ptr::null(),
|
||||||
|
ptr::null(),
|
||||||
|
1,
|
||||||
|
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
|
||||||
|
environment.as_ptr().cast(),
|
||||||
|
directory.as_ptr(),
|
||||||
|
&startup.StartupInfo,
|
||||||
|
&mut process,
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_CREATION_REFUSED"
|
||||||
|
);
|
||||||
|
let process_handle = owned(process.hProcess)?;
|
||||||
|
let _thread = owned(process.hThread)?;
|
||||||
|
// Handles not explicitly listed (including job, DB and keys) are never inherited.
|
||||||
|
drop(attributes);
|
||||||
|
drop(stdin);
|
||||||
|
drop(out_write);
|
||||||
|
drop(err_write);
|
||||||
|
let mut result = Output {
|
||||||
|
stdout: Vec::new(),
|
||||||
|
stderr: Vec::new(),
|
||||||
|
exit_code: None,
|
||||||
|
truncated: false,
|
||||||
|
interrupted: false,
|
||||||
|
cancelled: false,
|
||||||
|
};
|
||||||
|
let began = Instant::now();
|
||||||
|
let mut remaining = max_bytes;
|
||||||
|
loop {
|
||||||
|
drain(
|
||||||
|
&stdout,
|
||||||
|
&mut result.stdout,
|
||||||
|
&mut remaining,
|
||||||
|
&mut result.truncated,
|
||||||
|
)?;
|
||||||
|
drain(
|
||||||
|
&stderr,
|
||||||
|
&mut result.stderr,
|
||||||
|
&mut remaining,
|
||||||
|
&mut result.truncated,
|
||||||
|
)?;
|
||||||
|
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||||
|
ensure!(
|
||||||
|
unsafe {
|
||||||
|
QueryInformationJobObject(
|
||||||
|
job.as_raw_handle(),
|
||||||
|
JobObjectBasicAccountingInformation,
|
||||||
|
ptr::addr_of_mut!(accounting).cast(),
|
||||||
|
size_of_val(&accounting) as u32,
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
} != 0,
|
||||||
|
"PROCESS_TREE_STATE"
|
||||||
|
);
|
||||||
|
if accounting.ActiveProcesses == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if began.elapsed() >= Duration::from_secs(seconds.into()) || cancel.load(Ordering::SeqCst) {
|
||||||
|
result.cancelled = cancel.load(Ordering::SeqCst);
|
||||||
|
result.interrupted = true;
|
||||||
|
ensure!(
|
||||||
|
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||||
|
"PROCESS_TREE_TERMINATION"
|
||||||
|
);
|
||||||
|
// This wait proves termination, not absence of effects.
|
||||||
|
ensure!(
|
||||||
|
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||||
|
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||||
|
drop(job);
|
||||||
|
for _ in 0..8 {
|
||||||
|
drain(
|
||||||
|
&stdout,
|
||||||
|
&mut result.stdout,
|
||||||
|
&mut remaining,
|
||||||
|
&mut result.truncated,
|
||||||
|
)?;
|
||||||
|
drain(
|
||||||
|
&stderr,
|
||||||
|
&mut result.stderr,
|
||||||
|
&mut remaining,
|
||||||
|
&mut result.truncated,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
let mut code = 0;
|
||||||
|
ensure!(
|
||||||
|
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||||
|
&& code != STILL_ACTIVE as u32,
|
||||||
|
"PROCESS_EXIT_UNCONFIRMED"
|
||||||
|
);
|
||||||
|
result.exit_code = Some(code as i32);
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() {
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf16("e(OsStr::new("a b\\")).unwrap()).unwrap(),
|
||||||
|
"\"a b\\\\\""
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf16("e(OsStr::new("a\"b")).unwrap()).unwrap(),
|
||||||
|
"\"a\\\"b\""
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf16("e(OsStr::new("$(Get-Content x); & y")).unwrap()).unwrap(),
|
||||||
|
"\"$(Get-Content x); & y\""
|
||||||
|
);
|
||||||
|
assert!(quote(OsStr::new("a\0b")).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,25 @@
|
|||||||
use anyhow::{Result, ensure};
|
use anyhow::{Context, Result, ensure};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use prost::Message;
|
||||||
use rcgen::{CertificateParams, DnType, KeyPair};
|
use rcgen::{CertificateParams, DnType, KeyPair};
|
||||||
|
use rmm_agent_core::{
|
||||||
|
auth::{Binding, Outcome, Request},
|
||||||
|
jobs, ledger,
|
||||||
|
reconcile::{self, SyncClock},
|
||||||
|
};
|
||||||
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
|
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
|
||||||
|
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
|
||||||
use rmm_protocol::*;
|
use rmm_protocol::*;
|
||||||
|
use rusqlite::{Connection, OptionalExtension};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::atomic::{AtomicBool, Ordering},
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
|
||||||
|
},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@@ -22,6 +33,11 @@ struct Config {
|
|||||||
state_directory: PathBuf,
|
state_directory: PathBuf,
|
||||||
enrollment_token_file: PathBuf,
|
enrollment_token_file: PathBuf,
|
||||||
transport: String,
|
transport: String,
|
||||||
|
#[serde(default)]
|
||||||
|
job_binding_file: Option<PathBuf>,
|
||||||
|
// False until the independent LocalService clock qualification is complete.
|
||||||
|
#[serde(default)]
|
||||||
|
enable_jobs: bool,
|
||||||
}
|
}
|
||||||
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
@@ -105,6 +121,222 @@ async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
|
|||||||
fs::remove_file(&config.enrollment_token_file)?;
|
fs::remove_file(&config.enrollment_token_file)?;
|
||||||
Ok(identity)
|
Ok(identity)
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct JobClock {
|
||||||
|
native: Arc<rmm_agent_windows::clock::NativeClock>,
|
||||||
|
enabled: bool,
|
||||||
|
}
|
||||||
|
impl SyncClock for JobClock {
|
||||||
|
fn now(&self) -> Result<chrono::DateTime<Utc>> {
|
||||||
|
ensure!(self.enabled, "WINDOWS_JOBS_NOT_ENABLED");
|
||||||
|
self.native.now()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Default)]
|
||||||
|
struct EffectFence {
|
||||||
|
generation: AtomicU64,
|
||||||
|
deadline: AtomicI64,
|
||||||
|
}
|
||||||
|
impl EffectFence {
|
||||||
|
fn close(&self) {
|
||||||
|
self.generation.store(0, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
fn allows(&self, generation: u64, clock: &impl SyncClock) -> bool {
|
||||||
|
self.generation.load(Ordering::SeqCst) == generation
|
||||||
|
&& generation > 0
|
||||||
|
&& clock.now().is_ok_and(|now| {
|
||||||
|
(now + chrono::Duration::seconds(2)).timestamp_millis()
|
||||||
|
< self.deadline.load(Ordering::SeqCst)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
type Completion = (JobOffer, ExecutionPermitPayload, Outcome);
|
||||||
|
struct Running {
|
||||||
|
offer: JobOffer,
|
||||||
|
grant: ExecutionPermitPayload,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
worker: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
fn verified_window(
|
||||||
|
binding: &Binding,
|
||||||
|
request: &Request,
|
||||||
|
clock: &impl SyncClock,
|
||||||
|
) -> Result<(rmm_domain::jobs::JobPayload, ExecutionPermitPayload)> {
|
||||||
|
let now = clock.now()?;
|
||||||
|
// The entire qualified <=2s clock interval must lie inside the grant window.
|
||||||
|
let result = binding.verify(request, now - chrono::Duration::seconds(2))?;
|
||||||
|
binding.verify(request, now + chrono::Duration::seconds(2))?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
fn readonly_binding(path: &Path) -> Result<Binding> {
|
||||||
|
use std::ptr;
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::LocalFree,
|
||||||
|
Security::{
|
||||||
|
self, ACCESS_ALLOWED_ACE, ACL,
|
||||||
|
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||||
|
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
unsafe fn sid(sid: Security::PSID) -> Result<String> {
|
||||||
|
let mut raw = ptr::null_mut();
|
||||||
|
ensure!(
|
||||||
|
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
|
||||||
|
"BINDING_SID"
|
||||||
|
);
|
||||||
|
let mut len = 0;
|
||||||
|
while unsafe { *raw.add(len) } != 0 {
|
||||||
|
len += 1;
|
||||||
|
ensure!(len < 256, "BINDING_SID_LIMIT");
|
||||||
|
}
|
||||||
|
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
|
||||||
|
unsafe {
|
||||||
|
LocalFree(raw.cast());
|
||||||
|
}
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
|
||||||
|
// The immediate configuration directory must also deny agent replacement.
|
||||||
|
for (item, directory) in [
|
||||||
|
(path, false),
|
||||||
|
(path.parent().context("BINDING_PARENT")?, true),
|
||||||
|
] {
|
||||||
|
native::private_path(item, directory)?;
|
||||||
|
let mut owner = ptr::null_mut();
|
||||||
|
let mut dacl: *mut ACL = ptr::null_mut();
|
||||||
|
let mut descriptor = ptr::null_mut();
|
||||||
|
let status = unsafe {
|
||||||
|
GetNamedSecurityInfoW(
|
||||||
|
native::wide(item).as_ptr(),
|
||||||
|
SE_FILE_OBJECT,
|
||||||
|
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||||
|
&mut owner,
|
||||||
|
ptr::null_mut(),
|
||||||
|
&mut dacl,
|
||||||
|
ptr::null_mut(),
|
||||||
|
&mut descriptor,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
ensure!(status == 0, "BINDING_SECURITY");
|
||||||
|
let check = (|| -> Result<()> {
|
||||||
|
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
|
||||||
|
ensure!(
|
||||||
|
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
|
||||||
|
"BINDING_ADMIN_OWNER_REQUIRED"
|
||||||
|
);
|
||||||
|
for index in 0..unsafe { (*dacl).AceCount } {
|
||||||
|
let mut raw = ptr::null_mut();
|
||||||
|
ensure!(
|
||||||
|
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
|
||||||
|
"BINDING_ACE"
|
||||||
|
);
|
||||||
|
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
|
||||||
|
ensure!(
|
||||||
|
ace.Header.AceType == 0
|
||||||
|
&& usize::from(ace.Header.AceSize)
|
||||||
|
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||||
|
"BINDING_ACE_TYPE"
|
||||||
|
);
|
||||||
|
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
|
||||||
|
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
|
||||||
|
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
|
||||||
|
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
unsafe {
|
||||||
|
LocalFree(descriptor.cast());
|
||||||
|
}
|
||||||
|
check?;
|
||||||
|
}
|
||||||
|
let binding: Binding = serde_json::from_slice(&protected_read(path, 8192)?)?;
|
||||||
|
ensure!(
|
||||||
|
!binding.tenant_id.is_nil()
|
||||||
|
&& !binding.agent_id.is_nil()
|
||||||
|
&& !binding.asset_id.is_nil()
|
||||||
|
&& binding.enrollment_generation > 0
|
||||||
|
&& binding.assignment_version > 0
|
||||||
|
&& binding.public_key_hex.len() == 64
|
||||||
|
&& binding
|
||||||
|
.public_key_hex
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_hexdigit()),
|
||||||
|
"JOB_BINDING_PROFILE"
|
||||||
|
);
|
||||||
|
Ok(binding)
|
||||||
|
}
|
||||||
|
fn import_legacy_inventory(journal: &mut Journal) -> Result<()> {
|
||||||
|
let original = {
|
||||||
|
let mut q = journal
|
||||||
|
.connection()
|
||||||
|
.prepare("SELECT id,payload FROM events ORDER BY rowid")?;
|
||||||
|
q.query_map([], |r| {
|
||||||
|
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
|
||||||
|
})?
|
||||||
|
.collect::<rusqlite::Result<Vec<_>>>()?
|
||||||
|
};
|
||||||
|
let tx = journal.connection_mut().transaction()?;
|
||||||
|
for (id, bytes) in original {
|
||||||
|
let envelope = Envelope::decode(bytes.as_slice())?;
|
||||||
|
ensure!(
|
||||||
|
envelope.message_id == id
|
||||||
|
&& matches!(envelope.payload, Some(Payload::InventorySnapshot(_))),
|
||||||
|
"LEGACY_INVENTORY_BINDING"
|
||||||
|
);
|
||||||
|
let old: Option<Vec<u8>> = tx
|
||||||
|
.query_row("SELECT payload FROM job_events WHERE id=?1", [&id], |r| {
|
||||||
|
r.get(0)
|
||||||
|
})
|
||||||
|
.optional()?;
|
||||||
|
ensure!(
|
||||||
|
old.as_ref().is_none_or(|old| old == &bytes),
|
||||||
|
"LEGACY_INVENTORY_CONFLICT"
|
||||||
|
);
|
||||||
|
// Copy original bytes/ID, never decode/re-encode or discard pending telemetry.
|
||||||
|
tx.execute(
|
||||||
|
"INSERT OR IGNORE INTO job_events(id,payload) VALUES(?1,?2)",
|
||||||
|
rusqlite::params![id, bytes],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
// Core ACK/Sync deletion and the old queue advance in the SAME transaction.
|
||||||
|
tx.execute_batch("CREATE TRIGGER IF NOT EXISTS windows_legacy_inventory_ack AFTER DELETE ON job_events BEGIN DELETE FROM events WHERE id=OLD.id AND payload=OLD.payload; END;")?;
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn open_ledger(directory: &Path, binding: &Binding) -> Result<(Connection, fs::File)> {
|
||||||
|
use std::os::windows::fs::OpenOptionsExt;
|
||||||
|
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
|
||||||
|
let path = directory.join("consumption.sqlite");
|
||||||
|
let file = fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
||||||
|
.open(&path)?;
|
||||||
|
native::private_path(&path, false)?;
|
||||||
|
let db = Connection::open(&path)?;
|
||||||
|
ledger::initialize_ledger(&db)?;
|
||||||
|
db.execute_batch("CREATE TABLE IF NOT EXISTS windows_binding(identity TEXT NOT NULL);")?;
|
||||||
|
let identity = format!(
|
||||||
|
"{}:{}:{}:{}:{}",
|
||||||
|
binding.tenant_id,
|
||||||
|
binding.asset_id,
|
||||||
|
binding.agent_id,
|
||||||
|
binding.enrollment_generation,
|
||||||
|
binding.assignment_version
|
||||||
|
);
|
||||||
|
let old: Option<String> = db
|
||||||
|
.query_row("SELECT identity FROM windows_binding", [], |r| r.get(0))
|
||||||
|
.optional()?;
|
||||||
|
if let Some(old) = old {
|
||||||
|
ensure!(old == identity, "LEDGER_IDENTITY_MISMATCH");
|
||||||
|
} else {
|
||||||
|
db.execute("INSERT INTO windows_binding VALUES(?1)", [identity])?;
|
||||||
|
}
|
||||||
|
Ok((db, file))
|
||||||
|
}
|
||||||
struct Agent {
|
struct Agent {
|
||||||
config: Config,
|
config: Config,
|
||||||
identity: EnrollmentResponse,
|
identity: EnrollmentResponse,
|
||||||
@@ -113,15 +345,347 @@ struct Agent {
|
|||||||
boot: String,
|
boot: String,
|
||||||
instance: String,
|
instance: String,
|
||||||
started: Instant,
|
started: Instant,
|
||||||
|
binding: Option<Binding>,
|
||||||
|
ledger: Option<Connection>,
|
||||||
|
_ledger_file: Option<fs::File>,
|
||||||
|
clock: JobClock,
|
||||||
|
sync: Option<reconcile::ClientSync>,
|
||||||
|
prepared: bool,
|
||||||
|
fence: Arc<EffectFence>,
|
||||||
|
completed_tx: tokio::sync::mpsc::Sender<Completion>,
|
||||||
|
completed_rx: tokio::sync::mpsc::Receiver<Completion>,
|
||||||
|
running: Option<Running>,
|
||||||
|
deferred_permit: Option<(u64, ExecutionPermit)>,
|
||||||
}
|
}
|
||||||
impl Agent {
|
impl Agent {
|
||||||
|
fn close_gate(&mut self) {
|
||||||
|
self.fence.close();
|
||||||
|
if let Some(sync) = &mut self.sync {
|
||||||
|
sync.close();
|
||||||
|
}
|
||||||
|
self.prepared = false;
|
||||||
|
self.deferred_permit = None;
|
||||||
|
}
|
||||||
|
fn channel(&self, generation: u64) -> Result<reconcile::Channel> {
|
||||||
|
Ok(reconcile::Channel {
|
||||||
|
connection_generation: generation,
|
||||||
|
boot_id: Uuid::parse_str(&self.boot)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn ready(&self, generation: u64) -> bool {
|
||||||
|
self.config.enable_jobs
|
||||||
|
&& self.channel(generation).is_ok_and(|channel| {
|
||||||
|
self.sync
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|sync| sync.can_start(&channel, false, &self.clock))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> Vec<String> {
|
||||||
|
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
|
||||||
|
if self.config.enable_jobs
|
||||||
|
&& self.binding.is_some()
|
||||||
|
&& native::require_local_service().is_ok()
|
||||||
|
&& self.clock.now().is_ok()
|
||||||
|
{
|
||||||
|
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
|
||||||
|
if rmm_agent_windows::actions::powershell().is_ok() {
|
||||||
|
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
caps
|
||||||
|
}
|
||||||
|
fn record(
|
||||||
|
&mut self,
|
||||||
|
generation: u64,
|
||||||
|
offer: &JobOffer,
|
||||||
|
grant: &str,
|
||||||
|
outcome: Outcome,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut envelope = self.envelope(generation, Payload::JobResult(JobResult::default()))?;
|
||||||
|
let tx = self.journal.connection_mut().transaction()?;
|
||||||
|
let revision = jobs::transition(&tx, offer, &outcome.state, grant)?;
|
||||||
|
envelope.payload = Some(Payload::JobResult(jobs::result(
|
||||||
|
offer, revision, grant, outcome,
|
||||||
|
)));
|
||||||
|
jobs::event(&tx, &envelope)?;
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn recover_interrupted(&mut self) -> Result<()> {
|
||||||
|
let Some(binding) = self.binding.clone() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let interrupted = jobs::interrupted(
|
||||||
|
self.journal.connection(),
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&binding,
|
||||||
|
)?;
|
||||||
|
for (offer, grant) in interrupted {
|
||||||
|
if grant.is_empty() {
|
||||||
|
jobs::interrupted_request(self.journal.connection(), &offer)?;
|
||||||
|
} else {
|
||||||
|
let outcome = jobs::recover_interrupted_outcome(
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&binding,
|
||||||
|
&offer,
|
||||||
|
&grant,
|
||||||
|
)?
|
||||||
|
.unwrap_or_else(|| Outcome::unknown("AGENT_PROCESS_INTERRUPTED"));
|
||||||
|
// Replay original durable evidence only. Normal signed Sync,
|
||||||
|
// never startup, releases the previously consumed attempt.
|
||||||
|
self.record(0, &offer, &grant, outcome)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn replay(
|
||||||
|
&mut self,
|
||||||
|
channel: &crate::wire_channel::Handle,
|
||||||
|
generation: u64,
|
||||||
|
) -> Result<()> {
|
||||||
|
let events = jobs::events(self.journal.connection())?;
|
||||||
|
let passive = self.journal.events()?;
|
||||||
|
tokio::time::timeout(Duration::from_secs(2), async {
|
||||||
|
for mut event in events.into_iter().chain(passive).take(8) {
|
||||||
|
event.connection_generation = generation;
|
||||||
|
channel.send(&event).await?;
|
||||||
|
}
|
||||||
|
Ok::<_, anyhow::Error>(())
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn start_sync(
|
||||||
|
&mut self,
|
||||||
|
channel: &crate::wire_channel::Handle,
|
||||||
|
generation: u64,
|
||||||
|
) -> Result<()> {
|
||||||
|
self.fence.close();
|
||||||
|
let context = self.channel(generation)?;
|
||||||
|
let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?;
|
||||||
|
let prepared = sync.prepare(
|
||||||
|
self.journal.connection_mut(),
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
context,
|
||||||
|
None,
|
||||||
|
&self.clock,
|
||||||
|
)?;
|
||||||
|
self.prepared = true;
|
||||||
|
channel.send(&prepared.envelope).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn apply_sync(&mut self, generation: u64, response: SyncResponse) -> Result<()> {
|
||||||
|
ensure!(self.prepared, "UNSOLICITED_SYNC_RESPONSE");
|
||||||
|
self.prepared = false;
|
||||||
|
let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?;
|
||||||
|
let applied = sync.apply(self.journal.connection_mut(), &response, &self.clock)?;
|
||||||
|
ensure!(
|
||||||
|
applied.helper_instruction.is_none(),
|
||||||
|
"WINDOWS_HELPER_NOT_CONFIGURED"
|
||||||
|
);
|
||||||
|
sync.apply_consumption(
|
||||||
|
self.ledger.as_mut().context("LEDGER_REQUIRED")?,
|
||||||
|
&self.clock,
|
||||||
|
)?;
|
||||||
|
if self.ready(generation) {
|
||||||
|
let deadline = self
|
||||||
|
.sync
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|sync| sync.validity_deadline())
|
||||||
|
.context("SIGNED_LEASE_REQUIRED")?;
|
||||||
|
self.fence
|
||||||
|
.deadline
|
||||||
|
.store(deadline.timestamp_millis(), Ordering::SeqCst);
|
||||||
|
self.fence.generation.store(generation, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn completed(&mut self, generation: u64, (offer, grant, outcome): Completion) -> Result<()> {
|
||||||
|
let running = self
|
||||||
|
.running
|
||||||
|
.as_ref()
|
||||||
|
.context("UNSOLICITED_EXECUTOR_COMPLETION")?;
|
||||||
|
ensure!(
|
||||||
|
running.offer.job_id == offer.job_id
|
||||||
|
&& running.offer.attempt_id == offer.attempt_id
|
||||||
|
&& running.grant == grant,
|
||||||
|
"EXECUTOR_COMPLETION_BINDING"
|
||||||
|
);
|
||||||
|
ledger::persist_outcome(
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&grant,
|
||||||
|
&outcome,
|
||||||
|
)?;
|
||||||
|
self.record(
|
||||||
|
generation,
|
||||||
|
&offer,
|
||||||
|
&grant.grant_id.to_string(),
|
||||||
|
outcome.clone(),
|
||||||
|
)?;
|
||||||
|
ledger::finish(
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&grant,
|
||||||
|
&outcome,
|
||||||
|
)?;
|
||||||
|
self.running = None;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn permit(&mut self, generation: u64, permit: ExecutionPermit) -> Result<()> {
|
||||||
|
if let Some((old_generation, old)) = &self.deferred_permit {
|
||||||
|
ensure!(
|
||||||
|
*old_generation == generation && *old == permit,
|
||||||
|
"PENDING_PERMIT_CONFLICT"
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let offer = jobs::requesting(self.journal.connection())?.context("UNSOLICITED_PERMIT")?;
|
||||||
|
if !permit.denial_code.is_empty() {
|
||||||
|
self.record(
|
||||||
|
generation,
|
||||||
|
&offer,
|
||||||
|
"",
|
||||||
|
Outcome::unknown("PERMIT_DENIED_RECONCILIATION_REQUIRED"),
|
||||||
|
)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
self.ready(generation) && self.running.is_none(),
|
||||||
|
"FENCED_SYNC_REQUIRED"
|
||||||
|
);
|
||||||
|
let binding = self
|
||||||
|
.binding
|
||||||
|
.as_ref()
|
||||||
|
.context("JOB_BINDING_REQUIRED")?
|
||||||
|
.clone();
|
||||||
|
let request = jobs::permit_request(&offer, &permit)?;
|
||||||
|
let now = self.clock.now()?;
|
||||||
|
// Authenticate before interpreting timing. A freshly issued grant may
|
||||||
|
// need two seconds before the full uncertainty interval is inside it.
|
||||||
|
let (_, authenticated) = binding.verify(&request, now + chrono::Duration::seconds(2))?;
|
||||||
|
if now - chrono::Duration::seconds(2) < authenticated.not_before {
|
||||||
|
self.deferred_permit = Some((generation, permit));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let (job, grant) = verified_window(&binding, &request, &self.clock)?;
|
||||||
|
ensure!(
|
||||||
|
rmm_agent_windows::actions::supported(&job),
|
||||||
|
"UNSUPPORTED_CAPABILITY"
|
||||||
|
);
|
||||||
|
let started_at = self.clock.now()?;
|
||||||
|
let ledger = self.ledger.as_mut().context("LEDGER_REQUIRED")?;
|
||||||
|
ledger::begin_execution(
|
||||||
|
ledger,
|
||||||
|
&grant,
|
||||||
|
&request,
|
||||||
|
Uuid::parse_str(&self.boot)?,
|
||||||
|
started_at,
|
||||||
|
)?;
|
||||||
|
let cancelled: bool = self.journal.connection().query_row(
|
||||||
|
"SELECT cancel_requested FROM job_attempts WHERE job=?1 AND attempt=?2",
|
||||||
|
rusqlite::params![offer.job_id, offer.attempt_id],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
if cancelled {
|
||||||
|
let outcome = jobs::no_start("cancelled", "CANCELLED_BEFORE_EFFECT");
|
||||||
|
ledger::persist_outcome(
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&grant,
|
||||||
|
&outcome,
|
||||||
|
)?;
|
||||||
|
self.record(
|
||||||
|
generation,
|
||||||
|
&offer,
|
||||||
|
&grant.grant_id.to_string(),
|
||||||
|
outcome.clone(),
|
||||||
|
)?;
|
||||||
|
ledger::finish(
|
||||||
|
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
|
||||||
|
&grant,
|
||||||
|
&outcome,
|
||||||
|
)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut started = self.envelope(
|
||||||
|
generation,
|
||||||
|
Payload::JobStateChanged(JobStateChanged::default()),
|
||||||
|
)?;
|
||||||
|
let tx = self.journal.connection_mut().transaction()?;
|
||||||
|
let revision = jobs::transition(&tx, &offer, "running", &grant.grant_id.to_string())?;
|
||||||
|
started.payload = Some(Payload::JobStateChanged(JobStateChanged {
|
||||||
|
job_id: offer.job_id.clone(),
|
||||||
|
attempt_id: offer.attempt_id.clone(),
|
||||||
|
revision,
|
||||||
|
state: "running".into(),
|
||||||
|
grant_id: grant.grant_id.to_string(),
|
||||||
|
}));
|
||||||
|
jobs::event(&tx, &started)?;
|
||||||
|
tx.commit()?;
|
||||||
|
let cancelled = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker_cancel = cancelled.clone();
|
||||||
|
let clock = self.clock.clone();
|
||||||
|
let fence = self.fence.clone();
|
||||||
|
let completed = self.completed_tx.clone();
|
||||||
|
let directory = self.config.state_directory.join("jobs");
|
||||||
|
let work_offer = offer.clone();
|
||||||
|
let work_grant = grant.clone();
|
||||||
|
let worker = tokio::task::spawn_blocking(move || {
|
||||||
|
let outcome = (|| -> Result<Outcome> {
|
||||||
|
if !fence.allows(generation, &clock)
|
||||||
|
|| verified_window(&binding, &request, &clock).is_err()
|
||||||
|
{
|
||||||
|
return Ok(jobs::no_start(
|
||||||
|
"failed",
|
||||||
|
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let script = if matches!(job.action, Action::RunScript { .. }) {
|
||||||
|
match rmm_agent_windows::actions::Script::prepare(
|
||||||
|
&job,
|
||||||
|
&directory,
|
||||||
|
work_grant.grant_id,
|
||||||
|
) {
|
||||||
|
Ok(script) => Some(script),
|
||||||
|
Err(_) => return Ok(jobs::no_start("failed", "SCRIPT_PREPARATION_FAILED")),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
// File creation, pool scheduling and fsync never extend a start window.
|
||||||
|
if worker_cancel.load(Ordering::SeqCst) {
|
||||||
|
return Ok(jobs::no_start("cancelled", "CANCELLED_BEFORE_EFFECT"));
|
||||||
|
}
|
||||||
|
if !fence.allows(generation, &clock)
|
||||||
|
|| verified_window(&binding, &request, &clock).is_err()
|
||||||
|
{
|
||||||
|
return Ok(jobs::no_start(
|
||||||
|
"failed",
|
||||||
|
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(script) = script {
|
||||||
|
script.run(&job, &worker_cancel)
|
||||||
|
} else {
|
||||||
|
rmm_agent_windows::actions::inventory(&job)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
|
||||||
|
let _ = completed.blocking_send((work_offer, work_grant, outcome));
|
||||||
|
});
|
||||||
|
self.running = Some(Running {
|
||||||
|
offer,
|
||||||
|
grant,
|
||||||
|
cancel: cancelled,
|
||||||
|
worker,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
fn envelope(&mut self, generation: u64, payload: Payload) -> Result<Envelope> {
|
fn envelope(&mut self, generation: u64, payload: Payload) -> Result<Envelope> {
|
||||||
Ok(Envelope {
|
Ok(Envelope {
|
||||||
protocol_major: 1,
|
protocol_major: 1,
|
||||||
protocol_minor: 0,
|
protocol_minor: 0,
|
||||||
message_id: Uuid::new_v4().to_string(),
|
message_id: Uuid::new_v4().to_string(),
|
||||||
agent_id: self.identity.agent_id.clone(),
|
agent_id: self.identity.agent_id.clone(),
|
||||||
enrollment_generation: 1,
|
enrollment_generation: self.binding.as_ref().map_or(1, |b| b.enrollment_generation),
|
||||||
connection_generation: generation,
|
connection_generation: generation,
|
||||||
boot_id: self.boot.clone(),
|
boot_id: self.boot.clone(),
|
||||||
sequence: self.journal.next_sequence()?,
|
sequence: self.journal.next_sequence()?,
|
||||||
@@ -130,7 +694,7 @@ impl Agent {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn queue_inventory(&mut self, generation: u64) -> Result<()> {
|
fn queue_inventory(&mut self, generation: u64) -> Result<()> {
|
||||||
if self.journal.count()? > 0 {
|
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let data = serde_json::to_vec(&native::snapshot()?)?;
|
let data = serde_json::to_vec(&native::snapshot()?)?;
|
||||||
@@ -148,14 +712,26 @@ impl Agent {
|
|||||||
completeness: "partial".into(),
|
completeness: "partial".into(),
|
||||||
}),
|
}),
|
||||||
)?;
|
)?;
|
||||||
self.journal.save(&envelope)
|
if self.binding.is_some() {
|
||||||
|
jobs::event(self.journal.connection(), &envelope)
|
||||||
|
} else {
|
||||||
|
self.journal.save(&envelope)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
async fn session(&mut self, stop: &AtomicBool) -> Result<()> {
|
async fn session(&mut self, stop: &AtomicBool) -> Result<()> {
|
||||||
|
self.close_gate();
|
||||||
|
let result = self.session_inner(stop).await;
|
||||||
|
self.close_gate();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
async fn session_inner(&mut self, stop: &AtomicBool) -> Result<()> {
|
||||||
|
self.boot = native::boot_id().await?;
|
||||||
|
let advertised = self.capabilities();
|
||||||
let hello = self.envelope(
|
let hello = self.envelope(
|
||||||
0,
|
0,
|
||||||
Payload::ClientHello(ClientHello {
|
Payload::ClientHello(ClientHello {
|
||||||
agent_version: env!("CARGO_PKG_VERSION").into(),
|
agent_version: env!("CARGO_PKG_VERSION").into(),
|
||||||
capabilities: CAPABILITIES.iter().map(|v| v.to_string()).collect(),
|
capabilities: advertised.clone(),
|
||||||
}),
|
}),
|
||||||
)?;
|
)?;
|
||||||
let identity = crate::certificate_rotation::DeviceIdentity {
|
let identity = crate::certificate_rotation::DeviceIdentity {
|
||||||
@@ -180,7 +756,8 @@ impl Agent {
|
|||||||
let reply = tokio::time::timeout(Duration::from_secs(20), channel.receive()).await??;
|
let reply = tokio::time::timeout(Duration::from_secs(20), channel.receive()).await??;
|
||||||
ensure!(
|
ensure!(
|
||||||
reply.agent_id == self.identity.agent_id
|
reply.agent_id == self.identity.agent_id
|
||||||
&& reply.enrollment_generation == 1
|
&& reply.enrollment_generation
|
||||||
|
== self.binding.as_ref().map_or(1, |b| b.enrollment_generation)
|
||||||
&& reply.protocol_major == 1
|
&& reply.protocol_major == 1
|
||||||
&& reply.protocol_minor == 0,
|
&& reply.protocol_minor == 0,
|
||||||
"SERVER_HELLO_BINDING"
|
"SERVER_HELLO_BINDING"
|
||||||
@@ -194,26 +771,96 @@ impl Agent {
|
|||||||
"SERVER_LIMITS"
|
"SERVER_LIMITS"
|
||||||
);
|
);
|
||||||
self.queue_inventory(generation)?;
|
self.queue_inventory(generation)?;
|
||||||
|
self.replay(&channel, generation).await?;
|
||||||
|
let mut needs_sync = self.sync.is_some();
|
||||||
|
if self.sync.is_some() && self.running.is_none() {
|
||||||
|
if self.start_sync(&channel, generation).await.is_err() {
|
||||||
|
self.close_gate();
|
||||||
|
} else {
|
||||||
|
needs_sync = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut sync_at = Instant::now();
|
||||||
|
let mut capabilities_at = Instant::now();
|
||||||
let mut replay = Instant::now() - Duration::from_secs(10);
|
let mut replay = Instant::now() - Duration::from_secs(10);
|
||||||
let mut inventory = Instant::now();
|
let mut inventory = Instant::now();
|
||||||
let mut heartbeat = Instant::now() - Duration::from_secs(60);
|
let mut heartbeat = Instant::now() - Duration::from_secs(60);
|
||||||
let mut heartbeat_after = Duration::from_secs(30);
|
let mut heartbeat_after = Duration::from_secs(30);
|
||||||
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
||||||
while !stop.load(Ordering::SeqCst) {
|
while !stop.load(Ordering::SeqCst) || self.running.is_some() {
|
||||||
|
if stop.load(Ordering::SeqCst) {
|
||||||
|
self.close_gate();
|
||||||
|
if let Some(running) = &self.running {
|
||||||
|
running.cancel.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_=tick.tick()=>{},
|
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
|
||||||
|
_=tick.tick()=>{
|
||||||
|
if !stop.load(Ordering::SeqCst) && let Some((pending_generation,permit))=self.deferred_permit.take() {
|
||||||
|
ensure!(pending_generation==generation,"PENDING_PERMIT_GENERATION");self.permit(generation,permit)?;
|
||||||
|
}
|
||||||
|
if self.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
|
||||||
|
if let Ok(completion)=self.completed_rx.try_recv(){self.completed(generation,completion)?;}
|
||||||
|
else {let running=self.running.as_ref().context("RUNNING_REQUIRED")?;self.completed(generation,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;}
|
||||||
|
needs_sync=true;
|
||||||
|
}
|
||||||
|
let busy=self.running.is_some() || self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?;
|
||||||
|
if !stop.load(Ordering::SeqCst) && !busy {
|
||||||
|
if capabilities_at.elapsed()>=Duration::from_secs(60) {capabilities_at=Instant::now();if advertised!=self.capabilities(){return Ok(());}}
|
||||||
|
if self.prepared && sync_at.elapsed()>=Duration::from_secs(20){self.close_gate();needs_sync=true;}
|
||||||
|
if self.sync.is_some() && !self.prepared && (needs_sync || sync_at.elapsed()>=Duration::from_secs(40) || !self.ready(generation)) {
|
||||||
|
if self.start_sync(&channel,generation).await.is_err(){self.close_gate();needs_sync=true;}else{needs_sync=false;}sync_at=Instant::now();
|
||||||
|
}
|
||||||
|
if !needs_sync && !self.prepared && self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
|
||||||
|
let now=self.clock.now()?;
|
||||||
|
if let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
|
||||||
|
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
|
||||||
|
if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;}
|
||||||
|
else if now-chrono::Duration::seconds(2)>=job.not_before {
|
||||||
|
jobs::reserve_request(self.journal.connection(),&offer)?;
|
||||||
|
let request=self.envelope(generation,Payload::ExecutionPermitRequest(ExecutionPermitRequest{job_id:offer.job_id,attempt_id:offer.attempt_id,job_payload_hash:offer.job_payload_hash,assignment_version:job.assignment_version}))?;
|
||||||
|
channel.send(&request).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
message=channel.receive()=>{
|
message=channel.receive()=>{
|
||||||
let message=message?;
|
let message=message?;
|
||||||
ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==1 && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING");
|
ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==self.binding.as_ref().map_or(1,|b|b.enrollment_generation) && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING");
|
||||||
match message.payload {
|
match message.payload {
|
||||||
Some(Payload::Ack(ack))=>self.journal.ack(&ack.message_id)?,
|
Some(Payload::Ack(ack))=>{
|
||||||
// There is deliberately no acceptance/start path. A stale
|
let pending:Option<Vec<u8>>=self.journal.connection().query_row("SELECT payload FROM job_events WHERE id=?1",[&ack.message_id],|r|r.get(0)).optional()?;
|
||||||
// or malicious offer cannot activate an unimplemented job.
|
if let Some(bytes)=pending && matches!(Envelope::decode(bytes.as_slice())?.payload,Some(Payload::InventorySnapshot(_)|Payload::JobResult(_))){needs_sync=true;}
|
||||||
Some(Payload::JobOffer(_)|Payload::ExecutionPermit(_))=>anyhow::bail!("UNSUPPORTED_EXECUTION_CAPABILITY"),
|
self.journal.ack(&ack.message_id)?;jobs::ack(self.journal.connection_mut(),&ack.message_id)?;
|
||||||
|
},
|
||||||
|
Some(Payload::SyncResponse(response))=>{if self.apply_sync(generation,response).is_err(){self.close_gate();needs_sync=true;}sync_at=Instant::now();},
|
||||||
|
Some(Payload::JobOffer(offer))=>{
|
||||||
|
ensure!(self.config.enable_jobs,"UNSUPPORTED_EXECUTION_CAPABILITY");
|
||||||
|
let binding=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.clone();
|
||||||
|
let accepted=self.envelope(generation,Payload::JobAccepted(JobAccepted{job_id:offer.job_id.clone(),attempt_id:offer.attempt_id.clone(),job_payload_hash:offer.job_payload_hash.clone(),journal_proof:rmm_domain::jobs::hash(&offer.encode_to_vec())}))?;
|
||||||
|
let tx=self.journal.connection_mut().transaction()?;
|
||||||
|
let fresh=jobs::accept(&tx,&binding,&offer,rmm_agent_windows::actions::supported)?;
|
||||||
|
jobs::event(&tx,&accepted)?;tx.commit()?;needs_sync|=fresh;
|
||||||
|
},
|
||||||
|
Some(Payload::ExecutionPermit(permit))=>self.permit(generation,permit)?,
|
||||||
|
Some(Payload::CancelRequest(cancel))=>{
|
||||||
|
let row:Option<(Vec<u8>,String,String)>=self.journal.connection().query_row("SELECT offer,state,grant_id FROM job_attempts WHERE job=?1 AND attempt=?2",rusqlite::params![cancel.job_id,cancel.attempt_id],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
|
||||||
|
if let Some((bytes,state,grant))=row {
|
||||||
|
self.journal.connection().execute("UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2",rusqlite::params![cancel.job_id,cancel.attempt_id])?;
|
||||||
|
if let Some(running)=&self.running && running.offer.job_id==cancel.job_id && running.offer.attempt_id==cancel.attempt_id {running.cancel.store(true,Ordering::SeqCst);}
|
||||||
|
if state=="accepted" {self.record(generation,&JobOffer::decode(bytes.as_slice())?,&grant,jobs::no_start("cancelled","CANCELLED_BEFORE_START"))?;needs_sync=true;}
|
||||||
|
}
|
||||||
|
let ack=self.envelope(generation,Payload::Ack(Ack{message_id:message.message_id}))?;channel.send(&ack).await?;
|
||||||
|
},
|
||||||
_=>anyhow::bail!("UNSUPPORTED_SERVER_MESSAGE")
|
_=>anyhow::bail!("UNSUPPORTED_SERVER_MESSAGE")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if stop.load(Ordering::SeqCst) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if heartbeat.elapsed() >= heartbeat_after {
|
if heartbeat.elapsed() >= heartbeat_after {
|
||||||
let payload = Payload::Heartbeat(Heartbeat {
|
let payload = Payload::Heartbeat(Heartbeat {
|
||||||
instance_id: self.instance.clone(),
|
instance_id: self.instance.clone(),
|
||||||
@@ -235,13 +882,10 @@ impl Agent {
|
|||||||
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
|
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
|
||||||
}
|
}
|
||||||
if replay.elapsed() >= Duration::from_secs(5) {
|
if replay.elapsed() >= Duration::from_secs(5) {
|
||||||
for mut event in self.journal.events()? {
|
self.replay(&channel, generation).await?;
|
||||||
event.connection_generation = generation;
|
|
||||||
channel.send(&event).await?;
|
|
||||||
}
|
|
||||||
replay = Instant::now();
|
replay = Instant::now();
|
||||||
}
|
}
|
||||||
if inventory.elapsed() >= Duration::from_secs(86400) {
|
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
|
||||||
self.queue_inventory(generation)?;
|
self.queue_inventory(generation)?;
|
||||||
inventory = Instant::now();
|
inventory = Instant::now();
|
||||||
}
|
}
|
||||||
@@ -258,6 +902,11 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
let path = Path::new(&arguments[2]);
|
let path = Path::new(&arguments[2]);
|
||||||
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
||||||
let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?;
|
let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?;
|
||||||
|
native::require_local_service()?;
|
||||||
|
ensure!(
|
||||||
|
config.state_directory.is_absolute(),
|
||||||
|
"ABSOLUTE_STATE_REQUIRED"
|
||||||
|
);
|
||||||
native::private_path(&config.state_directory, true)?;
|
native::private_path(&config.state_directory, true)?;
|
||||||
ensure!(
|
ensure!(
|
||||||
crate::https_channel::server_name()? == config.server_name,
|
crate::https_channel::server_name()? == config.server_name,
|
||||||
@@ -266,7 +915,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
let ca = protected_read(&config.ca_file, 32768)?;
|
let ca = protected_read(&config.ca_file, 32768)?;
|
||||||
for child in fs::read_dir(&config.state_directory)? {
|
for child in fs::read_dir(&config.state_directory)? {
|
||||||
let child = child?;
|
let child = child?;
|
||||||
native::private_path(&child.path(), false)?;
|
native::private_path(&child.path(), child.file_type()?.is_dir())?;
|
||||||
}
|
}
|
||||||
let journal = Journal::open(&config.state_directory)?;
|
let journal = Journal::open(&config.state_directory)?;
|
||||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||||
@@ -275,8 +924,20 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
.build()?;
|
.build()?;
|
||||||
runtime.block_on(async move {
|
runtime.block_on(async move {
|
||||||
let identity = enrollment(&config, &ca).await?;
|
let identity = enrollment(&config, &ca).await?;
|
||||||
|
let mut journal=journal;
|
||||||
journal.pin_identity(&identity.agent_id)?;
|
journal.pin_identity(&identity.agent_id)?;
|
||||||
let boot = native::boot_id().await?;
|
let boot = native::boot_id().await?;
|
||||||
|
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
|
||||||
|
if let Some(binding)=&binding {
|
||||||
|
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
|
||||||
|
native::private_path(&config.state_directory.join("jobs"),true)?;
|
||||||
|
import_legacy_inventory(&mut journal)?;
|
||||||
|
}
|
||||||
|
ensure!(!config.enable_jobs || binding.is_some(),"ENABLED_JOBS_REQUIRE_BINDING");
|
||||||
|
let (ledger,ledger_file)=match &binding {Some(binding)=>{let (db,file)=open_ledger(&config.state_directory,binding)?;(Some(db),Some(file))},None=>(None,None)};
|
||||||
|
let clock=JobClock{native:Arc::new(rmm_agent_windows::clock::NativeClock::new()),enabled:config.enable_jobs};
|
||||||
|
let sync=if config.enable_jobs {binding.clone().map(reconcile::ClientSync::new)} else {None};
|
||||||
|
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
|
||||||
let mut agent = Agent {
|
let mut agent = Agent {
|
||||||
config,
|
config,
|
||||||
identity,
|
identity,
|
||||||
@@ -284,10 +945,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
journal,
|
journal,
|
||||||
boot,
|
boot,
|
||||||
instance: Uuid::new_v4().to_string(),
|
instance: Uuid::new_v4().to_string(),
|
||||||
started: Instant::now(),
|
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
|
||||||
|
prepared:false,fence:Arc::new(EffectFence::default()),completed_tx,completed_rx,running:None,deferred_permit:None,
|
||||||
};
|
};
|
||||||
|
agent.recover_interrupted()?;
|
||||||
let mut backoff = 1;
|
let mut backoff = 1;
|
||||||
while !stop.load(Ordering::SeqCst) {
|
while !stop.load(Ordering::SeqCst) || agent.running.is_some() {
|
||||||
|
if stop.load(Ordering::SeqCst) {
|
||||||
|
agent.close_gate();
|
||||||
|
if let Some(running)=&agent.running {running.cancel.store(true,Ordering::SeqCst);}
|
||||||
|
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
|
||||||
|
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
|
||||||
|
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
|
||||||
|
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
|
||||||
|
}
|
||||||
|
if agent.running.is_some() {tokio::select!{Some(completion)=agent.completed_rx.recv()=>agent.completed(0,completion)?,_=tokio::time::sleep(Duration::from_millis(250))=>{}}}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let _ = agent.session(stop).await;
|
let _ = agent.session(stop).await;
|
||||||
if start.elapsed() > Duration::from_secs(60) {
|
if start.elapsed() > Duration::from_secs(60) {
|
||||||
@@ -296,7 +970,15 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
|||||||
let delay = crate::https_channel::retry_delay(backoff);
|
let delay = crate::https_channel::retry_delay(backoff);
|
||||||
backoff = (backoff + 1).min(6);
|
backoff = (backoff + 1).min(6);
|
||||||
let until = Instant::now() + delay;
|
let until = Instant::now() + delay;
|
||||||
while !stop.load(Ordering::SeqCst) && Instant::now() < until {
|
while Instant::now() < until && (!stop.load(Ordering::SeqCst) || agent.running.is_some()) {
|
||||||
|
if stop.load(Ordering::SeqCst) {
|
||||||
|
agent.close_gate();if let Some(running)=&agent.running {running.cancel.store(true,Ordering::SeqCst);}
|
||||||
|
}
|
||||||
|
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
|
||||||
|
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
|
||||||
|
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
|
||||||
|
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
|
||||||
|
}
|
||||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,7 +989,7 @@ pub fn main() -> Result<()> {
|
|||||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
if args == ["--help"] {
|
if args == ["--help"] {
|
||||||
println!(
|
println!(
|
||||||
"Development Windows passive service. --service --config ABSOLUTE_PATH. No job executor or approval bypass."
|
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
|
||||||
);
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -341,3 +1023,90 @@ pub fn main() -> Result<()> {
|
|||||||
);
|
);
|
||||||
rmm_agent_windows::service::dispatch(service_run)
|
rmm_agent_windows::service::dispatch(service_run)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn old_passive_configuration_cannot_enable_jobs_or_read_the_clock() {
|
||||||
|
let config:Config=serde_json::from_value(serde_json::json!({"server_name":"example.invalid","connect_address":"127.0.0.1:443","ca_file":"C:/fixture/ca.pem","state_directory":"C:/fixture/state","enrollment_token_file":"C:/fixture/token","transport":"auto"})).unwrap();
|
||||||
|
assert!(!config.enable_jobs);
|
||||||
|
assert!(config.job_binding_file.is_none());
|
||||||
|
let clock = JobClock {
|
||||||
|
native: Arc::new(rmm_agent_windows::clock::NativeClock::new()),
|
||||||
|
enabled: config.enable_jobs,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
clock.now().unwrap_err().to_string(),
|
||||||
|
"WINDOWS_JOBS_NOT_ENABLED"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn legacy_inventory_keeps_original_bytes_until_concrete_core_ack() {
|
||||||
|
let directory =
|
||||||
|
std::env::temp_dir().join(format!("windows-runtime-import-{}", Uuid::new_v4()));
|
||||||
|
fs::create_dir(&directory).unwrap();
|
||||||
|
let mut journal = Journal::open(&directory).unwrap();
|
||||||
|
journal.pin_identity("retained").unwrap();
|
||||||
|
let sequence = journal.next_sequence().unwrap();
|
||||||
|
let envelope = Envelope {
|
||||||
|
message_id: Uuid::new_v4().to_string(),
|
||||||
|
sequence,
|
||||||
|
payload: Some(Payload::InventorySnapshot(InventorySnapshot::default())),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
journal.save(&envelope).unwrap();
|
||||||
|
let mut original = envelope.encode_to_vec();
|
||||||
|
original.extend([0xf8, 0x07, 0x01]); // Unknown additive protobuf field must remain byte-exact.
|
||||||
|
journal
|
||||||
|
.connection()
|
||||||
|
.execute(
|
||||||
|
"UPDATE events SET payload=?1 WHERE id=?2",
|
||||||
|
rusqlite::params![&original, &envelope.message_id],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
import_legacy_inventory(&mut journal).unwrap();
|
||||||
|
for table in ["events", "job_events"] {
|
||||||
|
let bytes: Vec<u8> = journal
|
||||||
|
.connection()
|
||||||
|
.query_row(
|
||||||
|
&format!("SELECT payload FROM {table} WHERE id=?1"),
|
||||||
|
[&envelope.message_id],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(bytes, original);
|
||||||
|
}
|
||||||
|
jobs::ack(journal.connection_mut(), &Uuid::new_v4().to_string()).unwrap();
|
||||||
|
assert_eq!(journal.count().unwrap(), 1);
|
||||||
|
import_legacy_inventory(&mut journal).unwrap(); // Exact same-ID copy is idempotent.
|
||||||
|
assert_eq!(journal.next_sequence().unwrap(), sequence + 1);
|
||||||
|
jobs::ack(journal.connection_mut(), &envelope.message_id).unwrap();
|
||||||
|
assert_eq!(journal.count().unwrap(), 0);
|
||||||
|
assert!(jobs::events(journal.connection()).unwrap().is_empty());
|
||||||
|
drop(journal);
|
||||||
|
fs::remove_dir_all(directory).unwrap();
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn worker_fence_requires_same_generation_and_entire_clock_interval() {
|
||||||
|
struct Clock(chrono::DateTime<Utc>);
|
||||||
|
impl SyncClock for Clock {
|
||||||
|
fn now(&self) -> Result<chrono::DateTime<Utc>> {
|
||||||
|
Ok(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = Utc::now();
|
||||||
|
let fence = EffectFence::default();
|
||||||
|
fence.deadline.store(
|
||||||
|
(now + chrono::Duration::seconds(3)).timestamp_millis(),
|
||||||
|
Ordering::SeqCst,
|
||||||
|
);
|
||||||
|
assert!(!fence.allows(1, &Clock(now)));
|
||||||
|
fence.generation.store(1, Ordering::SeqCst);
|
||||||
|
assert!(fence.allows(1, &Clock(now)));
|
||||||
|
assert!(!fence.allows(2, &Clock(now)));
|
||||||
|
assert!(!fence.allows(1, &Clock(now + chrono::Duration::seconds(1))));
|
||||||
|
fence.close();
|
||||||
|
assert!(!fence.allows(1, &Clock(now)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ def powershell(script, payload=None, timeout=60, remote_signed=False):
|
|||||||
UPLOAD = r'''
|
UPLOAD = r'''
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
||||||
if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'}
|
if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe)$') {throw 'Artifact allowlist'}
|
||||||
$root='C:\ProgramData\RustDiscoveryBootstrap'
|
$root='C:\ProgramData\RustDiscoveryBootstrap'
|
||||||
if (!(Test-Path -LiteralPath $root)) {
|
if (!(Test-Path -LiteralPath $root)) {
|
||||||
New-Item -ItemType Directory -Path $root | Out-Null
|
New-Item -ItemType Directory -Path $root | Out-Null
|
||||||
@@ -68,7 +68,7 @@ if (Test-Path -LiteralPath $path) {throw 'Artifact already exists'}
|
|||||||
VERIFY_UPLOAD = r'''
|
VERIFY_UPLOAD = r'''
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
||||||
if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'}
|
if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe)$') {throw 'Artifact allowlist'}
|
||||||
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name
|
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name
|
||||||
$hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
|
$hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||||
if ($hash -cne $p.sha256) {throw 'Artifact hash'}
|
if ($hash -cne $p.sha256) {throw 'Artifact hash'}
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Read-only LocalService W32Time readiness bootstrap; no RMM jobs.
|
||||||
|
|
||||||
|
A lost SSH reply is resumed using readback --id, never by repeating start.
|
||||||
|
The temporary service is separate from the permanent enrolled Windows agent.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import client_bootstrap as cb
|
||||||
|
|
||||||
|
STATE = cb.EVIDENCE / 'clock-readiness'
|
||||||
|
ROOT = r'C:\ProgramData\RustDiscoveryClockReadiness'
|
||||||
|
SERVICE = 'RmmWindowsClockReadiness'
|
||||||
|
|
||||||
|
PREPARE = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if($p.sha -notmatch '^[a-f0-9]{64}$' -or $p.name -notin @('WindowsClockReadiness.exe','ClockReadiness.ps1')){throw 'Fixed artifact'}
|
||||||
|
$root='C:\ProgramData\RustDiscoveryClockReadiness'
|
||||||
|
function CheckPrivate($path){
|
||||||
|
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
if($owner -notin @('S-1-5-18','S-1-5-32-544') -or $acl.Access.Count -eq 0){throw 'Artifact owner/DACL'}
|
||||||
|
foreach($ace in $acl.Access){
|
||||||
|
$sid=$ace.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
if($ace.AccessControlType -ne 'Allow' -or $sid -notin @('S-1-5-18','S-1-5-32-544','S-1-5-19')){throw 'Artifact broad ACL'}
|
||||||
|
if($sid -eq 'S-1-5-19' -and ([int64]$ace.FileSystemRights -band (-bnot ([int64][Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [int64][Security.AccessControl.FileSystemRights]::Synchronize)))){throw 'Artifact writable by service account'}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!(Test-Path -LiteralPath $root)){
|
||||||
|
New-Item -ItemType Directory -Path $root|Out-Null
|
||||||
|
$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false)
|
||||||
|
foreach($sid in @('S-1-5-18','S-1-5-32-544','S-1-5-19')){
|
||||||
|
$rights=if($sid -eq 'S-1-5-19'){'ReadAndExecute'}else{'FullControl'}
|
||||||
|
$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,'ContainerInherit,ObjectInherit','None','Allow')))
|
||||||
|
}
|
||||||
|
$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $root -AclObject $a
|
||||||
|
}
|
||||||
|
if((Get-Item -LiteralPath $root).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Root reparse'}
|
||||||
|
CheckPrivate $root
|
||||||
|
$dir=Join-Path $root $p.sha
|
||||||
|
if(!(Test-Path -LiteralPath $dir)){New-Item -ItemType Directory -Path $dir|Out-Null}
|
||||||
|
if((Get-Item -LiteralPath $dir).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Artifact reparse'}
|
||||||
|
CheckPrivate $dir
|
||||||
|
$file=Join-Path $dir $p.name
|
||||||
|
$exists=Test-Path -LiteralPath $file
|
||||||
|
if($exists -and ((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'File reparse'}
|
||||||
|
if($exists){CheckPrivate $file}
|
||||||
|
if($exists -and (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha){throw 'Artifact immutable'}
|
||||||
|
[pscustomobject]@{exists=$exists;sha=$p.sha}|ConvertTo-Json -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
SCRIPT = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
$id=[guid]::ParseExact($p.id,'D').ToString()
|
||||||
|
if($id -cne $p.id -or $p.binary -notmatch '^[a-f0-9]{64}$' -or $p.source -notmatch '^[a-f0-9]{64}$' -or $p.action -notin @('start','readback')){throw 'Fixed request'}
|
||||||
|
$root='C:\ProgramData\RustDiscoveryClockReadiness';$name='RmmWindowsClockReadiness'
|
||||||
|
$case=Join-Path $root $id;$intent=Join-Path $case 'intent.json';$result=Join-Path $case 'result.json'
|
||||||
|
$exe=Join-Path (Join-Path $root $p.binary) 'WindowsClockReadiness.exe'
|
||||||
|
$source=Join-Path (Join-Path $root $p.source) 'ClockReadiness.ps1'
|
||||||
|
foreach($file in @($exe,$source)){
|
||||||
|
if((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Reparse'}
|
||||||
|
}
|
||||||
|
if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.binary -or (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Qualified source and binary'}
|
||||||
|
$command='"'+$exe+'" --service '+$id
|
||||||
|
function PrivateFile($path){
|
||||||
|
$a=New-Object Security.AccessControl.FileSecurity;$a.SetAccessRuleProtection($true,$false)
|
||||||
|
foreach($sid in @('S-1-5-18','S-1-5-32-544')){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))}
|
||||||
|
$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $path -AclObject $a
|
||||||
|
}
|
||||||
|
function WriteNew($path,$data){
|
||||||
|
$bytes=[Text.Encoding]::UTF8.GetBytes(($data|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','None')
|
||||||
|
try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};PrivateFile $path
|
||||||
|
}
|
||||||
|
if($p.action -eq 'start'){
|
||||||
|
if((Test-Path -LiteralPath $case) -or (Get-Service -Name $name -ErrorAction SilentlyContinue)){throw 'Use retained case readback; never repeat start'}
|
||||||
|
New-Item -ItemType Directory -Path $case|Out-Null
|
||||||
|
WriteNew $intent ([ordered]@{id=$id;binary=$p.binary;source=$p.source;command=$command;service=$name;no_jobs=$true})
|
||||||
|
New-Service -Name $name -BinaryPathName $command -StartupType Manual -Credential (New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString)))|Out-Null
|
||||||
|
& "$env:WINDIR\System32\sc.exe" sidtype $name unrestricted|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness service SID'}
|
||||||
|
$sid=(New-Object Security.Principal.NTAccount('NT SERVICE\'+$name)).Translate([Security.Principal.SecurityIdentifier])
|
||||||
|
$a=Get-Acl -LiteralPath $case;$a.SetAccessRuleProtection($true,$true)
|
||||||
|
$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid,'ReadAndExecute,Write','ContainerInherit,ObjectInherit','None','Allow')));Set-Acl -LiteralPath $case -AclObject $a
|
||||||
|
Start-Service -Name $name
|
||||||
|
}
|
||||||
|
if(!(Test-Path -LiteralPath $intent)){throw 'Missing durable intent'}
|
||||||
|
$i=Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json
|
||||||
|
if($i.id -cne $id -or $i.binary -cne $p.binary -or $i.source -cne $p.source -or $i.command -cne $command -or $i.service -cne $name){throw 'Retained intent mismatch'}
|
||||||
|
$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'"
|
||||||
|
if($service -and ($service.PathName -cne $command -or $service.StartName -notin @('NT AUTHORITY\LocalService','NT AUTHORITY\Local Service'))){throw 'Service owner/configuration mismatch'}
|
||||||
|
$deadline=[DateTime]::UtcNow.AddSeconds(25)
|
||||||
|
while($service -and $service.State -ne 'Stopped' -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Milliseconds 250;$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'"}
|
||||||
|
if($service -and $service.State -ne 'Stopped'){throw 'Readiness still active; retain case and readback'}
|
||||||
|
$token=$null;$tokenPath=Join-Path $case 'token.json'
|
||||||
|
if(Test-Path -LiteralPath $tokenPath){
|
||||||
|
if((Get-Item -LiteralPath $tokenPath).Length -gt 1024 -or ((Get-Item -LiteralPath $tokenPath).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Token report bound'}
|
||||||
|
$token=Get-Content -LiteralPath $tokenPath -Raw|ConvertFrom-Json
|
||||||
|
if($token.user_sid -cne 'S-1-5-19' -or $token.administrator_member -ne $false -or $token.system_user -ne $false){throw 'Token report identity'}
|
||||||
|
PrivateFile $tokenPath
|
||||||
|
}
|
||||||
|
$data=$null
|
||||||
|
if(Test-Path -LiteralPath $result){
|
||||||
|
if((Get-Item -LiteralPath $result).Length -gt 16384 -or ((Get-Item -LiteralPath $result).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Result bound'}
|
||||||
|
$data=Get-Content -LiteralPath $result -Raw|ConvertFrom-Json
|
||||||
|
if($data.case_id -cne $id -or $data.token_sid -cne 'S-1-5-19' -or $data.token.user_sid -cne 'S-1-5-19' -or $data.token.administrator_member -ne $false -or $data.token.system_user -ne $false -or $data.token.elevation_flag -notin @(0,1) -or $data.token.elevation_type -notin @(1,2,3) -or $data.elevated -ne ($data.token.elevation_flag -ne 0) -or $data.service_name -cne $name -or $data.read_only -ne $true){throw 'Actual LocalService report'}
|
||||||
|
PrivateFile $result
|
||||||
|
}
|
||||||
|
if($service){
|
||||||
|
$cleanup=Join-Path $case 'cleanup-intent.json'
|
||||||
|
if(!(Test-Path -LiteralPath $cleanup)){WriteNew $cleanup ([ordered]@{id=$id;command=$command;service=$name;remove_only_own_stopped_service=$true})}
|
||||||
|
else{$c=Get-Content -LiteralPath $cleanup -Raw|ConvertFrom-Json;if($c.id -cne $id -or $c.command -cne $command -or $c.service -cne $name){throw 'Cleanup intent mismatch'}}
|
||||||
|
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness cleanup'}
|
||||||
|
}
|
||||||
|
[pscustomobject]@{id=$id;native_report=$data;partial_token=$token;service_removed=!(Get-Service -Name $name -ErrorAction SilentlyContinue);service_exit_code=if($service){$service.ExitCode}else{$null};service_specific_exit_code=if($service){$service.ServiceSpecificExitCode}else{$null};no_jobs=$true;no_clock_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 15 -Compress
|
||||||
|
'''
|
||||||
|
LAUNCH = r'''$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||||
|
if($p.source -notmatch '^[a-f0-9]{64}$'){throw 'Source hash'}
|
||||||
|
$file='C:\ProgramData\RustDiscoveryClockReadiness\'+$p.source+'\ClockReadiness.ps1'
|
||||||
|
if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Source changed'}
|
||||||
|
$inputJson=$p|ConvertTo-Json -Compress
|
||||||
|
$raw=$inputJson|& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $file
|
||||||
|
if($LASTEXITCODE -ne 0){throw 'Readiness source failed'}
|
||||||
|
$raw
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def save(folder, name, value):
|
||||||
|
fd = os.open(folder / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as out:
|
||||||
|
json.dump(value, out, indent=2)
|
||||||
|
out.flush()
|
||||||
|
os.fsync(out.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def stage(path, name):
|
||||||
|
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
value = cb.powershell(PREPARE, dict(sha=digest, name=name))
|
||||||
|
if not value['exists']:
|
||||||
|
access = cb.contract.protected_json(cb.ROOT / 'credentials/windows-dev-access.json')
|
||||||
|
prefix = access['ssh_prefix']
|
||||||
|
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
|
||||||
|
remote = '/C:/ProgramData/RustDiscoveryClockReadiness/' + digest + '/' + name
|
||||||
|
batch = 'put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(remote) + '\n'
|
||||||
|
result = subprocess.run(args, input=batch.encode(), capture_output=True, timeout=120)
|
||||||
|
if result.returncode:
|
||||||
|
raise RuntimeError('CLOCK_ARTIFACT_UPLOAD_FAILED')
|
||||||
|
if not cb.powershell(PREPARE, dict(sha=digest, name=name))['exists']:
|
||||||
|
raise RuntimeError('CLOCK_ARTIFACT_READBACK_FAILED')
|
||||||
|
return digest
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('action', choices=('start', 'readback'))
|
||||||
|
parser.add_argument('--binary', type=Path)
|
||||||
|
parser.add_argument('--id')
|
||||||
|
args = parser.parse_args()
|
||||||
|
os.umask(0o077)
|
||||||
|
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
if args.action == 'start':
|
||||||
|
if args.id or not args.binary or not args.binary.is_file():
|
||||||
|
raise RuntimeError('NEW_CASE_BINARY_REQUIRED')
|
||||||
|
ident = str(uuid.uuid4())
|
||||||
|
folder = STATE / ident
|
||||||
|
folder.mkdir(mode=0o700)
|
||||||
|
source_path = folder / 'ClockReadiness.ps1'
|
||||||
|
fd = os.open(source_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as out:
|
||||||
|
out.write(SCRIPT)
|
||||||
|
intent = dict(id=ident, binary=hashlib.sha256(args.binary.read_bytes()).hexdigest(), source=hashlib.sha256(SCRIPT.encode()).hexdigest(), no_jobs=True)
|
||||||
|
save(folder, 'intent.json', intent)
|
||||||
|
print('Retained readiness case ' + ident, flush=True)
|
||||||
|
stage(args.binary, 'WindowsClockReadiness.exe')
|
||||||
|
stage(source_path, 'ClockReadiness.ps1')
|
||||||
|
save(folder, 'start-intent.json', dict(**intent, action='start'))
|
||||||
|
else:
|
||||||
|
if not args.id or args.binary:
|
||||||
|
raise RuntimeError('READBACK_SAME_CASE_REQUIRED')
|
||||||
|
ident = str(uuid.UUID(args.id))
|
||||||
|
folder = STATE / ident
|
||||||
|
intent = cb.contract.protected_json(folder / 'intent.json')
|
||||||
|
if intent['source'] != hashlib.sha256(SCRIPT.encode()).hexdigest():
|
||||||
|
raise RuntimeError('QUALIFIED_SOURCE_CHANGED')
|
||||||
|
result = cb.powershell(LAUNCH, dict(**intent, action=args.action), timeout=60)
|
||||||
|
save(folder, 'readback-' + str(uuid.uuid4()) + '.json', result)
|
||||||
|
report = result['native_report']
|
||||||
|
if not result['service_removed'] or not report or len(report['samples']) != 2:
|
||||||
|
raise RuntimeError('READINESS_NATIVE_REPORT_INCOMPLETE')
|
||||||
|
diagnostic = all(s['trusted'] for s in report['samples'])
|
||||||
|
qualified = all(s.get('adapter_qualified') is True for s in report['samples'])
|
||||||
|
ready = diagnostic and qualified
|
||||||
|
completed = dict(native_execution_verified=True, diagnostic_status_ready=diagnostic, adapter_qualified=qualified, clock_ready=ready, **result)
|
||||||
|
if not (folder / 'result.json').exists():
|
||||||
|
save(folder, 'result.json', completed)
|
||||||
|
elif cb.contract.protected_json(folder / 'result.json')['native_report'] != report:
|
||||||
|
raise RuntimeError('IMMUTABLE_NATIVE_REPORT_CHANGED')
|
||||||
|
print(json.dumps(dict(id=ident,native_execution_verified=True,diagnostic_status_ready=diagnostic,adapter_qualified=qualified,clock_ready=ready,reasons=[s['reason'] for s in report['samples']],rpc_codes=[s['rpc_code'] for s in report['samples']],token=report.get('token'),service_removed=True,no_jobs=True)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Qualified passive-only Windows runtime replacement, never a Windows RMM job.
|
||||||
|
|
||||||
|
Native test qualification and binary replacement are separate explicit phases.
|
||||||
|
Only the parent/orchestrator executes native phases after source review.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import client_bootstrap as cb
|
||||||
|
import activate_auto_transport as activation
|
||||||
|
import auto_transport_acceptance as auto
|
||||||
|
|
||||||
|
base=auto.base
|
||||||
|
require=cb.contract.require
|
||||||
|
STATE=cb.EVIDENCE/'runtime-upgrade'
|
||||||
|
TARGET='x86_64-pc-windows-gnu'
|
||||||
|
IMAGE='rust-discovery-windows-clock-full:local'
|
||||||
|
ACTIVATION='422562e8-18eb-4865-977d-ab2af65f510b'
|
||||||
|
|
||||||
|
TESTS=r'''
|
||||||
|
$ErrorActionPreference='Stop'
|
||||||
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
||||||
|
if ($p.name -notin @('windows-tests-lib.exe','windows-tests-bin.exe') -or $p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed native test artifact'}
|
||||||
|
$binary='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name
|
||||||
|
if ((Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Exact native test artifact hash'}
|
||||||
|
function Run-Own([string]$arguments) {
|
||||||
|
$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$binary;$si.Arguments=$arguments
|
||||||
|
$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true
|
||||||
|
$proc=New-Object Diagnostics.Process;$proc.StartInfo=$si
|
||||||
|
if (!$proc.Start()) {throw 'Native selftest start'}
|
||||||
|
try {
|
||||||
|
$stdout=$proc.StandardOutput.ReadToEndAsync();$stderr=$proc.StandardError.ReadToEndAsync()
|
||||||
|
if (!$proc.WaitForExit(120000)) {$proc.Kill();throw 'Native selftest timeout'}
|
||||||
|
$out=$stdout.Result;$err=$stderr.Result
|
||||||
|
if ($out.Length -gt 32768 -or $err.Length -gt 32768) {throw 'Bounded native selftest output'}
|
||||||
|
return [pscustomobject]@{exit_code=$proc.ExitCode;stdout=$out;stderr=$err}
|
||||||
|
} finally {$proc.Dispose()}
|
||||||
|
}
|
||||||
|
$list=Run-Own '--list --format terse'
|
||||||
|
if ($list.exit_code -ne 0) {throw 'Native selftest listing failed'}
|
||||||
|
$result=Run-Own '--test-threads=1'
|
||||||
|
[pscustomobject]@{listed=$list;result=$result;native_windows=$true;execution_context='bootstrap_administrator_unit_tests';rmm_jobs_created=$false;clock_service_changed=$false} | ConvertTo-Json -Depth 6 -Compress
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
UPGRADE=r'''
|
||||||
|
$ErrorActionPreference='Stop'
|
||||||
|
$p=$global:RmmRuntimePayload
|
||||||
|
if ($null -eq $p -or [string]([guid]$p.id) -cne $p.id -or $p.action -notin @('state','enter','finish','rollback')) {throw 'Fixed passive runtime intent'}
|
||||||
|
foreach($n in @('old_sha256','new_sha256','probe_sha256','config_sha256')) {if ($p.$n -notmatch '^[0-9a-f]{64}$') {throw 'Qualified hash binding'}}
|
||||||
|
if ($p.old_sha256 -cne '31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37' -or $p.new_sha256 -ceq $p.old_sha256) {throw 'Known old passive runtime'}
|
||||||
|
$name='RmmDiscoveryWindows';$root='C:\ProgramData\RustDiscovery';$state=Join-Path $root 'state';$config=Join-Path $root 'config.json'
|
||||||
|
$binary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe'
|
||||||
|
$folder='C:\ProgramData\RustDiscoveryBootstrap\runtime-'+$p.id
|
||||||
|
$active='C:\ProgramData\RustDiscoveryBootstrap\runtime-active-intent.json'
|
||||||
|
$uploaded='C:\ProgramData\RustDiscoveryBootstrap\'+$p.new_sha256+'\rmm-agent-windows.exe'
|
||||||
|
$probe='C:\ProgramData\RustDiscoveryBootstrap\'+$p.probe_sha256+'\RuntimeStateProbe.exe'
|
||||||
|
$sid=(New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
$allowed=@('S-1-5-18','S-1-5-32-544',$sid)
|
||||||
|
function Check([string]$path,[bool]$directory) {
|
||||||
|
$item=Get-Item -LiteralPath $path -Force
|
||||||
|
if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Fixed regular path'}
|
||||||
|
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
||||||
|
if ($owner -notin $allowed -and ($directory -or $owner -cne 'S-1-5-19')) {throw 'Protected owner'}
|
||||||
|
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if (!$rules.Count) {throw 'Empty DACL'}
|
||||||
|
foreach($r in $rules) {if ($r.AccessControlType -ne 'Allow' -or $r.IdentityReference.Value -notin $allowed) {throw 'Unexpected DACL'}}
|
||||||
|
}
|
||||||
|
function Hash-Bytes([byte[]]$bytes) {
|
||||||
|
$hash=[Security.Cryptography.SHA256]::Create()
|
||||||
|
try {return ([BitConverter]::ToString($hash.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()} finally {$hash.Dispose()}
|
||||||
|
}
|
||||||
|
function Hash([string]$path) {Check $path $false;return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||||
|
function Acl-Hash([string]$path) {return Hash-Bytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))}
|
||||||
|
function Write-New([string]$path,$value) {
|
||||||
|
$bytes=[Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Depth 24 -Compress))
|
||||||
|
$file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
|
||||||
|
try {$file.Write($bytes,0,$bytes.Length);$file.Flush($true)} finally {$file.Dispose()}
|
||||||
|
}
|
||||||
|
function Probe {
|
||||||
|
if ((Hash $probe) -cne $p.probe_sha256) {throw 'Exact readonly witness artifact'}
|
||||||
|
$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$probe;$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true
|
||||||
|
$proc=New-Object Diagnostics.Process;$proc.StartInfo=$si
|
||||||
|
if (!$proc.Start()) {throw 'Readonly witness start'}
|
||||||
|
try {
|
||||||
|
$stdout=$proc.StandardOutput.ReadToEndAsync();$stderr=$proc.StandardError.ReadToEndAsync()
|
||||||
|
if (!$proc.WaitForExit(20000)) {$proc.Kill();throw 'Readonly witness timeout'}
|
||||||
|
if ($proc.ExitCode -ne 0 -or $stdout.Result.Length -gt 32768 -or $stderr.Result.Length) {throw 'Readonly witness refusal'}
|
||||||
|
return ($stdout.Result | ConvertFrom-Json)
|
||||||
|
} finally {$proc.Dispose()}
|
||||||
|
}
|
||||||
|
function Snapshot([string]$expected) {
|
||||||
|
foreach($dir in @('C:\Program Files\RustDiscovery',$root,$state)) {Check $dir $true}
|
||||||
|
Check $config $false
|
||||||
|
if ((Get-Item -LiteralPath $config).Length -gt 32768 -or (Hash $config) -cne $p.config_sha256) {throw 'Exact immutable auto configuration'}
|
||||||
|
$cfg=Get-Content -LiteralPath $config -Raw | ConvertFrom-Json
|
||||||
|
if ((($cfg.PSObject.Properties.Name|Sort-Object)-join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport' -or $cfg.transport -cne 'auto' -or $cfg.server_name -cne 'discovery.ease-technologies.de' -or $cfg.state_directory -cne $state -or $cfg.ca_file -cne (Join-Path $root 'server-ca.pem') -or $cfg.enrollment_token_file -cne (Join-Path $state 'enrollment.token')) {throw 'Original six-field passive configuration'}
|
||||||
|
if ((Test-Path -LiteralPath $cfg.enrollment_token_file) -or (Test-Path -LiteralPath (Join-Path $root 'binding.json')) -or (Test-Path -LiteralPath (Join-Path $state 'consumption.sqlite')) -or (Test-Path -LiteralPath (Join-Path $state 'jobs'))) {throw 'Passive only: no token binding ledger or jobs directory'}
|
||||||
|
$svc=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" -OperationTimeoutSec 10
|
||||||
|
$command='"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"'
|
||||||
|
if ($svc.PathName -cne $command -or $svc.StartName -cne 'NT AUTHORITY\LocalService' -or $svc.StartMode -cne 'Auto') {throw 'Unchanged LocalService deployment'}
|
||||||
|
$owner=$null
|
||||||
|
if ($svc.State -eq 'Running') {
|
||||||
|
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$svc.ProcessId) -OperationTimeoutSec 10
|
||||||
|
$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid
|
||||||
|
if ($owner -cne 'S-1-5-19') {throw 'Actual LocalService identity'}
|
||||||
|
}
|
||||||
|
$identity=Get-Content -LiteralPath (Join-Path $state 'identity.json') -Raw | ConvertFrom-Json
|
||||||
|
if ($identity.agent_id -cne '63ea15b2-0643-403d-b5b4-cba1288dbea3' -or $identity.asset_id -cne 'a176520e-8a91-4e93-a78b-8e7620f430e0') {throw 'Original registered identity'}
|
||||||
|
if ((Hash $binary) -cne $expected) {throw 'Pinned actual binary'}
|
||||||
|
$public=[ordered]@{};$acls=[ordered]@{}
|
||||||
|
foreach($pair in @(@('ca',$cfg.ca_file),@('identity',(Join-Path $state 'identity.json')),@('certificate',(Join-Path $state 'device.pem')))) {$public[$pair[0]]=Hash $pair[1];$acls[$pair[0]]=Acl-Hash $pair[1]}
|
||||||
|
$key=Join-Path $state 'device.key';Check $key $false;$item=Get-Item -LiteralPath $key
|
||||||
|
$acls.private_key=Acl-Hash $key
|
||||||
|
return [pscustomobject]@{agent_id=$identity.agent_id;asset_id=$identity.asset_id;binary_sha256=$expected;binary_acl_sha256=(Acl-Hash $binary);config_sha256=(Hash $config);config_acl_sha256=(Acl-Hash $config);public_hashes=$public;identity_acls=$acls;private_key_metadata=[ordered]@{length=$item.Length;creation_ticks=$item.CreationTimeUtc.Ticks;last_write_ticks=$item.LastWriteTimeUtc.Ticks};private_key_read=$false;service=[ordered]@{state=$svc.State;start_name=$svc.StartName;start_mode=$svc.StartMode;path=$svc.PathName;process_id=$svc.ProcessId;owner_sid=$owner};journal=(Probe)}
|
||||||
|
}
|
||||||
|
function Preserved($before,$after,[bool]$frozen) {
|
||||||
|
foreach($field in @('agent_id','asset_id','config_sha256','config_acl_sha256','binary_acl_sha256')) {if ($before.$field -cne $after.$field) {throw 'Preserved deployment metadata'}}
|
||||||
|
foreach($field in @('public_hashes','identity_acls','private_key_metadata')) {if (($before.$field|ConvertTo-Json -Compress) -cne ($after.$field|ConvertTo-Json -Compress)) {throw 'Preserved identity metadata'}}
|
||||||
|
foreach($field in @('database_file_id','database_creation')) {if (($before.journal.$field|ConvertTo-Json -Compress) -cne ($after.journal.$field|ConvertTo-Json -Compress)) {throw 'Original database file identity'}}
|
||||||
|
if ($after.journal.integrity -cne 'ok' -or $after.journal.sequence -lt $before.journal.sequence -or $after.journal.identity_sha256 -cne $before.journal.identity_sha256 -or $after.journal.consumption_exists -or $after.journal.jobs_directory_exists) {throw 'Preserved passive journal'}
|
||||||
|
if ($frozen) {foreach($field in @('metadata_sha256','events_sha256')) {if ($before.journal.$field -cne $after.journal.$field) {throw 'Stopped original tables changed'}}}
|
||||||
|
foreach($row in $before.journal.schema) {
|
||||||
|
$found=$false
|
||||||
|
foreach($candidate in $after.journal.schema) {
|
||||||
|
if ($candidate[0] -ceq $row[0] -and $candidate[1] -ceq $row[1]) {
|
||||||
|
if ($found -or $candidate[2] -cne $row[2]) {throw 'Original schema changed'}
|
||||||
|
$found=$true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!$found) {throw 'Original schema missing'}
|
||||||
|
}
|
||||||
|
foreach($field in $after.journal.core_counts.PSObject.Properties) {if ($field.Value -ne 0) {throw 'Unexpected job or Sync rows'}}
|
||||||
|
}
|
||||||
|
function New-Intent {
|
||||||
|
if ((Test-Path -LiteralPath $folder) -or (Test-Path -LiteralPath $active)) {throw 'Existing native runtime intent: read finish, never repeat enter'}
|
||||||
|
New-Item -ItemType Directory -Path $folder | Out-Null
|
||||||
|
$acl=New-Object Security.AccessControl.DirectorySecurity;$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
|
||||||
|
foreach($identity in @('S-1-5-18','S-1-5-32-544')) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($identity)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))}
|
||||||
|
Set-Acl -LiteralPath $folder -AclObject $acl
|
||||||
|
}
|
||||||
|
function Read-Intent {
|
||||||
|
Check $folder $true
|
||||||
|
$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw | ConvertFrom-Json
|
||||||
|
foreach($field in @('id','old_sha256','new_sha256','probe_sha256','config_sha256')) {if ($intent.payload.$field -cne $p.$field) {throw 'Exact existing native intent'}}
|
||||||
|
return $intent
|
||||||
|
}
|
||||||
|
function Stop-Own {Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20))}
|
||||||
|
function Start-Own {Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))}
|
||||||
|
if ($p.action -eq 'state') {Snapshot $p.old_sha256|ConvertTo-Json -Depth 24 -Compress;exit 0}
|
||||||
|
if ($p.action -eq 'finish') {
|
||||||
|
$intent=Read-Intent
|
||||||
|
$restored=Test-Path -LiteralPath (Join-Path $folder 'rollback-intent.json')
|
||||||
|
$expected=$p.new_sha256;if ($restored) {$expected=$p.old_sha256}
|
||||||
|
$after=Snapshot $expected;Preserved $intent.before $after $false
|
||||||
|
if ($after.service.state -cne 'Running') {throw 'Selected runtime not running; no repeated start'}
|
||||||
|
[pscustomobject]@{read_only=$true;completed=$true;restored=$restored;id=$p.id;native=$after;original=$intent.before;stop_receipt=(Test-Path -LiteralPath (Join-Path $folder 'stopped.json'));entered_receipt=(Test-Path -LiteralPath (Join-Path $folder 'entered.json'));no_jobs=$true;no_clock_change=$true;no_reboot=$true} | ConvertTo-Json -Depth 24 -Compress;exit 0
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if ($p.action -eq 'enter') {
|
||||||
|
$before=Snapshot $p.old_sha256
|
||||||
|
if ($before.service.state -cne 'Running' -or $before.journal.pending_inventory_events -ne 0) {throw 'Settled original runtime required'}
|
||||||
|
if ((Hash $uploaded) -cne $p.new_sha256) {throw 'New qualified binary upload'}
|
||||||
|
New-Intent
|
||||||
|
$intent=[pscustomobject]@{payload=$p;before=$before;binary_sddl=(Get-Acl -LiteralPath $binary).Sddl}
|
||||||
|
Write-New $active @{id=$p.id;old_sha256=$p.old_sha256;new_sha256=$p.new_sha256;no_jobs=$true}
|
||||||
|
Write-New (Join-Path $folder 'intent.json') $intent
|
||||||
|
Write-New (Join-Path $folder 'stop-attempt.json') @{stop_once=$true;no_jobs=$true}
|
||||||
|
Stop-Own
|
||||||
|
$stopped=Snapshot $p.old_sha256;Preserved $before $stopped $false
|
||||||
|
if ($stopped.journal.pending_inventory_events -ne 0) {throw 'Unacknowledged legacy inventory: preserve and inspect'}
|
||||||
|
Write-New (Join-Path $folder 'stopped.json') $stopped
|
||||||
|
$candidate=Join-Path $folder 'candidate.exe';[IO.File]::Copy($uploaded,$candidate,$false)
|
||||||
|
if ((Hash $candidate) -cne $p.new_sha256) {throw 'Exact staged candidate'}
|
||||||
|
[IO.File]::Replace($candidate,$binary,(Join-Path $folder 'original-binary.exe'))
|
||||||
|
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($intent.binary_sddl);Set-Acl -LiteralPath $binary -AclObject $acl
|
||||||
|
if ((Hash (Join-Path $folder 'original-binary.exe')) -cne $p.old_sha256) {throw 'Versioned original binary retained'}
|
||||||
|
$swapped=Snapshot $p.new_sha256;Preserved $stopped $swapped $true
|
||||||
|
Write-New (Join-Path $folder 'swapped.json') $swapped
|
||||||
|
Write-New (Join-Path $folder 'start-attempt.json') @{start_once=$true;no_jobs=$true}
|
||||||
|
Start-Own
|
||||||
|
$after=Snapshot $p.new_sha256;Preserved $before $after $false
|
||||||
|
if ($after.service.state -cne 'Running') {throw 'New runtime stopped after start; no automatic retry'}
|
||||||
|
Write-New (Join-Path $folder 'entered.json') $after
|
||||||
|
[pscustomobject]@{entered=$true;id=$p.id;native=$after;no_jobs=$true;no_clock_change=$true;no_reboot=$true}|ConvertTo-Json -Depth 24 -Compress
|
||||||
|
} else {
|
||||||
|
$intent=Read-Intent
|
||||||
|
if (Test-Path -LiteralPath (Join-Path $folder 'rollback-intent.json')) {throw 'Rollback already requested; readback only, no repeated start'}
|
||||||
|
$actual=Hash $binary
|
||||||
|
if ($actual -cne $p.old_sha256 -and $actual -cne $p.new_sha256) {throw 'Unknown runtime; refuse rollback overwrite'}
|
||||||
|
$current=Snapshot $actual;Preserved $intent.before $current $false
|
||||||
|
Write-New (Join-Path $folder 'rollback-intent.json') @{id=$p.id;actual_sha256=$actual;restore_sha256=$p.old_sha256;no_jobs=$true}
|
||||||
|
if ($current.service.state -eq 'Running') {Stop-Own} elseif ($current.service.state -ne 'Stopped') {throw 'Unexpected service transition'}
|
||||||
|
if ($actual -cne $p.old_sha256) {
|
||||||
|
$backup=Join-Path $folder 'original-binary.exe';if ((Hash $backup) -cne $p.old_sha256) {throw 'Exact original backup'}
|
||||||
|
$candidate=Join-Path $folder 'rollback-candidate.exe';[IO.File]::Copy($backup,$candidate,$false)
|
||||||
|
[IO.File]::Replace($candidate,$binary,(Join-Path $folder 'rollback-new-binary.exe'))
|
||||||
|
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($intent.binary_sddl);Set-Acl -LiteralPath $binary -AclObject $acl
|
||||||
|
}
|
||||||
|
Write-New (Join-Path $folder 'rollback-start-attempt.json') @{start_once=$true;no_jobs=$true}
|
||||||
|
Start-Own
|
||||||
|
$after=Snapshot $p.old_sha256;Preserved $intent.before $after $false
|
||||||
|
Write-New (Join-Path $folder 'rollback-result.json') $after
|
||||||
|
[pscustomobject]@{restored=$true;id=$p.id;native=$after;no_jobs=$true;no_reboot=$true}|ConvertTo-Json -Depth 24 -Compress
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (Test-Path -LiteralPath $folder) {Write-New (Join-Path $folder ('error-'+[guid]::NewGuid().ToString()+'.json')) @{incomplete=$true;error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;no_retry_start=$true}}
|
||||||
|
throw
|
||||||
|
}
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def digest(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||||
|
def write(folder,name,value):
|
||||||
|
descriptor=os.open(folder/name,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
|
||||||
|
with os.fdopen(descriptor,'w') as stream:json.dump(value,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def source_files():
|
||||||
|
names=['Cargo.toml','Cargo.lock','rust-toolchain.toml','crates/agent-windows/Cargo.toml','crates/agent-windows/build.rs']
|
||||||
|
for name in ['main','lib','runtime','native','inventory','journal','service','process','actions','clock']:
|
||||||
|
names.append('crates/agent-windows/src/'+name+'.rs')
|
||||||
|
names+=['crates/agent-windows/examples/runtime_state.rs']
|
||||||
|
names+=['crates/agent/src/'+name+'.rs' for name in ['https_channel','transport','wire_channel']]
|
||||||
|
for crate in ['agent-core','domain','protocol']:
|
||||||
|
names.append('crates/'+crate+'/Cargo.toml')
|
||||||
|
if crate=='agent-core':names.extend('crates/agent-core/src/'+name+'.rs' for name in ['lib','auth','crypto','jobs','ledger','reconcile'])
|
||||||
|
else:names.extend(str(path.relative_to(cb.ROOT)) for path in sorted((cb.ROOT/'crates'/crate/'src').glob('*.rs')))
|
||||||
|
names.extend(str(path.relative_to(cb.ROOT)) for path in sorted((cb.ROOT/'crates/agent-windows/native').glob('*')) if path.is_file())
|
||||||
|
names.append('proto/agent.proto')
|
||||||
|
require(all((cb.ROOT/name).is_file() for name in names),'all default-profile build sources must exist/freeze first')
|
||||||
|
return {name:digest(cb.ROOT/name) for name in sorted(set(names))}
|
||||||
|
|
||||||
|
|
||||||
|
def stable(manifest):
|
||||||
|
require(manifest['architecture']==TARGET and manifest['default_features'] is True
|
||||||
|
and manifest['system_helper_feature'] is False,'qualified default unprivileged Windows profile')
|
||||||
|
require(all((cb.ROOT/name).is_file() and digest(cb.ROOT/name)==sha for name,sha in manifest['source_files'].items()),'qualified source drift')
|
||||||
|
for item in manifest['artifacts'].values():
|
||||||
|
path=Path(item['path']);require(path.is_file() and digest(path)==item['sha256'],'qualified artifact changed')
|
||||||
|
|
||||||
|
|
||||||
|
def command(arguments,timeout=300):
|
||||||
|
result=subprocess.run(arguments,capture_output=True,timeout=timeout)
|
||||||
|
if result.returncode:raise RuntimeError('LOCAL_BUILD_FAILED_'+str(result.returncode))
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def build():
|
||||||
|
"""Local cross-build only; source must already have been frozen by owners."""
|
||||||
|
os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
|
||||||
|
before=source_files();write(folder,'source-before.json',before)
|
||||||
|
target=cb.ROOT/'devstate/windows-runtime/target';target.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
script='cargo clippy --locked --offline --target '+TARGET+' -p rmm-agent-windows --all-targets -- -D warnings && cargo build --locked --offline --target '+TARGET+' -p rmm-agent-windows --bin rmm-agent-windows --example runtime_state --release && cargo test --locked --offline --target '+TARGET+' -p rmm-agent-windows --lib --bin rmm-agent-windows --no-run --message-format=json'
|
||||||
|
raw=command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m',
|
||||||
|
'-v',str(cb.ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','/bin/sh',IMAGE,'-c',script])
|
||||||
|
require(source_files()==before,'source changed during local build; do not qualify')
|
||||||
|
units={}
|
||||||
|
for line in raw.decode().splitlines():
|
||||||
|
try:item=json.loads(line)
|
||||||
|
except ValueError:continue
|
||||||
|
if item.get('reason')=='compiler-artifact' and 'rmm-agent-windows' in item.get('package_id',''):
|
||||||
|
require('system-helper' not in item.get('features',[]),'system helper excluded from passive qualification')
|
||||||
|
if item.get('reason')=='compiler-artifact' and item.get('profile',{}).get('test') and item.get('executable'):
|
||||||
|
kind=item['target']['kind'];key='lib' if 'lib' in kind else 'bin' if 'bin' in kind else None
|
||||||
|
if key:units[key]=target/Path(item['executable']).relative_to('/target')
|
||||||
|
require(set(units)=={'lib','bin'},'both actual compiled native test executables')
|
||||||
|
artifacts={}
|
||||||
|
for key,path,name,release in [('agent',target/TARGET/'release/rmm-agent-windows.exe','rmm-agent-windows.exe',True),
|
||||||
|
('probe',target/TARGET/'release/examples/runtime_state.exe','RuntimeStateProbe.exe',True),
|
||||||
|
('lib',units['lib'],'windows-tests-lib.exe',False),('bin',units['bin'],'windows-tests-bin.exe',False)]:
|
||||||
|
destination=folder/name;shutil.copyfile(path,destination);destination.chmod(0o600)
|
||||||
|
original_sha=digest(path)
|
||||||
|
if key in ('lib','bin'):
|
||||||
|
# Strip only the private delivery copy. Preserve Cargo's original
|
||||||
|
# linked executable and all prior manifests/native observations.
|
||||||
|
command(['docker','run','--rm','--network','none','--read-only',
|
||||||
|
'-v',str(folder.resolve())+':/artifacts',
|
||||||
|
'--entrypoint','x86_64-w64-mingw32-strip',IMAGE,
|
||||||
|
'--strip-debug','/artifacts/'+name])
|
||||||
|
require(digest(path)==original_sha,'original native unit link preserved')
|
||||||
|
data=destination.read_bytes();offset=int.from_bytes(data[60:64],'little')
|
||||||
|
require(data[:2]==b'MZ' and data[offset:offset+6]==b'PE\0\0\x64\x86','native x86-64 PE artifact')
|
||||||
|
artifacts[key]=dict(path=str(destination.resolve()),name=name,sha256=digest(destination),bytes=len(data),release_build=release)
|
||||||
|
if key in ('lib','bin'):
|
||||||
|
artifacts[key].update(debug_stripped=True,original_link_path=str(path.resolve()),original_link_sha256=original_sha)
|
||||||
|
require(source_files()==before,'source changed during artifact preparation; do not qualify')
|
||||||
|
manifest=dict(schema_version=1,architecture=TARGET,default_features=True,system_helper_feature=False,
|
||||||
|
source_files=before,artifacts=artifacts,checks=dict(cross_clippy_D_warnings=True,release_build=True,windows_unit_link=True),native_vm_tested=False)
|
||||||
|
write(folder,'manifest.json',manifest)
|
||||||
|
print(json.dumps(dict(manifest=str((folder/'manifest.json').resolve()),artifacts={k:v['sha256'] for k,v in artifacts.items()},native_vm_tested=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def upload(item):
|
||||||
|
pointer=cb.EVIDENCE/(item['name']+'.latest.json')
|
||||||
|
if pointer.exists() and cb.contract.protected_json(pointer)['sha256']==item['sha256']:
|
||||||
|
return cb.powershell(cb.VERIFY_UPLOAD,dict(name=item['name'],sha256=item['sha256']))
|
||||||
|
return cb.upload(item['path'],item['name'])
|
||||||
|
|
||||||
|
|
||||||
|
def qualify(manifest_path):
|
||||||
|
manifest=cb.contract.protected_json(manifest_path);stable(manifest)
|
||||||
|
os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
folder=STATE/('qualification-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
|
||||||
|
write(folder,'intent.json',dict(manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),source_files=manifest['source_files'],test_runner_sha256=hashlib.sha256(TESTS.encode()).hexdigest()))
|
||||||
|
before=auto.scopes();flags=auto.status();write(folder,'server-before.json',dict(counts=before,flags=flags))
|
||||||
|
reports={}
|
||||||
|
for key,minimum in [('lib',12),('bin',6)]:
|
||||||
|
item=manifest['artifacts'][key];upload(item)
|
||||||
|
report=cb.powershell(TESTS,dict(name=item['name'],sha256=item['sha256']),timeout=150)
|
||||||
|
write(folder,key+'-native.json',report)
|
||||||
|
require(report['listed']['exit_code']==report['result']['exit_code']==0,'native unit executable success')
|
||||||
|
listed=re.findall(r'^(.+): test\r?$',report['listed']['stdout'],re.M)
|
||||||
|
summary=re.search(r'test result: ok\. (\d+) passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',report['result']['stdout'])
|
||||||
|
require(summary and len(listed)>=minimum and int(summary.group(1))==len(listed),'all actually listed native tests passed with zero skipped/filtered')
|
||||||
|
reports[key]=dict(artifact_sha256=item['sha256'],passed=len(listed),test_names=listed,native_context='bootstrap_administrator_unit_tests')
|
||||||
|
stable(manifest)
|
||||||
|
after=auto.scopes();after_flags=auto.status();require(after==before and flags==after_flags and auto.flags_disabled(flags),'native units changed no job counts or server policy/hooks')
|
||||||
|
write(folder,'result.json',dict(verified=True,completed=True,native_unit_tests=reports,manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),source_files=manifest['source_files'],server_counts=after,server_flags=flags,
|
||||||
|
no_jobs=True,no_clock_service_changes=True,local_service_runtime_test=False,clock_adapter_qualified=False))
|
||||||
|
print(json.dumps(dict(verified=True,qualification=str((folder/'result.json').resolve()),native_tests={k:v['passed'] for k,v in reports.items()},clock_adapter_qualified=False)))
|
||||||
|
|
||||||
|
|
||||||
|
PREPARE_SOURCE=base.PREPARE_SCRIPT.replace('TransportAcceptance.ps1','RuntimeUpgrade.ps1')
|
||||||
|
LAUNCH_SOURCE=base.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1','RuntimeUpgrade.ps1').replace('RmmTransportPayload','RmmRuntimePayload')
|
||||||
|
|
||||||
|
|
||||||
|
def stage_source():
|
||||||
|
raw=UPGRADE.encode();sha=hashlib.sha256(raw).hexdigest()
|
||||||
|
value=cb.powershell(PREPARE_SOURCE,dict(sha256=sha))
|
||||||
|
if not value['already_uploaded']:
|
||||||
|
folder=STATE/'source';folder.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
path=folder/(sha+'.ps1')
|
||||||
|
if not path.exists():
|
||||||
|
fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
|
||||||
|
with os.fdopen(fd,'wb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno())
|
||||||
|
require(digest(path)==sha,'fixed staged source bytes')
|
||||||
|
prefix=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix']
|
||||||
|
arguments=['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]]
|
||||||
|
target='/C:/ProgramData/RustDiscoveryBootstrap/'+sha+'/RuntimeUpgrade.ps1'
|
||||||
|
result=subprocess.run(arguments,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
|
||||||
|
require(result.returncode==0,'fixed runtime bootstrap transfer')
|
||||||
|
require(cb.powershell(PREPARE_SOURCE,dict(sha256=sha))['already_uploaded'],'staged source hash verification')
|
||||||
|
return sha
|
||||||
|
|
||||||
|
|
||||||
|
def remote(intent,action):
|
||||||
|
require(intent['source_sha256']==hashlib.sha256(UPGRADE.encode()).hexdigest(),'preserved exact runtime bootstrap source')
|
||||||
|
payload={**intent['remote_payload'],'action':action}
|
||||||
|
return cb.powershell(LAUNCH_SOURCE,dict(sha256=intent['source_sha256'],payload=payload),timeout=100,remote_signed=True)
|
||||||
|
|
||||||
|
|
||||||
|
def manifest_and_qualification(manifest_path,qualification_path):
|
||||||
|
manifest=cb.contract.protected_json(manifest_path);stable(manifest)
|
||||||
|
qualified=cb.contract.protected_json(qualification_path)
|
||||||
|
require(qualified['verified'] is True and qualified['completed'] is True
|
||||||
|
and qualified['manifest_sha256']==digest(manifest_path)
|
||||||
|
and qualified['manifest_path']==str(manifest_path.resolve())
|
||||||
|
and qualified['source_files']==manifest['source_files']
|
||||||
|
and qualified['native_unit_tests']['lib']['artifact_sha256']==manifest['artifacts']['lib']['sha256']
|
||||||
|
and qualified['native_unit_tests']['bin']['artifact_sha256']==manifest['artifacts']['bin']['sha256']
|
||||||
|
and qualified['native_unit_tests']['lib']['passed']>=12 and qualified['native_unit_tests']['bin']['passed']>=6
|
||||||
|
and qualified['no_jobs'] is True and qualified['clock_adapter_qualified'] is False,'source-bound completed native library/bin qualification')
|
||||||
|
return manifest,qualified
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade(manifest_path,qualification_path):
|
||||||
|
manifest,qualified=manifest_and_qualification(manifest_path,qualification_path)
|
||||||
|
current=cb.contract.protected_json(activation.CURRENT)
|
||||||
|
require(current['type']=='rmm.windows.current-transport' and current['case_id']==ACTIVATION
|
||||||
|
and current['transport']=='auto' and current['binary_sha256']==base.BINARY,'known original native automatic transport index')
|
||||||
|
derived=activation.transition(ACTIVATION)
|
||||||
|
require(derived['original_config_sha256']==base.ORIGINAL_CONFIG
|
||||||
|
and derived['expected_auto_config_sha256']==current['config_sha256'],'independently derived original auto bytes')
|
||||||
|
os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||||
|
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700)
|
||||||
|
for key in ['agent','probe']:upload(manifest['artifacts'][key])
|
||||||
|
source=stage_source()
|
||||||
|
payload=dict(id=ident,old_sha256=base.BINARY,new_sha256=manifest['artifacts']['agent']['sha256'],
|
||||||
|
probe_sha256=manifest['artifacts']['probe']['sha256'],config_sha256=current['config_sha256'])
|
||||||
|
intent=dict(id=ident,type='passive_runtime_upgrade',started_at=cb.contract.now().isoformat(),source_sha256=source,
|
||||||
|
manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),qualification_path=str(qualification_path.resolve()),
|
||||||
|
qualification_sha256=digest(qualification_path),remote_payload=payload,config_derivation=derived,
|
||||||
|
original_transport_index=dict(path=str(activation.CURRENT.resolve()),sha256=digest(activation.CURRENT)),
|
||||||
|
no_jobs=True,no_binding_or_policy_change=True,no_clock_change=True,no_reboot=True)
|
||||||
|
write(folder,'intent.json',intent)
|
||||||
|
before=dict(native=remote(intent,'state'),central=base.observe(ident),counts=auto.scopes(),server=auto.status())
|
||||||
|
require(before['counts']==qualified['server_counts'] and before['server']==qualified['server_flags']
|
||||||
|
and auto.flags_disabled(before['server']),'unchanged settled job/policy state after qualification')
|
||||||
|
require(before['native']['service']['state']=='Running' and before['native']['journal']['pending_inventory_events']==0,'settled original service and acknowledged inventory')
|
||||||
|
write(folder,'before.json',before)
|
||||||
|
write(folder,'enter-intent.json',dict(id=ident,stop_swap_start_once=True,source_sha256=source))
|
||||||
|
try:write(folder,'entered.json',remote(intent,'enter'))
|
||||||
|
except Exception as error:
|
||||||
|
write(folder,'enter-reply-incomplete.json',dict(error_type=type(error).__name__,continuation='finish reads only; explicit rollback is separate, never repeat enter'))
|
||||||
|
raise
|
||||||
|
print('Passive runtime transition '+ident,flush=True)
|
||||||
|
finish(ident)
|
||||||
|
|
||||||
|
|
||||||
|
def load_case(ident):
|
||||||
|
ident=str(uuid.UUID(ident));folder=STATE/ident
|
||||||
|
intent=cb.contract.protected_json(folder/'intent.json')
|
||||||
|
require(intent['id']==ident and intent['type']=='passive_runtime_upgrade','same retained runtime case')
|
||||||
|
require(digest(intent['manifest_path'])==intent['manifest_sha256'] and digest(intent['qualification_path'])==intent['qualification_sha256'],'historical qualification files unchanged')
|
||||||
|
manifest,_=manifest_and_qualification(Path(intent['manifest_path']),Path(intent['qualification_path']))
|
||||||
|
return folder,intent,manifest
|
||||||
|
|
||||||
|
|
||||||
|
def publish_current(folder,result_name,binary):
|
||||||
|
result=folder/result_name
|
||||||
|
value=dict(schema_version=1,type='rmm.windows.current-runtime',case_id=folder.name,agent_id=base.AGENT,
|
||||||
|
asset_id=base.ASSET,binary_sha256=binary,transport='auto',evidence=dict(path=str(result.resolve()),sha256=digest(result)),
|
||||||
|
windows_jobs_enabled=False,clock_adapter_qualified=False)
|
||||||
|
path=cb.EVIDENCE/'current-runtime.json'
|
||||||
|
if path.exists():
|
||||||
|
previous=cb.contract.protected_json(path)
|
||||||
|
if previous==value:return
|
||||||
|
require(previous['case_id']==folder.name,'do not overwrite another current runtime transition')
|
||||||
|
backup=folder/('previous-index-'+str(uuid.uuid4())+'.json');write(folder,backup.name,previous)
|
||||||
|
temporary=path.with_name('.runtime-'+str(uuid.uuid4())+'.json')
|
||||||
|
write(temporary.parent,temporary.name,value);os.replace(temporary,path)
|
||||||
|
|
||||||
|
|
||||||
|
def finish(ident):
|
||||||
|
folder,intent,manifest=load_case(ident)
|
||||||
|
restored=(folder/'rollback-intent.json').exists()
|
||||||
|
before=cb.contract.protected_json(folder/'before.json')
|
||||||
|
observed=remote(intent,'finish');write(folder,'finish-readback-'+str(uuid.uuid4())+'.json',observed)
|
||||||
|
expected=base.BINARY if restored else manifest['artifacts']['agent']['sha256']
|
||||||
|
require(observed['completed'] is True and observed['read_only'] is True and observed['restored']==restored and observed['native']['binary_sha256']==expected,'actual retained selected runtime; no second start')
|
||||||
|
started=cb.contract.protected_json(folder/'rollback-intent.json')['started_at'] if restored else intent['started_at']
|
||||||
|
online=base.wait_mode(ident,'wss',cb.contract.timestamp(started),before['central']['device'])
|
||||||
|
after=remote(intent,'finish');write(folder,'after-readback-'+str(uuid.uuid4())+'.json',after)
|
||||||
|
native=after['native'];require(native['journal']['pending_inventory_events']==0 and native['journal']['sequence']>before['native']['journal']['sequence'],'actual new process heartbeat sequence and concrete inventory ACK')
|
||||||
|
device=base.read_device();denied=base.foreign_denied()
|
||||||
|
require(cb.contract.timestamp(device['observed_at'])>=cb.contract.timestamp(intent['started_at']),'fresh upgraded inventory stored independently')
|
||||||
|
observations={o['scope']:o for o in device['inventory'].get('observations',[])}
|
||||||
|
hardware=observations.get('windows.hardware',{})
|
||||||
|
if not restored:require(hardware.get('quality')=='valid' and hardware['data']['logical_processors_visible']>0
|
||||||
|
and hardware['data']['memory_total_bytes']>0,'actual unprivileged native hardware observation')
|
||||||
|
counts=auto.scopes();flags=auto.status();require(counts==before['counts'] and flags==before['server'] and auto.flags_disabled(flags),'both target job counts/policy/fault hooks preserved')
|
||||||
|
stable(manifest)
|
||||||
|
result_name='rollback-completed.json' if restored else 'result.json'
|
||||||
|
result=folder/result_name
|
||||||
|
value=dict(verified=True,completed=True,restored=restored,id=ident,native=native,online=online,stored_inventory=device,foreign_denied=denied,
|
||||||
|
manifest_path=intent['manifest_path'],manifest_sha256=intent['manifest_sha256'],qualification_sha256=intent['qualification_sha256'],
|
||||||
|
counts=counts,server=flags,no_jobs=True,no_reboot=True,no_clock_change=True,windows_jobs_enabled=False,
|
||||||
|
clock_adapter_qualified=False,private_key_read=False,configuration_unchanged=True,transport='auto',preferred_wire='wss')
|
||||||
|
if result.exists():require(cb.contract.protected_json(result)['verified'] is True,'retain prior successful runtime result')
|
||||||
|
else:write(folder,result_name,value)
|
||||||
|
publish_current(folder,result_name,expected)
|
||||||
|
print(json.dumps(dict(verified=True,id=ident,passive_only=True,clock_adapter_qualified=False,windows_jobs_enabled=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def rollback(ident):
|
||||||
|
folder,intent,_=load_case(ident)
|
||||||
|
before=cb.contract.protected_json(folder/'before.json')
|
||||||
|
require(auto.scopes()==before['counts'] and auto.status()==before['server'],'no intervening job/policy changes before explicit rollback')
|
||||||
|
write(folder,'rollback-intent.json',dict(id=ident,old_binary_sha256=base.BINARY,started_at=cb.contract.now().isoformat(),start_once=True,no_jobs=True))
|
||||||
|
try:value=remote(intent,'rollback')
|
||||||
|
except Exception as error:
|
||||||
|
write(folder,'rollback-reply-incomplete.json',dict(error_type=type(error).__name__,readback_required=True,no_repeated_start=True));raise
|
||||||
|
write(folder,'rollback-result.json',value)
|
||||||
|
require(value['restored'] is True and value['native']['binary_sha256']==base.BINARY,'actual preserved original binary restored')
|
||||||
|
finish(ident)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('phase',choices=['build-local','qualify-native','upgrade-passive','finish','rollback'])
|
||||||
|
parser.add_argument('--manifest',type=Path);parser.add_argument('--qualification',type=Path);parser.add_argument('--id')
|
||||||
|
args=parser.parse_args()
|
||||||
|
if args.phase=='build-local':require(not(args.manifest or args.qualification or args.id),'build creates a fresh immutable manifest');build()
|
||||||
|
elif args.phase=='qualify-native':require(args.manifest and not(args.qualification or args.id),'one qualified local manifest');qualify(args.manifest)
|
||||||
|
elif args.phase=='upgrade-passive':require(args.manifest and args.qualification and not args.id,'native qualified same manifest, no supplied new case ID');upgrade(args.manifest,args.qualification)
|
||||||
|
else:require(args.id and not(args.manifest or args.qualification),'same original transition ID only');{'finish':finish,'rollback':rollback}[args.phase](args.id)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
try:main()
|
||||||
|
except Exception as error:
|
||||||
|
print('WINDOWS_RUNTIME_UPGRADE_INCOMPLETE:'+type(error).__name__)
|
||||||
|
raise SystemExit(2) from None
|
||||||
@@ -52,6 +52,23 @@ Zugänge und private Rohbelege bleiben gitignoriert.
|
|||||||
|
|
||||||
## Aktuelle Windowsfortsetzung
|
## Aktuelle Windowsfortsetzung
|
||||||
|
|
||||||
|
Neuester passiver Windowsstand: Agent `f64e8115…`, eigener erhaltender Fall
|
||||||
|
`c4f9b280-e83d-4b8e-a1c2-1cd103f73eda`, tatsächlicher LocalService/Auto/WSS,
|
||||||
|
gleiche Identität/Schlüsselmetadaten/ACLs und ursprüngliche Telemetrie-DB.
|
||||||
|
Neue Hardware-/begrenzte Softwarebeobachtungen, zwei frische Heartbeats und
|
||||||
|
konkretes Inventar-ACK nachgewiesen. Davor native Default-Unitqualifikation
|
||||||
|
`3dbfe686-6e91-41e9-a5bc-078f7a4e3e6a`:12+6 tatsächlich bestanden.
|
||||||
|
Jobs bleiben deaktiviert, Clockadapter fest unqualifiziert, kein Signingbinding,
|
||||||
|
Verbrauchsledger oder Jobsverzeichnis angelegt. W32Time gestoppt und unverändert;
|
||||||
|
dessen Start und eine mögliche nur prozessbezogene RemoteSigned-Option wurden
|
||||||
|
konkret beim Benutzer angefragt, noch nicht genehmigt. SYSTEM-Helperquelle nur
|
||||||
|
featureisoliert vorbereitet, noch nicht installiert/nativ als Dienst abgenommen.
|
||||||
|
Nach tatsächlichem Codecfehler wurde die Probevariante strikt korrigiert;
|
||||||
|
eigener Fall `38b0fe75-f6a5-4ad3-ab2d-7f3acf7e9cbd` bestand alle21 nativen
|
||||||
|
Unitfixtures, kein tatsächlicher SYSTEM-/Pipepeer-Nachweis.
|
||||||
|
Details und Grenzen im [Implementierungsstand](implementation-status.md) und
|
||||||
|
[Clockbericht](windows-clock-readiness.md). Notebook weiterhin nur Entwicklung.
|
||||||
|
|
||||||
**Fortsetzung 2026-11-14:** Gemeinsamer `rmm-agent-core` und Linuxadapter
|
**Fortsetzung 2026-11-14:** Gemeinsamer `rmm-agent-core` und Linuxadapter
|
||||||
implementiert. Eigene Core-Unittests zuerst auf Cloud-Linux (25) und danach auf
|
implementiert. Eigene Core-Unittests zuerst auf Cloud-Linux (25) und danach auf
|
||||||
Windows (24) nativ ohne Skip bestanden; Fall
|
Windows (24) nativ ohne Skip bestanden; Fall
|
||||||
|
|||||||
@@ -1,5 +1,58 @@
|
|||||||
# Tatsächlicher Implementierungsstand
|
# Tatsächlicher Implementierungsstand
|
||||||
|
|
||||||
|
## Windows-Laufzeit erhaltend als LocalService aktualisiert — 2026-11-14
|
||||||
|
|
||||||
|
Zusätzlicher Helper-Quelllauf: zunächst20/21 native Fixtures bestanden; Serde
|
||||||
|
akzeptierte bei einer intern getaggten Unit-Variante unerwartete Probe-Felder.
|
||||||
|
Die Variante ist jetzt eine strikt leere Struktur, unverändertes Wireformat
|
||||||
|
`{"operation":"probe"}`. Der ursprüngliche Negativtest bleibt erhalten.
|
||||||
|
Neuer Fall `38b0fe75-f6a5-4ad3-ab2d-7f3acf7e9cbd` bestand tatsächlich alle21
|
||||||
|
Fixtures einschließlich neun Helperfälle, ohne Skip, als Bootstrapadministrator.
|
||||||
|
Das qualifiziert Codec-/Guardfixturen, keinen laufenden SYSTEM-Dienst oder
|
||||||
|
tatsächliche Pipepeers. Die Helperquelle wurde zusätzlich unabhängig auf
|
||||||
|
Grantintervall, echte SCM-Prozessidentität, Dependencies/Groups, Recoveryaktionen
|
||||||
|
und Deadline geprüft. Recovery-Command/Reboot/Restart bleiben verweigert;
|
||||||
|
überschrittene SCM-Laufzeit nach möglicher Wirkung bleibt Unknown. Eine synchrone
|
||||||
|
SCM-API kann trotzdem blockieren; keine harte Effektabbruchgarantie behauptet.
|
||||||
|
|
||||||
|
Die Default-Laufzeit integriert jetzt den gemeinsamen Jobkern, additive
|
||||||
|
Telemetrie-/Jobtabellen und monotone Sequenzmigration. Der PowerShell-5.1-
|
||||||
|
Executor ist implementiert: unveränderte genehmigte Skriptbytes, einzelne
|
||||||
|
Argumente, begrenzte Rohbytes, atomare Windows-Jobobject-Zuordnung und explizite
|
||||||
|
Handlevererbung. Maschinenrichtlinien werden nicht verändert; die Ausführungs-
|
||||||
|
richtlinie wird derzeit geerbt. Timeout/Abbruch kann eine Wirkung hinterlassen
|
||||||
|
und wird deshalb nicht als erfolgreicher oder sicher wiederholbarer Lauf gewertet.
|
||||||
|
Dies ist noch kein tatsächlicher Windows-RMM-Jobnachweis.
|
||||||
|
|
||||||
|
Native Qualifikation `3dbfe686-6e91-41e9-a5bc-078f7a4e3e6a`: alle12 Library-
|
||||||
|
und6 Binarytests ohne Skip bestanden, als Bootstrapadministrator. Ein früherer
|
||||||
|
Fall bestand bereits12 Tests, verlor danach beim Übertragen der großen zweiten
|
||||||
|
Testdatei die Antwort und bleibt unvollständig. Neue, vor Hashbildung von
|
||||||
|
Debuginformationen befreite Testkopien wurden beide erneut tatsächlich geprüft;
|
||||||
|
Originalartefakte und frühere Berichte blieben erhalten. Cross-Clippy mit
|
||||||
|
`-D warnings`, Releasebuild und Quellenbindung bestanden.
|
||||||
|
|
||||||
|
Anschließend eigener erhaltender Dienstwechsel
|
||||||
|
`c4f9b280-e83d-4b8e-a1c2-1cd103f73eda`: Agent `f64e8115…` läuft tatsächlich
|
||||||
|
als LocalService SID19, automatisch, mit unverändertem `transport=auto` und
|
||||||
|
bevorzugtem WSS. Geräteidentität, Zertifikat, private Schlüsselmetadaten,
|
||||||
|
Konfiguration/ACLs und ursprüngliche Telemetrie-DB-Dateiidentität erhalten;
|
||||||
|
Integrität `ok`, Sequenz steigt, zwei frische Heartbeats und konkretes Inventar-
|
||||||
|
ACK nachgewiesen. Neue CPU-/Speicher- und begrenzte64-/32-Bit-HKLM-Software-
|
||||||
|
beobachtungen wurden unabhängig auf dem Server gelesen; explizit Teilinventar,
|
||||||
|
kein `Win32_Product`, kein vollständiger Patchstatus. Fremder Tenant verweigert.
|
||||||
|
|
||||||
|
Windows bleibt0 Jobs/Outbox/Grants/ungeklärte Wirkungen, Linux30/30/26/0.
|
||||||
|
Kein Binding, Verbrauchsledger oder Jobsverzeichnis angelegt; keine neue
|
||||||
|
Ausführungscapability. `enable_jobs=false` und `ADAPTER_QUALIFIED=false` bleiben
|
||||||
|
geschlossen. Der implementierte Zeitadapter und seine tatsächlichen negativen
|
||||||
|
Zwischenstände stehen in [Windows-Zeitstatus](windows-clock-readiness.md).
|
||||||
|
W32Time blieb gestoppt; dessen Start und eine etwaige prozessbezogene
|
||||||
|
PowerShell-Richtlinie warten auf die jeweils konkrete Benutzerentscheidung.
|
||||||
|
Die SYSTEM-Helperquelle ist featureisoliert; daraus folgt keine native Helper-,
|
||||||
|
Pipe- oder Systemaktionsabnahme. Geschützte Belege:
|
||||||
|
`devstate/windows-client/runtime-upgrade/<Fall>/`.
|
||||||
|
|
||||||
## Dauerhafte Outcomes und atomarer Start nativ geprüft — 2026-11-14
|
## Dauerhafte Outcomes und atomarer Start nativ geprüft — 2026-11-14
|
||||||
|
|
||||||
Beim Portieren wurde eine bestehende Verfügbarkeitslücke gefunden: Ein Crash
|
Beim Portieren wurde eine bestehende Verfügbarkeitslücke gefunden: Ein Crash
|
||||||
|
|||||||
@@ -0,0 +1,229 @@
|
|||||||
|
# Windows-Zeitstatus: Adapter und native Readinessprobe
|
||||||
|
|
||||||
|
Stand 2026-11-14. Ergänzung zu [Windows-Jobgrenze](windows-job-boundary.md).
|
||||||
|
Diese Strecke ändert weder die Windows-Geräteidentität noch die WebUI-Grenze.
|
||||||
|
Ein Zeitstatusbericht ist keine Jobgenehmigung. `NativeClock::now()` verweigert
|
||||||
|
aktuell immer mit `CLOCK_ADAPTER_UNQUALIFIED`, unabhängig von einem positiven
|
||||||
|
Diagnosestatus; `ADAPTER_QUALIFIED=false` bleibt bis zur tatsächlichen nativen
|
||||||
|
Adapterabnahme im Code fest geschlossen. Der aktuelle RPC-Prototyp ist
|
||||||
|
noch kein vollständig qualifizierter produktiver Zeitvertrauensnachweis.
|
||||||
|
|
||||||
|
## Vertrag und konservative Genauigkeitspolitik
|
||||||
|
|
||||||
|
`crates/agent-windows/src/clock.rs` enthält eine numerische Statusauswertung und
|
||||||
|
einen `SyncClock`-Adapter. Ein Stub wird aus dem engen IDL mit WIDL generiert;
|
||||||
|
der C-Adapter fängt RPC-Ausnahmen mittels Windows-SEH vor der Rust-Grenze ab.
|
||||||
|
Einziger aufgerufener Statusvertrag ist MS-W32T Interface4.1, Opnum6. Die sechs
|
||||||
|
vorherigen IDL-Platzhalter erhalten ausschließlich dessen Ordinal; sie werden
|
||||||
|
niemals aufgerufen und bilden keine mutierenden Produktfunktionen ab.
|
||||||
|
|
||||||
|
Die Zeitintervalle für Verzögerung, Dispersion, Phasenabweichung und Alter sind
|
||||||
|
100ns-Einheiten. `qwLastSyncTicks` ist dagegen ein UTC-FILETIME seit1601;
|
||||||
|
`tpTimeLastGoodSync` bezeichnet das verstrichene Alter seit dem letzten guten
|
||||||
|
Abgleich, kein zweites UTC-Datum:
|
||||||
|
[Statusstruktur](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/f60ebce0-df96-4c96-b40b-fdbd34a2c936),
|
||||||
|
[Zeitdienstelemente](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/1da649d7-3edf-4a9a-98c2-907ecacd1633).
|
||||||
|
|
||||||
|
Der technische Default verlangt gemeinsam:
|
||||||
|
|
||||||
|
- `SYNC=2`, letztes Syncergebnis0, Leap0..2 und Stratum1..15;
|
||||||
|
- letzten erfolgreichen Abgleich höchstens3600s alt, UTC-Zeitstempel nicht in
|
||||||
|
der Zukunft, beide Altersdarstellungen innerhalb1s plus Abrufdauer konsistent;
|
||||||
|
- Dispersion + halbe nichtnegative Root-Roundtripverzögerung + absolute
|
||||||
|
Phasenabweichung + gesamte gemessene Abrufdauer höchstens2s;
|
||||||
|
- Abrufdauer höchstens1s, bekannte Flags und exaktes x64-Strukturlayout120Byte.
|
||||||
|
|
||||||
|
Negative Root-Verzögerung wird konservativ verweigert, auch wenn einzelne
|
||||||
|
Zeitquellen solche Werte liefern können. Überlauf, unbekannte Felder, Fehler,
|
||||||
|
veralteter oder widersprüchlicher Status schließen das Gate. Das separate
|
||||||
|
MS-SNTP-Authentifizierungsflag wird nicht über die bestehende Linux-NTP-Politik
|
||||||
|
hinaus verlangt. Die Werte begrenzen die gemeldete technische Unsicherheit;
|
||||||
|
sie ersetzen keine neue kryptografische Vertrauensentscheidung für Zeitquellen.
|
||||||
|
[Synczustände](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/b4abb4b0-6d6e-41e4-bd41-d54980d0598a).
|
||||||
|
|
||||||
|
Wallclock und beide präzisen Kernel-Interruptzähler werden vor und nach jedem
|
||||||
|
Abruf beobachtet. Der unbereinigte Zähler berücksichtigt Schlafzeit, der
|
||||||
|
unbiased-Zähler schließt sie aus. Eine Differenz oder Wallclockänderung über1s
|
||||||
|
invalidiert. Ein späterer Status kann erst nach einem tatsächlich erfolgreichen
|
||||||
|
Abgleich mit UTC-Zeitstempel nach dieser Diskontinuität wieder öffnen. Einfaches
|
||||||
|
Pollieren des alten Pre-Resume-Status genügt nicht. Es wird kein OS-Suspend oder
|
||||||
|
Uhrsprung als destruktiver nativer Test ausgelöst:
|
||||||
|
[Interruptzähler](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise),
|
||||||
|
[Zähler ohne Schlafzeit](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttimeprecise).
|
||||||
|
|
||||||
|
## Lokaler RPC und verbleibende Identitätsfrage
|
||||||
|
|
||||||
|
Der erste Readiness-Prototyp benutzt ausschließlich lokalen `ncacn_np` am
|
||||||
|
festen authentifizierten Endpunkt `\\pipe\\W32TIME_ALT`, WINNT, PacketPrivacy,
|
||||||
|
Identify und den tatsächlichen Prozesskontext; keine Zugangsdaten und kein
|
||||||
|
Fallback zum unauthentifizierten W32TIME-Endpunkt. Der NDR-Allocator begrenzt
|
||||||
|
seine Gesamtdaten auf64KiB. RPC-Timeout1,5s ist ein Paket-Inaktivitätslimit;
|
||||||
|
zusätzlich verweigert die Auswertung jede tatsächlich über1s dauernde Abfrage.
|
||||||
|
Ausgaben enthalten nur begrenzte numerische Statusfelder und Fehlercodes, keine
|
||||||
|
Peer-Namen, Adressen oder Rohdaten.
|
||||||
|
[MS-W32T-Transport](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655),
|
||||||
|
[RPC-Zeitlimit](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetoption).
|
||||||
|
|
||||||
|
WINNT mit PacketPrivacy authentifiziert allein noch nicht zuverlässig die
|
||||||
|
Identität des lokalen Named-Pipe-Servers. NTLM kann auch bei gesetztem
|
||||||
|
`MUTUAL_AUTH` Erfolg melden, obwohl es keine gegenseitige Authentifizierung
|
||||||
|
unterstützt. Eine solche Flagänderung ist kein Sicherheitsnachweis. Vor
|
||||||
|
Produktintegration muss zusätzlich die tatsächliche Serveridentität belastbar
|
||||||
|
gebunden werden. `RPC_SECURITY_QOS_V3.Sid` ist insbesondere für `ncalrpc`
|
||||||
|
dokumentiert; ob die aktuelle W32Time-Implementierung einen entsprechend
|
||||||
|
qualifizierbaren lokalen Endpunkt anbietet, ist offen. Kein automatischer
|
||||||
|
Wechsel auf einen schwächeren Transport.
|
||||||
|
[RPC-QoS](https://learn.microsoft.com/en-us/windows/win32/rpc/quality-of-service),
|
||||||
|
[SID-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v3_w).
|
||||||
|
|
||||||
|
## Getrennte LocalService-Probe
|
||||||
|
|
||||||
|
`examples/clock_readiness.rs` ist ein eigener kurzlebiger SCM-Dienst
|
||||||
|
`RmmWindowsClockReadiness`. Er prüft im eigenen nativen Prozess TokenUser
|
||||||
|
`S-1-5-19`, erfasst das tatsächliche Elevationflag und den Elevationtyp sowie
|
||||||
|
aktivierte Administratormitgliedschaft und SYSTEM-Identität separat, liest zwei
|
||||||
|
Zeitstatuswerte und schreibt einen
|
||||||
|
höchstens16KiB großen Bericht. Keine RMM-Verbindung, kein Agentenstop, keine
|
||||||
|
Uhrkorrektur und keine Änderung von W32Time-Konfiguration oder System-ACLs.
|
||||||
|
|
||||||
|
`deploy/windows/clock_readiness.py` legt für jeden Versuch einen neuen privaten
|
||||||
|
Fall mit UUID, Source-/Binaryhash und dauerhaftem Intent vor dem RPC an.
|
||||||
|
Bootstrapdateien liegen versioniert unter einem eigenen privaten Verzeichnis.
|
||||||
|
Nur der eigene Readiness-Dienst erhält Schreibrecht auf seinen Ergebnisordner;
|
||||||
|
das Manifest bleibt Administratoren/SYSTEM vorbehalten. Nach Dienstende werden
|
||||||
|
Statusbericht und exakte Dienstkonfiguration gelesen und ausschließlich dieser
|
||||||
|
eng gebundene gestoppte Hilfsdienst entfernt. Ausgelieferte Dateien und private
|
||||||
|
Belege bleiben für Readback erhalten. Der vorhandene Bootstrap verwendet nur
|
||||||
|
prozessbezogen `RemoteSigned`, keine Maschinenrichtlinienänderung und keine
|
||||||
|
entsprechende Erlaubnis für spätere RMM-PowerShell-Jobs.
|
||||||
|
|
||||||
|
Nach unklarer SSH-Antwort ausschließlich `readback --id <bestehende UUID>`
|
||||||
|
verwenden. Kein erneutes Starten desselben Falls, kein blinder neuer Start als
|
||||||
|
Ersatz. `native_execution_verified` weist die tatsächliche LocalService-Probe
|
||||||
|
nach; `diagnostic_status_ready` bildet den Rohstatus beider Berichte ab; `clock_ready`
|
||||||
|
verlangt zusätzlich die getrennte Adapterqualifikation. Rohstatus allein kann
|
||||||
|
niemals produktive Clock-Bereitschaft behaupten. Ein negativer
|
||||||
|
Status ist ein gültiger Messbeleg und keine Freigabe für Jobcapabilities. Die
|
||||||
|
oben offene Serveridentitätsbindung bleibt dabei eigenständig erforderlich.
|
||||||
|
Das rohe Elevationflag wird nicht mit Administratormitgliedschaft gleichgesetzt;
|
||||||
|
seine tatsächliche Bedeutung für dieses Diensttoken wird erst nativ ermittelt.
|
||||||
|
[Token-Elevation](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_elevation),
|
||||||
|
[aktivierte Gruppenmitgliedschaft](https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-checktokenmembership).
|
||||||
|
|
||||||
|
## Tatsächlich lokal ausgeführte Qualifikation
|
||||||
|
|
||||||
|
- WIDL-Generierung und beide C-Objekte Windows-x64 mit Clang-SEH und `-Werror`:
|
||||||
|
erfolgreich; statische C-Assertions bestätigen120Byte-Status/64Byte-Rust-ABI.
|
||||||
|
- WindowsGNU-Crossbuild der Readiness-EXE mit Lockfile/offline: erfolgreich.
|
||||||
|
- Drei Rust-Tests: Status-/Unsicherheitsverweigerung, Suspend mit notwendigem
|
||||||
|
anschließendem Sync, Wallclockrücksprung/Überlauf: alle bestanden.
|
||||||
|
- Drei Python-Guards: readback nach verlorener Startantwort ohne erneuten Start,
|
||||||
|
Sourceänderung verweigert, fehlender nativer Bericht verweigert: bestanden.
|
||||||
|
- Alle drei PowerShell-Bootstrapfragmente mit PowerShell-Parser geprüft.
|
||||||
|
|
||||||
|
Toolchain lokal im Entwicklungscontainer
|
||||||
|
`rust-discovery-windows-clock-full:local` aus dem bisherigen gecachten
|
||||||
|
Windows-Buildimage mit `mingw-w64-tools` und `clang`. `build.rs` verlangt für
|
||||||
|
Windows derzeit genau x86-64/GNU; MSVC und andere Architekturen sind nicht
|
||||||
|
qualifiziert. Compiler-/Containerprüfungen ersetzen keine tatsächliche
|
||||||
|
Windows-Ausführung. Native Ergebnisse werden getrennt im Projekt ergänzt.
|
||||||
|
|
||||||
|
## Native Zwischenstände: keine Clock-Abnahme
|
||||||
|
|
||||||
|
Der Root-Runner hat drei getrennte Fälle durchgeführt und die Belege privat
|
||||||
|
unter `devstate/windows-client/clock-readiness/` erhalten:
|
||||||
|
|
||||||
|
- `995eb9c1-e1f4-4b17-85b4-5976e9e362e6`: vor Upload/Diensterstellung
|
||||||
|
verweigert. Die ACL-Prüfung berücksichtigte das automatisch ergänzte reine
|
||||||
|
Synchronize-Recht nicht. Tatsächlicher Readback: Rootbesitzer Administrators,
|
||||||
|
nur SYSTEM/Administrators FullControl und LocalService ReadExecute+Synchronize,
|
||||||
|
kein Hilfsdienst, kein Remote-Fall und keine Dateien. Danach wurde nur dieses
|
||||||
|
zusätzliche Nichtschreibrecht im engen ACL-Maskenvertrag zugelassen.
|
||||||
|
- `89b3e688-50ae-4cbd-b519-16a379aa6424`: Hilfsdienststart scheiterte mit
|
||||||
|
behandeltem1066, kein Ergebnisbericht. Derselbe Fall wurde ausschließlich
|
||||||
|
gelesen und sein exakt gebundener gestoppter Hilfsdienst entfernt. Ursache
|
||||||
|
noch nicht durch einen spezifischen Fehlercode belegt.
|
||||||
|
- `513fb6df-df3b-43a2-bada-a0f7bb939f54`: nach Erweiterung um tatsächliche
|
||||||
|
Tokenfelder wurde kein Ergebnisbericht erzeugt; Dienstexit1067. Nur die eigene
|
||||||
|
ApplicationError-Metadatenabfrage belegte Exception `c0000005` im eigenen
|
||||||
|
`WindowsClockReadiness.exe` um2026-11-13T23:52:57.3579204Z. Auch dieser exakt
|
||||||
|
gebundene gestoppte Hilfsdienst wurde im Readback entfernt. Das ist ein
|
||||||
|
tatsächlicher nativer Fehler, kein DLL-/Zugriffs-/Zeitstatus-Erfolgsnachweis.
|
||||||
|
|
||||||
|
Die danach vorbereitete Probe schreibt den begrenzten Tokenbeleg bereits vor dem
|
||||||
|
RPC dauerhaft und führt numerische SCM-Stufen für behandelte Fehler. Der konkrete Compiler-TLS-Fehler wurde danach lokalisiert und behoben (unten).
|
||||||
|
Authentifizierte Serveridentitätsbindung bleibt offen; Windows-Jobclock
|
||||||
|
bleibt unqualifiziert und das Jobgate geschlossen. Die permanenten Agenten,
|
||||||
|
Geräteidentitäten, Zeitdienste und Cloudserver wurden von diesen ausschließlich
|
||||||
|
eigenen Readinesshilfsdiensten nicht verändert.
|
||||||
|
|
||||||
|
Der zusätzliche eigene Fehleroffset `0x48b4e4` ließ sich mit der exakten
|
||||||
|
EXE9be65748… und ImageBase`0x140000000` lokal mittels MinGW-addr2line auf
|
||||||
|
`release_allocations()` abbilden. Disassembly zeigt dort den Zugriff auf eine
|
||||||
|
NULL-Compiler-TLS-Basis des SCM-Threads. Der Korrekturbuild ersetzt ausschließlich
|
||||||
|
diesen `_Thread_local`-Allocatorzustand durch `InitOnceExecuteOnce`/`TlsAlloc`
|
||||||
|
und eine pro synchronem Aufruf über `TlsSetValue` gebundene, geprüfte Arena.
|
||||||
|
Aufrufende Threads ohne Arena erhalten keine Allokation; nach Cleanup wird der
|
||||||
|
Pointer gelöscht. Endpoint, RPC-Authentifizierung und IDL wurden dafür nicht
|
||||||
|
abgeschwächt. Die begrenzte Tokenprobe wird vorher dauerhaft geschrieben.
|
||||||
|
Dieser korrigierte Build wurde erfolgreich crossgebaut; die drei Rusttests,
|
||||||
|
drei Runnerguards und PowerShellparser liefen erneut erfolgreich. Der native Nachweis folgt im nächsten Absatz.
|
||||||
|
|
||||||
|
Native Korrekturprobe `ecf04ebb-23e4-48da-b324-56d98460cd64`, EXE
|
||||||
|
`4219054b8c51462458ab36fcb0eee3ad5e6905e4725621e6f5103c3e0eca9f4f`:
|
||||||
|
tatsächlich ausgeführt, zwei Statusabrufe, dauerhafte Token- und Ergebnisberichte,
|
||||||
|
Hilfsdienst danach entfernt. Beide Abrufe liefern RPC1722 (`CLOCK_UNSUPPORTED`),
|
||||||
|
keinen Zeitstatus und `clock_ready=false`; gemessene Dauer3,6513ms und0,2029ms.
|
||||||
|
Damit ist der Compiler-TLS-Absturz für diese Strecke nativ behoben, aber kein
|
||||||
|
Zeitvertrauen belegt. Das echte Diensttoken besitzt SID`S-1-5-19`, keine aktivierte
|
||||||
|
Administratormitgliedschaft und keine SYSTEM-Identität, dennoch
|
||||||
|
`TokenIsElevated=1`/`TokenElevationType=Default(1)`. Der rohe Elevationswert darf
|
||||||
|
nicht als gleichwertige Administratorzugehörigkeitsprüfung verwendet werden.
|
||||||
|
|
||||||
|
Eine anschließende enge Endpointprobe ist nun implementiert und lokal
|
||||||
|
crossqualifiziert: ausschließlich lokaler EPM, exakte Clock-UUID/Version4.1,
|
||||||
|
höchstens16 Einträge, nur aggregierte Transportanzahlen und Fehlercode. Keine
|
||||||
|
Endpointnamen, Annotationen oder Adressen verlassen die C-Grenze. Diese Probe
|
||||||
|
führt keinen ALPC-Statusaufruf aus und ersetzt keine Serveridentitätsprüfung.
|
||||||
|
Der entsprechende neue native Durchlauf ist noch offen.
|
||||||
|
|
||||||
|
## Implementierter nächster Kandidat: ALPC mit fester Server-SID
|
||||||
|
|
||||||
|
`NativeClock::new()` verwendet im aktuellen Quellstand ausschließlich einen
|
||||||
|
lokal per exakter Interface-UUID/Version gefundenen `ncalrpc`-Endpunkt. Die
|
||||||
|
verlangte Server-SID wird lokal als LocalService`S-1-5-19` erzeugt und mittels
|
||||||
|
`RPC_SECURITY_QOS_V3.Sid` und `MUTUAL_AUTH` fest gebunden. WINNT/PacketPrivacy,
|
||||||
|
Identify und der echte Prozesskontext bleiben erforderlich. Es gibt keinen
|
||||||
|
Status-Fallback auf Named Pipes und keine Übernahme einer Identität aus der
|
||||||
|
Endpointliste. Ein fremder registrierter Endpunkt kann so höchstens die
|
||||||
|
Bereitschaft verhindern. Dieser Vertrag trennt unterschiedliche Windowskonten;
|
||||||
|
ein Angreifer mit bereits denselben LocalService-Prozessrechten gehört nicht
|
||||||
|
zu einer neu behaupteten Prozessisolation. Der zuvor dokumentierte Named-Pipe-
|
||||||
|
Abruf bleibt eine getrennte Diagnose und liefert selbst bei geeignetem Status
|
||||||
|
immer `trusted=false`/`CLOCK_SERVER_IDENTITY_UNQUALIFIED`.
|
||||||
|
|
||||||
|
Da Windows die synchrone RPC-Timeout-/Cancel-API für `ncalrpc` nicht entsprechend
|
||||||
|
unterstützt, begrenzt ein einziger prozessweiter RPC-Worker den Aufrufer. Er
|
||||||
|
verwendet einen Kanal mit Kapazität1 und maximal1s Antwortwartezeit. Ein Timeout
|
||||||
|
vergiftet diesen Worker dauerhaft: keine Ersatzthreads, kein blindes Wiederholen,
|
||||||
|
kein Rückfall auf Named Pipes. Selbst bei einem hängenden read-only RPC existiert
|
||||||
|
höchstens ein solcher Worker; die Agenten-/Telemetriearbeit kehrt mit
|
||||||
|
`CLOCK_UNTRUSTED` zurück. Rekonstruktion eines `NativeClock`-Objekts setzt diesen
|
||||||
|
Zustand nicht zurück. Parallelaufrufe bei belegtem Worker werden verweigert.
|
||||||
|
[RPC-Cancel-Grenzen](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpccancelthreadex).
|
||||||
|
|
||||||
|
Dieser Kandidat wurde erfolgreich für WindowsGNU crossgebaut. Fünf lokale
|
||||||
|
Rusttests bestehen, einschließlich Timeout und nachfolgend verweigerter zweiter
|
||||||
|
RPC-Wirkung sowie unverändert geschlossenem Qualifikationsgate; die früheren
|
||||||
|
drei Clocktests bleiben erhalten. Vier Runnerguards bestehen, zusätzlich
|
||||||
|
Rohstatusbereitschaft ohne Adapterqualifikation verweigert produktive Bereitschaft. Native Nachweise für
|
||||||
|
ALPC-Verfügbarkeit, feste SID-Bindung und positive Zeitbereitschaft stehen aus.
|
||||||
|
Das ist weiterhin keine Windows-Jobclock-Abnahme.
|
||||||
|
|
||||||
|
Ein eigener Bootstrap-Readback des Root-Agenten bestätigte für W32Time
|
||||||
|
`Stopped`, Startart`Manual`, KontoLocalService`S-1-5-19` und PID0. Die
|
||||||
|
RPC1722-Werte der korrigierten Probe sind damit konsistent. Der Zeitdienst wurde
|
||||||
|
für diese Readinessstrecke nicht gestartet oder umkonfiguriert. Ein entsprechender
|
||||||
|
eng begrenzter Start des bestehenden Dienstes bleibt bis zur hierfür vom
|
||||||
|
Root-Agenten angefragten Benutzerentscheidung ausgesetzt. Der neue
|
||||||
|
ALPC-/SID-Kandidat wurde deshalb noch nicht nativ ausgeführt.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Windows-Client: Abnahmegates
|
# Windows-Client: Abnahmegates
|
||||||
|
|
||||||
Stand 2026-11-13, Spezifikation 1.15. Der Windows-11-x64-Gast ist ein eigenes
|
Stand 2026-11-14, Spezifikation 1.15. Der Windows-11-x64-Gast ist ein eigenes
|
||||||
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
||||||
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
|
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
|
||||||
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
|
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
|
||||||
@@ -11,9 +11,9 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht
|
|||||||
| Passiver Client | SCM-Dienst, Service-SID/ACLs, Enrollment/mTLS/WSS, Inventar mit Quelle/Zeit, Heartbeats und Mandantentrennung nativ bestanden; sieben native Rusttests. | Bestehende Identität und Telemetriehistorie bei allen weiteren Schritten erhalten. |
|
| Passiver Client | SCM-Dienst, Service-SID/ACLs, Enrollment/mTLS/WSS, Inventar mit Quelle/Zeit, Heartbeats und Mandantentrennung nativ bestanden; sieben native Rusttests. | Bestehende Identität und Telemetriehistorie bei allen weiteren Schritten erhalten. |
|
||||||
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
|
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
|
||||||
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
|
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
|
||||||
| Signierter Jobkern | Gemeinsamer Core und Linuxadapter implementiert; native Core-Unittests zuerst Linux (25), dann Windows (24) bestanden. Bestehender Windows-Dienst bleibt passiv und verweigert Jobs/Grants. | Native Dienstintegration, vertrauenswürdige Uhr, erhaltende Journalmigration und vollständige Startgrenze qualifizieren. Unit-Fixturen ersetzen keinen tatsächlichen Jobnachweis. |
|
| Signierter Jobkern | Gemeinsamer Core/Helper-Sync und atomare Outcomes nativ zuerst Linux, dann Windows geprüft; letzter Fixturelauf76/54. Default-Windowsdienst mit additiver Journalmigration erhaltend als LocalService aktualisiert; native Unitqualifikation12+6. Jobs bleiben deaktiviert, kein Binding/Ledger angelegt. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Passive Migration und Unit-Fixturen ersetzen keinen Jobnachweis. |
|
||||||
| PowerShell | Noch kein Executor oder freigegebener Interpreter. Server/UI lösen derzeit Linuxvarianten auf. | Exakte Windows-PowerShell-5.1-Bytes, Ausgabeencoding, Prozessgrenzen und unprivilegierte Ausführungsidentität binden. Erst nach vollständigem Antrag und tatsächlichem WebUI-Klick ausführen. |
|
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. |
|
||||||
| Privilegierte Aktionen | Kein Windows-Helper, keine Named-Pipe-Aktionsschnittstelle. | Eigenständiger restriktiver Helper mit geprüfter Pipe-Identität und unabhängiger Signatur-/Plan-/Grantprüfung; keine SYSTEM-Netzwerkkomponente. |
|
| Privilegierte Aktionen | Featureisolierte SYSTEM-Helper-/Named-Pipe-Quelle mit eigener Policy und unabhängigem Sync vorbereitet; keine Installation oder native Peer-/Wirkungsabnahme. | Gegenseitige tatsächliche SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen; erst danach eng erlaubte Systemaktion. |
|
||||||
| Pakete/Dienste/Logs | Noch keine native Windows-Aktionsabnahme. | Begrenzte geprüfte MSI-/EXE-Rezepte, Dienst-/Eventlogadapter und unabhängige Nachbedingungen. Keine allgemeinen Installershellstrings oder impliziten Reboots. |
|
| Pakete/Dienste/Logs | Noch keine native Windows-Aktionsabnahme. | Begrenzte geprüfte MSI-/EXE-Rezepte, Dienst-/Eventlogadapter und unabhängige Nachbedingungen. Keine allgemeinen Installershellstrings oder impliziten Reboots. |
|
||||||
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
|
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
|
||||||
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
|
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Focused readback/error gates for the LocalService readiness bootstrap. No VM."""
|
||||||
|
import hashlib
|
||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
ROOT=pathlib.Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'deploy/windows'))
|
||||||
|
import clock_readiness as clock
|
||||||
|
|
||||||
|
|
||||||
|
class ReadinessGuards(unittest.TestCase):
|
||||||
|
def case(self,root):
|
||||||
|
ident='11111111-1111-4111-8111-111111111111'
|
||||||
|
folder=root/ident;folder.mkdir(mode=0o700)
|
||||||
|
clock.save(folder,'intent.json',dict(id=ident,binary='a'*64,source=hashlib.sha256(clock.SCRIPT.encode()).hexdigest(),no_jobs=True))
|
||||||
|
return ident,folder
|
||||||
|
|
||||||
|
def result(self,ident,trusted=False):
|
||||||
|
return dict(id=ident,native_report=dict(case_id=ident,token_sid='S-1-5-19',elevated=False,read_only=True,
|
||||||
|
samples=[dict(trusted=trusted,reason='CLOCK_PERMISSION_DENIED',rpc_code=5)]*2),service_removed=True,no_jobs=True)
|
||||||
|
|
||||||
|
def test_lost_start_reply_only_readbacks_and_retains_untrusted_evidence(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root=pathlib.Path(tmp);ident,folder=self.case(root);calls=[]
|
||||||
|
def remote(script,payload,**kwargs):
|
||||||
|
self.assertEqual(script,clock.LAUNCH);calls.append(payload['action']);return self.result(ident)
|
||||||
|
with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',side_effect=remote),patch('builtins.print'):
|
||||||
|
clock.main();clock.main()
|
||||||
|
self.assertEqual(calls,['readback','readback'])
|
||||||
|
report=clock.cb.contract.protected_json(folder/'result.json')
|
||||||
|
self.assertTrue(report['native_execution_verified']);self.assertFalse(report['clock_ready'])
|
||||||
|
self.assertFalse((folder/'start-intent.json').exists())
|
||||||
|
|
||||||
|
def test_good_raw_status_cannot_claim_production_clock_without_qualification(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root=pathlib.Path(tmp);ident,folder=self.case(root)
|
||||||
|
report=self.result(ident,trusted=True)
|
||||||
|
for sample in report['native_report']['samples']:sample['adapter_qualified']=False
|
||||||
|
with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',return_value=report),patch('builtins.print'):
|
||||||
|
clock.main()
|
||||||
|
result=clock.cb.contract.protected_json(folder/'result.json')
|
||||||
|
self.assertTrue(result['diagnostic_status_ready']);self.assertFalse(result['adapter_qualified']);self.assertFalse(result['clock_ready'])
|
||||||
|
|
||||||
|
def test_changed_source_cannot_resume_same_case(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root=pathlib.Path(tmp);ident,_=self.case(root)
|
||||||
|
with patch.object(clock,'STATE',root),patch.object(clock,'SCRIPT',clock.SCRIPT+'\n'),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',side_effect=AssertionError('no remote call')):
|
||||||
|
with self.assertRaisesRegex(RuntimeError,'QUALIFIED_SOURCE_CHANGED'):clock.main()
|
||||||
|
|
||||||
|
def test_missing_native_report_cannot_claim_qualification(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root=pathlib.Path(tmp);ident,folder=self.case(root)
|
||||||
|
with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',return_value=dict(native_report=None,service_removed=True)):
|
||||||
|
with self.assertRaisesRegex(RuntimeError,'INCOMPLETE'):clock.main()
|
||||||
|
self.assertFalse((folder/'result.json').exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
Reference in New Issue
Block a user