Compare commits

..
29 changed files with 3483 additions and 60 deletions
+1 -1
View File
@@ -39,4 +39,4 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
@@ -157,6 +157,7 @@ mod service {
let clock = super::clock::NativeClock::new();
STAGE.store(30, Ordering::SeqCst);
let pipe = super::clock::named_pipe_diagnostic();
let status_rpc = super::clock::status_rpc_diagnostic();
let first = clock.report();
std::thread::sleep(Duration::from_millis(750));
STAGE.store(31, Ordering::SeqCst);
@@ -164,7 +165,7 @@ mod service {
let identity_controls = super::clock::identity_controls();
STAGE.store(40, Ordering::SeqCst);
let data = serde_json::to_vec_pretty(
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"status_rpc_diagnostic":status_rpc,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
)?;
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
STAGE.store(41, Ordering::SeqCst);
@@ -259,6 +260,6 @@ fn main() -> anyhow::Result<()> {
fn main() {
println!(
"{}",
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"status_rpc_diagnostic":clock::status_rpc_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
);
}
+46 -6
View File
@@ -71,20 +71,47 @@ typedef struct {
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
* leave C. A zero native return is meaningful only when return_present is1.
* Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena,
* 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped,
* 90 contained RPC/SEH exception. Never used by the clock trust evaluator.
*/
typedef struct {
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
uint32_t status_present, ul_size, c_entries, p_entries_present;
} RmmClockTrace;
_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI");
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace) {
RMM_W32TIME_STATUS *status = NULL;
unsigned long result = 0;
Arena arena = {0};
if (trace) trace->stage = 50;
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
if (!result) {
RpcTryExcept {
if (trace) trace->stage = 60;
result = RmmW32TimeQueryStatus(binding, &status);
if (trace) {
trace->stage = 61; trace->native_rpc_return_present = 1;
trace->native_rpc_return = result;
}
if (!result) {
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries)
if (trace) {
trace->stage = 62; trace->status_present = status != NULL;
if (status) {
trace->ul_size = status->ulSize; trace->c_entries = status->cEntries;
trace->p_entries_present = status->pEntries != NULL;
}
}
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) {
if (trace) trace->stage = 70;
result = RPC_X_BAD_STUB_DATA;
}
else {
if (trace) trace->stage = 80;
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
out->state = status->ulLcState; out->flags = status->ulTSFlags;
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
@@ -95,21 +122,24 @@ static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
}
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
result = RpcExceptionCode();
if (trace) {trace->stage = 90; trace->rpc_exception = result;}
} RpcEndExcept
release_allocations(&arena);
TlsSetValue(arena_index, NULL);
}
return result;
}
uint32_t rmm_clock_query(RmmClockStatus *out) {
static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace) {
RPC_WSTR text = NULL;
RPC_BINDING_HANDLE binding = NULL;
RPC_SECURITY_QOS qos = {0};
unsigned long result;
memset(out, 0, sizeof(*out));
if (trace) trace->stage = 10;
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
if (result) return result;
if (trace) trace->stage = 20;
result = RpcBindingFromStringBindingW(text, &binding);
RpcStringFreeW(&text);
if (result) return result;
@@ -117,13 +147,23 @@ uint32_t rmm_clock_query(RmmClockStatus *out) {
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
if (trace) trace->stage = 30;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
if (!result) result = invoke_status(binding, out);
if (!result) {
if (trace) trace->stage = 40;
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
}
if (!result) result = invoke_status(binding, out, trace);
RpcBindingFree(&binding);
return result;
}
uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL); }
uint32_t rmm_clock_query_trace(RmmClockTrace *trace) {
RmmClockStatus ignored = {0};
memset(trace, 0, sizeof(*trace));
return pipe_query(&ignored, trace);
}
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
* The expected SID is fixed locally, never adopted from endpoint metadata.
*/
@@ -188,7 +228,7 @@ static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
qos.ServerSecurityDescriptor = &descriptor;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
if (!result) result = invoke_status(binding, out);
if (!result) result = invoke_status(binding, out, NULL);
}
RpcBindingFree(&binding);
break; /* no retry, alternate identity, endpoint or weaker transport */
+6 -1
View File
@@ -31,6 +31,11 @@ typedef struct {
unsigned long cEntries;
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
} RMM_W32TIME_STATUS;
/* Microsoft declares PW32TIME_STATUS_INFO separately. Keep the inner pointer
* explicitly unique; the out parameter's outer pointer defaults to ref.
* WIDL 7 propagates a parameter-level [ref] through a direct ** declaration.
*/
typedef [unique] RMM_W32TIME_STATUS *RMM_PW32TIME_STATUS;
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
interface RmmW32Time {
unsigned long RmmUnusedSlot0([in] handle_t binding);
@@ -39,5 +44,5 @@ interface RmmW32Time {
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);
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out] RMM_PW32TIME_STATUS *status);
}
+82
View File
@@ -259,6 +259,87 @@ pub fn named_pipe_diagnostic() -> ClockReport {
}
.report()
}
/// Diagnostic-only ABI captured before the existing C layout guard. Presence
/// flags are numeric0/1; no remote pointers, names or returned entries escape.
#[derive(Clone, Copy, Debug, Default, Serialize)]
#[repr(C)]
pub struct StatusRpcTrace {
pub stage: u32,
pub native_rpc_return: u32,
pub native_rpc_return_present: u32,
pub rpc_exception: u32,
pub status_present: u32,
pub ul_size: u32,
pub c_entries: u32,
pub p_entries_present: u32,
}
#[derive(Debug, Serialize)]
pub struct StatusRpcDiagnostic {
pub rpc_code: u32,
pub independent_call: bool,
pub trace: Option<StatusRpcTrace>,
pub diagnostic_only: bool,
pub adapter_qualified: bool,
pub trusted: bool,
}
/// The fixed authenticated named-pipe call is observed separately. It never
/// selects a production transport or supplies a trusted timestamp. One worker,
/// one outstanding call and no replacement/retry after a local timeout.
pub fn status_rpc_diagnostic() -> StatusRpcDiagnostic {
#[cfg(windows)]
let (rpc_code, trace) = {
type Reply = std::sync::mpsc::SyncSender<(u32, StatusRpcTrace)>;
type Requests = std::sync::mpsc::SyncSender<Reply>;
static WORKER: std::sync::OnceLock<Mutex<Option<Requests>>> = std::sync::OnceLock::new();
let worker = WORKER.get_or_init(|| {
let (sender, receiver) = std::sync::mpsc::sync_channel::<Reply>(1);
let created = std::thread::Builder::new()
.name("rmm-clock-status-diag".into())
.spawn(move || {
#[link(name = "rmm_clock_rpc", kind = "static")]
#[link(name = "rpcrt4")]
#[link(name = "advapi32")]
unsafe extern "C" {
fn rmm_clock_query_trace(trace: *mut StatusRpcTrace) -> u32;
}
while let Ok(reply) = receiver.recv() {
let mut trace = StatusRpcTrace::default();
// SAFETY: fixed8*u32 C ABI; SEH stays contained inside C.
let code = unsafe { rmm_clock_query_trace(&mut trace) };
let _ = reply.send((code, trace));
}
})
.is_ok();
Mutex::new(created.then_some(sender))
});
if let Ok(mut worker) = worker.try_lock() {
let (reply, receiver) = std::sync::mpsc::sync_channel(1);
let sent = worker
.as_ref()
.is_some_and(|sender| sender.try_send(reply).is_ok());
if sent
&& let Ok((code, trace)) = receiver.recv_timeout(std::time::Duration::from_secs(2))
{
(code, Some(trace))
} else {
*worker = None;
(1818, None)
}
} else {
(170, None)
}
};
#[cfg(not(windows))]
let (rpc_code, trace) = (50, None);
StatusRpcDiagnostic {
rpc_code,
independent_call: true,
trace,
diagnostic_only: true,
adapter_qualified: false,
trusted: false,
}
}
/// Read-only negative controls for the separate native readiness program.
/// Neither control can produce clock authority, even if the OS accepts it.
/// Rejection without a successful genuine status query is not identity proof.
@@ -443,6 +524,7 @@ mod tests {
}
#[test]
fn production_clock_stays_closed_until_native_adapter_qualification() {
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
assert_eq!(
NativeClock::new().now().unwrap_err().to_string(),
"CLOCK_ADAPTER_UNQUALIFIED"
+170 -5
View File
@@ -16,16 +16,67 @@ pub const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents";
pub const DB: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite";
const ACTOR_RW: u32 = 0x0012_019f;
const SCHEMA:&str="CREATE TABLE IF NOT EXISTS system_intent_meta(id INTEGER PRIMARY KEY CHECK(id=1),file_identity BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intent_mirrors(id TEXT PRIMARY KEY,outcome_sha256 TEXT NOT NULL,mirror_observed_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS system_intent_denial_resumes(id TEXT NOT NULL,agent_instance TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(id,agent_instance));
CREATE TRIGGER IF NOT EXISTS system_intents_no_delete BEFORE DELETE ON system_intents BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR NOT ((NEW.phase=OLD.phase AND NEW.cancel_requested=1 AND OLD.cancel_requested IN (0,1)) OR (OLD.phase='prepared' AND NEW.phase IN ('known_no_dispatch','may_have_dispatched') AND NEW.cancel_requested=OLD.cancel_requested)) BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_delete BEFORE DELETE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_update BEFORE UPDATE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_delete BEFORE DELETE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_update BEFORE UPDATE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;";
const LEGACY_INTENTS_TABLE: &str = "CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));";
const LEGACY_MONOTONIC: &str = "CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;";
const CLAIM_RESUME: &str = "INSERT OR IGNORE INTO system_intent_denial_resumes(id,agent_instance,observed_at) VALUES(?1,?2,?3)";
fn initialize_schema(db: &mut Connection) -> Result<()> {
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='system_intents')",
[],
|r| r.get(0),
)?;
if exists {
let columns = db
.prepare("PRAGMA table_info(system_intents)")?
.query_map([], |r| r.get::<_, String>(1))?
.collect::<rusqlite::Result<Vec<_>>>()?;
if !columns.iter().any(|name| name == "cancel_requested") {
ensure!(
columns
== [
"id", "job", "attempt", "grant_id", "body", "digest", "phase"
],
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let old:String=db.query_row("SELECT sql FROM sqlite_master WHERE type='trigger' AND name='system_intents_monotonic'",[],|r|r.get(0))?;
let normalize = |s: &str| {
s.replace("IF NOT EXISTS ", "")
.trim_end_matches(';')
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
};
ensure!(
normalize(&old) == normalize(LEGACY_MONOTONIC),
"SYSTEM_INTENT_LEGACY_TRIGGER"
);
let table: String = db.query_row(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='system_intents'",
[],
|r| r.get(0),
)?;
ensure!(
normalize(&table) == normalize(LEGACY_INTENTS_TABLE),
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute_batch("ALTER TABLE system_intents ADD COLUMN cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1));DROP TRIGGER system_intents_monotonic;")?;
tx.execute_batch(SCHEMA)?;
tx.commit()?;
}
}
db.execute_batch(SCHEMA)?;
Ok(())
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Intent {
@@ -148,14 +199,14 @@ impl Store {
} else {
OpenFlags::SQLITE_OPEN_READ_ONLY
};
let db = Connection::open_with_flags(DB, flags)?;
let mut db = Connection::open_with_flags(DB, flags)?;
db.busy_timeout(Duration::from_millis(250))?;
if write {
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
let mode: String = db.query_row("PRAGMA journal_mode=PERSIST", [], |r| r.get(0))?;
ensure!(mode == "persist", "SYSTEM_INTENT_JOURNAL_MODE");
db.execute_batch("PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;PRAGMA journal_size_limit=1048576;")?;
db.execute_batch(SCHEMA)?;
initialize_schema(&mut db)?;
db.execute(
"INSERT OR IGNORE INTO system_intent_meta VALUES(1,?1)",
[serde_json::to_vec(&identity)?],
@@ -241,10 +292,60 @@ impl Store {
}
pub fn cancel_before_dispatch(&mut self, id: Uuid) -> Result<Phase> {
self.check()?;
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[id.to_string()],
)?;
let (_, phase) = advance(&mut self.db, id, Phase::KnownNoDispatch)?;
self.check()?;
Ok(phase)
}
/// Denial only. Original phase/request/anchor never changes, even after IPC.
pub fn deny(&mut self, original: &Request, boot: Uuid) -> Result<()> {
self.check()?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = self.by_grant(permit.grant_id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[intent.id.to_string()],
)?;
self.check()
}
/// Open a new ordinary RO connection for each observation. No long-lived
/// SQLite read transaction or immutable-mode shortcut may hide actor denial.
pub fn require_not_denied(
original: &Request,
boot: Uuid,
generation: u64,
policy: &str,
binary: &str,
) -> Result<()> {
let mut store = Self::open(false)?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = store.by_grant(permit.grant_id)?;
let (_, phase) = store.load(intent.id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot
&& intent.connection_generation == generation
&& phase == Phase::MayHaveDispatched
&& intent.policy_sha256 == policy
&& intent.helper_binary_sha256 == binary,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
let denied: i64 = store.db.query_row(
"SELECT cancel_requested FROM system_intents WHERE id=?1",
[intent.id.to_string()],
|r| r.get(0),
)?;
ensure!(denied == 0, "SYSTEM_MSI_CANCELLED_OR_FENCED");
store.check()
}
pub fn pending(&self) -> Result<Vec<Intent>> {
let mut rows=self.db.prepare("SELECT i.id FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id) ORDER BY i.rowid LIMIT 2")?;
let ids = rows
@@ -356,7 +457,7 @@ mod tests {
let dispatched = Uuid::new_v4();
for id in [cancelled, dispatched] {
db.execute(
"INSERT INTO system_intents VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
"INSERT INTO system_intents(id,job,attempt,grant_id,body,digest,phase) VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
[id.to_string()],
)
.unwrap();
@@ -377,6 +478,29 @@ mod tests {
advance(&mut db, dispatched, Phase::KnownNoDispatch).unwrap(),
(0, Phase::MayHaveDispatched)
);
for _ in 0..2 {
db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[dispatched.to_string()],
)
.unwrap();
}
assert_eq!(
db.query_row(
"SELECT phase,cancel_requested FROM system_intents WHERE id=?1",
[dispatched.to_string()],
|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
)
.unwrap(),
("may_have_dispatched".into(), 1)
);
assert!(
db.execute(
"UPDATE system_intents SET cancel_requested=0 WHERE id=?1",
[dispatched.to_string()]
)
.is_err()
);
assert!(
db.execute(
"UPDATE system_intents SET phase='prepared' WHERE id=?1",
@@ -411,4 +535,45 @@ mod tests {
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 1);
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 0);
}
#[test]
fn additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger() {
let mut db = Connection::open_in_memory().unwrap();
db.execute_batch(LEGACY_INTENTS_TABLE).unwrap();
db.execute_batch(LEGACY_MONOTONIC).unwrap();
db.execute("INSERT INTO system_intents VALUES('id','job','attempt','grant',x'0102','original','may_have_dispatched')",[]).unwrap();
initialize_schema(&mut db).unwrap();
initialize_schema(&mut db).unwrap();
assert_eq!(
db.query_row(
"SELECT body,digest,phase,cancel_requested FROM system_intents",
[],
|r| Ok((
r.get::<_, Vec<u8>>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?
))
)
.unwrap(),
(
vec![1, 2],
"original".into(),
"may_have_dispatched".into(),
0
)
);
db.execute("UPDATE system_intents SET cancel_requested=1", [])
.unwrap();
assert!(
db.execute("UPDATE system_intents SET body=x'03'", [])
.is_err()
);
assert!(
db.execute("UPDATE system_intents SET cancel_requested=0", [])
.is_err()
);
let mut foreign = Connection::open_in_memory().unwrap();
foreign.execute_batch("CREATE TABLE system_intents(id,job,attempt,grant_id,body,digest,phase);CREATE TRIGGER system_intents_monotonic BEFORE UPDATE ON system_intents BEGIN SELECT 1;END;").unwrap();
assert!(initialize_schema(&mut foreign).is_err());
}
}
+113 -24
View File
@@ -7,6 +7,7 @@ use rmm_agent_core::{
};
use rmm_domain::jobs::hash;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha2::{Digest, Sha256};
use std::{
ffi::c_void,
fs::File,
@@ -29,7 +30,13 @@ use windows_sys::Win32::{
};
pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper";
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v1";
// Framing v2 is deliberately a separate endpoint. Old peers cannot send a
// v1 call to this server or interpret the drain receipt as another reply.
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
const FRAME_HEADER_LEN: usize = 12;
const DRAIN_RECEIPT_LEN: usize = 56;
pub const FRAME_LIMIT: usize = 1024 * 1024;
pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4
const READ_MASK: u32 = 0x0012_00a9;
@@ -44,6 +51,7 @@ pub enum Stage {
ClientSendFrame,
ClientReadReply,
ClientReplyBinding,
ClientDrainReceipt,
ClientReport,
ServerConnect,
ServerReadHeader,
@@ -54,6 +62,7 @@ pub enum Stage {
ServerCallBinding,
ServerRecheckPeer,
ServerReply,
ServerDrainReceipt,
Unclassified,
}
impl Stage {
@@ -66,6 +75,7 @@ impl Stage {
Self::ClientSendFrame => "client_send_frame",
Self::ClientReadReply => "client_read_reply",
Self::ClientReplyBinding => "client_reply_binding",
Self::ClientDrainReceipt => "client_drain_receipt",
Self::ClientReport => "client_report",
Self::ServerConnect => "server_connect",
Self::ServerReadHeader => "server_read_header",
@@ -76,6 +86,7 @@ impl Stage {
Self::ServerCallBinding => "server_call_binding",
Self::ServerRecheckPeer => "server_recheck_peer",
Self::ServerReply => "server_reply",
Self::ServerDrainReceipt => "server_drain_receipt",
Self::Unclassified => "unclassified",
}
}
@@ -123,6 +134,8 @@ fn known_code(text: &str) -> Option<&'static str> {
"HELPER_FRAME_CAPACITY",
"HELPER_FRAME_EMPTY",
"HELPER_FRAME_LENGTH",
"HELPER_FRAME_VERSION",
"HELPER_DRAIN_RECEIPT",
"HELPER_HANDLE",
"HELPER_IMAGE_PARENT",
"HELPER_IMAGE_SIZE",
@@ -1189,27 +1202,60 @@ fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY");
Ok(writer.0)
}
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
let mut bytes = encode(value)?;
let mut header = u32::try_from(bytes.len())?.to_be_bytes();
transfer(pipe, &mut header, true, deadline)?;
transfer(pipe, &mut bytes, true, deadline)
fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
let mut header = [0; FRAME_HEADER_LEN];
header[..8].copy_from_slice(&FRAME_TAG);
header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes());
Ok(header)
}
fn frame_length(header: [u8; 4]) -> Result<usize> {
let len = u32::from_be_bytes(header) as usize;
fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
let mut header = frame_header(bytes.len())?;
transfer(pipe, &mut header, true, deadline)?;
transfer(pipe, bytes, true, deadline)
}
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
send_bytes(pipe, &mut encode(value)?, deadline)
}
fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
ensure!(header[..8] == FRAME_TAG, "HELPER_FRAME_VERSION");
let len = u32::from_be_bytes(header[8..].try_into()?) as usize;
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
Ok(len)
}
fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
let mut header = [0u8; 4];
let mut header = [0u8; FRAME_HEADER_LEN];
transfer(pipe, &mut header, false, deadline)?;
frame_length(header)
}
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
let mut bytes = vec![0u8; len];
transfer(pipe, &mut bytes, false, deadline)?;
Ok(serde_json::from_slice(&bytes)?)
Ok(bytes)
}
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?)
}
// This fixed-size receipt only acknowledges receipt of these transport bytes.
// It never acknowledges durable evidence, clears state, or permits an effect.
fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
let mut receipt = [0; DRAIN_RECEIPT_LEN];
receipt[..8].copy_from_slice(&DRAIN_TAG);
receipt[8..24].copy_from_slice(challenge.as_bytes());
receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes));
receipt
}
fn verify_drain_receipt(
receipt: &[u8; DRAIN_RECEIPT_LEN],
challenge: Uuid,
reply_bytes: &[u8],
) -> Result<()> {
ensure!(
*receipt == drain_receipt(challenge, reply_bytes),
"HELPER_DRAIN_RECEIPT"
);
Ok(())
}
pub struct Server {
@@ -1305,13 +1351,24 @@ impl Server {
peer.check().context(Stage::ServerRecheckPeer)?;
Ok(Some(Received { call, peer }))
}
pub fn reply(&self, value: &Reply) -> Result<()> {
send(
self.pipe.as_raw_handle(),
value,
Instant::now() + Duration::from_secs(5),
)
.context(Stage::ServerReply)
pub fn reply(&self, value: &Reply, peer: &mut PeerProof) -> Result<()> {
// Do not disconnect after WriteFile merely copied bytes into a pipe
// buffer. Wait for a receipt from the same fully pinned peer within
// the original reply deadline, without an unbounded FlushFileBuffers.
let deadline = Instant::now() + Duration::from_secs(5);
peer.check().context(Stage::ServerRecheckPeer)?;
let mut bytes = encode(value).context(Stage::ServerReply)?;
send_bytes(self.pipe.as_raw_handle(), &mut bytes, deadline).context(Stage::ServerReply)?;
let mut receipt = [0; DRAIN_RECEIPT_LEN];
transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline)
.context(Stage::ServerDrainReceipt)?;
verify_drain_receipt(&receipt, value.challenge, &bytes)
.context(Stage::ServerDrainReceipt)?;
peer.check().context(Stage::ServerRecheckPeer)?;
if Instant::now() >= deadline {
return Err(anyhow::anyhow!("HELPER_PIPE_TIMEOUT")).context(Stage::ServerDrainReceipt);
}
Ok(())
}
pub fn disconnect(&self) {
unsafe {
@@ -1345,7 +1402,9 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
.context(Stage::ClientHelperPeer)?;
send(pipe.as_raw_handle(), call, deadline).context(Stage::ClientSendFrame)?;
let len = length(pipe.as_raw_handle(), deadline).context(Stage::ClientReadReply)?;
let reply: Reply = body(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
let reply_bytes =
body_bytes(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
let reply: Reply = serde_json::from_slice(&reply_bytes).context(Stage::ClientReadReply)?;
peer.check().context(Stage::ClientHelperPeer)?;
if !(reply.schema_version == 1
&& reply.challenge == call.challenge
@@ -1366,6 +1425,11 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
) {
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
}
// Only a complete, authenticated, bound and operation-checked reply gets
// this receipt. Hash the received bytes, never a JSON re-serialization.
let mut receipt = drain_receipt(call.challenge, &reply_bytes);
transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)
.context(Stage::ClientDrainReceipt)?;
Ok(reply)
}
@@ -1388,12 +1452,21 @@ mod tests {
#[test]
fn untrusted_lengths_are_rejected_before_body_allocation() {
for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] {
assert!(frame_length(n.to_be_bytes()).is_err());
let mut header = [0; FRAME_HEADER_LEN];
header[..8].copy_from_slice(&FRAME_TAG);
header[8..].copy_from_slice(&n.to_be_bytes());
assert!(frame_length(header).is_err());
assert!(frame_header(n as usize).is_err());
}
assert_eq!(
frame_length((FRAME_LIMIT as u32).to_be_bytes()).unwrap(),
FRAME_LIMIT
);
let header = frame_header(FRAME_LIMIT).unwrap();
assert_eq!(frame_length(header).unwrap(), FRAME_LIMIT);
// Neither a v1 length prefix nor another framing version is accepted.
let mut old = [0; FRAME_HEADER_LEN];
old[..4].copy_from_slice(&1u32.to_be_bytes());
assert!(frame_length(old).is_err());
let mut foreign = header;
foreign[7] = b'1';
assert!(frame_length(foreign).is_err());
}
#[test]
fn protocol_does_not_accept_a_shell_operation() {
@@ -1417,6 +1490,22 @@ mod tests {
assert_eq!(diagnostic(&caller).code, "UNCLASSIFIED_IO_OR_CODEC");
let remote = remote_denial(Stage::ClientReplyBinding, "caller-payload-private-marker");
assert_eq!(diagnostic(&remote).code, "UNCLASSIFIED_REMOTE_DENIAL");
let challenge = Uuid::from_u128(1);
let raw = br#"{"a":1,"b":2}"#;
let receipt = drain_receipt(challenge, raw);
assert!(verify_drain_receipt(&receipt, challenge, raw).is_ok());
// Same JSON meaning, different exact bytes must not drain this reply.
assert!(verify_drain_receipt(&receipt, challenge, br#"{"b":2,"a":1}"#).is_err());
assert!(verify_drain_receipt(&receipt, Uuid::from_u128(2), raw).is_err());
for offset in [0, 7, 8, 23, 24, DRAIN_RECEIPT_LEN - 1] {
let mut changed = receipt;
changed[offset] ^= 1;
let error = verify_drain_receipt(&changed, challenge, raw)
.unwrap_err()
.context(Stage::ServerDrainReceipt);
assert_eq!(diagnostic(&error).code, "HELPER_DRAIN_RECEIPT");
assert_eq!(diagnostic(&error).stage, "server_drain_receipt");
}
}
#[test]
fn reconfigured_service_cannot_adopt_an_old_running_identity() {
+130 -1
View File
@@ -470,6 +470,13 @@ fn verified_mirror_row(
Ok(outcome)
}
fn system_shape(job: &JobPayload) -> bool {
if job.action.windows_msi().is_some() {
return job.execution_identity == "system"
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
}
job.execution_identity == "system"
&& (1..=120).contains(&job.max_runtime_seconds)
&& (1..=65536).contains(&job.max_output_bytes)
@@ -487,7 +494,7 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
matches!(
outcome.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired" | "unknown"
) && !outcome.reboot_required
) && (job.action.windows_msi().is_some() || !outcome.reboot_required)
&& outcome
.stdout
.len()
@@ -496,6 +503,47 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
"SYSTEM_EXECUTE_OUTCOME_SCOPE"
);
if outcome.state == "succeeded" {
if let Some(m) = job.action.windows_msi() {
let e = &outcome.evidence;
let after: crate::package::Snapshot = serde_json::from_value(e["after"].clone())?;
let noop = e["already_desired"] == true;
ensure!(
job.action.validate()
&& e["provider"] == "windows.msi.fixture/1"
&& e["recipe_sha256"] == m.recipe_sha256
&& e["artifact_sha256"] == m.recipe.artifact.sha256
&& e["postconditions_passed"] == true
&& e["state"] == "succeeded"
&& e["exit_code"] == serde_json::to_value(outcome.exit_code)?
&& e["already_desired"].is_boolean()
&& !outcome.output_truncated
&& e["reboot_initiated"] == false
&& e["automatic_retry"] == false
&& after.desired(m),
"SYSTEM_MSI_POSTCONDITION_BINDING"
);
if noop {
let before: crate::package::Snapshot = serde_json::from_value(e["before"].clone())?;
ensure!(
outcome.exit_code.is_none()
&& !outcome.reboot_required
&& e["installer_process_started"] == false
&& e["transaction_started"] == false
&& e["installer_reboot_required"].is_null()
&& before.desired(m),
"SYSTEM_MSI_NOOP_BINDING"
);
} else {
ensure!(
matches!(outcome.exit_code, Some(0 | 3010))
&& e["installer_process_started"] == true
&& outcome.reboot_required == (outcome.exit_code == Some(3010))
&& e["installer_reboot_required"] == outcome.reboot_required,
"SYSTEM_MSI_EXIT_BINDING"
);
}
return Ok(());
}
let Action::SetServiceState { unit, state } = &job.action else {
anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED");
};
@@ -537,6 +585,43 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
.collect(),
}
}
#[cfg(test)]
pub(crate) fn msi_test_job() -> JobPayload {
use rmm_domain::windows_execution::*;
let recipe:WindowsMsiRecipe=serde_json::from_value(json!({"schema_version":1,"recipe_id":MSI_RECIPE_ID,"recipe_version":"1","platform":"windows","upgrade_code":MSI_UPGRADE_CODE,"architecture":"x64","context":"machine","command_profile":"fixture_quiet_no_reboot_v1","artifact":{"artifact_id":uuid::Uuid::from_u128(10),"sha256":"ab".repeat(32),"bytes":32768},"postcondition":{"product_code":MSI_PRODUCT_CODE,"product_version":MSI_VERSION,"payload_path":MSI_PAYLOAD,"payload_sha256":MSI_PAYLOAD_10_SHA256,"payload_bytes":33},"no_reboot":true})).unwrap();
let manifest = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe,
};
let now = chrono::Utc::now();
let id = uuid::Uuid::from_u128(1);
JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: Action::EnsurePackage {
provider: "msi".into(),
package: MSI_PACKAGE_ID.into(),
version: MSI_VERSION.into(),
architecture: "x64".into(),
recipe_version: "1".into(),
installation_context: "machine".into(),
recipe_id: Some(MSI_RECIPE_ID.into()),
apt_manifest: None,
windows_msi_manifest: Some(Box::new(manifest)),
},
execution_identity: "system".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(2),
max_runtime_seconds: 30,
max_output_bytes: 4096,
}
}
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
native::private_path(state, true)?;
let path = state.join(PROBE_FILE);
@@ -574,6 +659,50 @@ fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
mod tests {
use super::*;
#[test]
fn msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit() {
let job = msi_test_job();
assert!(system_shape(&job));
let m = job.action.windows_msi().unwrap();
let p = &m.recipe.postcondition;
let snapshot = crate::package::Snapshot {
product_code: p.product_code.clone(),
related_products: vec![p.product_code.clone()],
product_state: Some("5".into()),
product_version: Some(p.product_version.clone()),
payload_sha256: Some(p.payload_sha256.clone()),
payload_bytes: Some(p.payload_bytes),
..Default::default()
};
let mut out = Outcome {
state: "succeeded".into(),
exit_code: Some(3010),
reboot_required: true,
evidence: json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":true,"reboot_initiated":false,"automatic_retry":false,"already_desired":false,"state":"succeeded","exit_code":3010,"installer_process_started":true,"installer_reboot_required":true,"after":snapshot,"before":snapshot}),
..Outcome::unknown("")
};
assert!(checked_outcome(&job, &out).is_ok());
out.reboot_required = false;
assert!(checked_outcome(&job, &out).is_err());
out.reboot_required = true;
out.evidence["after"]["payload_sha256"] = "cd".repeat(32).into();
assert!(checked_outcome(&job, &out).is_err());
out.evidence["after"] = serde_json::to_value(&snapshot).unwrap();
out.evidence["already_desired"] = true.into();
out.evidence["exit_code"] = serde_json::Value::Null;
out.exit_code = None;
out.reboot_required = false;
out.evidence["installer_reboot_required"] = serde_json::Value::Null;
out.evidence["installer_process_started"] = false.into();
out.evidence["transaction_started"] = false.into();
assert!(checked_outcome(&job, &out).is_ok());
out.exit_code = Some(0);
assert!(checked_outcome(&job, &out).is_err());
out.state = "unknown".into();
out.reboot_required = true;
out.exit_code = Some(1641);
assert!(checked_outcome(&job, &out).is_ok());
}
#[test]
fn system_route_binds_original_request_shape_budget_and_reply_scope() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
+313 -3
View File
@@ -69,11 +69,49 @@ pub struct Settings {
pub max_runtime_seconds: u32,
pub enable_effects: bool,
pub allow_reboot: bool,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "strict_recipe_hashes"
)]
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
}
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
d: D,
) -> std::result::Result<Option<Vec<String>>, D::Error> {
Vec::<String>::deserialize(d).map(Some)
}
impl Settings {
fn permits_msi(&self, job: &JobPayload) -> bool {
self.schema_version == 2
&& job.execution_identity == "system"
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& job.max_runtime_seconds <= self.max_runtime_seconds
&& job.action.windows_msi().is_some_and(|m| {
self.allowed_msi_recipe_sha256
.as_ref()
.is_some_and(|h| h.contains(&m.recipe_sha256))
})
}
pub fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == 1
matches!(self.schema_version, 1 | 2)
&& (self.schema_version == 2 || self.allowed_msi_recipe_sha256.is_none())
&& self
.allowed_msi_recipe_sha256
.as_ref()
.is_none_or(|hashes| {
hashes.len() <= 2
&& hashes.iter().all(|h| ipc::digest(h))
&& hashes
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
== hashes.len()
})
&& !self.allow_reboot
&& (1..=120).contains(&self.max_runtime_seconds)
&& self.allowed_services.len() <= 16,
@@ -763,6 +801,11 @@ fn verified_window(
Ok((job, permit, now))
}
struct UnsettledMsi {
grant: Uuid,
request_sha256: String,
installer: Box<crate::package::Installer>,
}
pub struct SystemHelper {
settings: Settings,
pin: Pin,
@@ -773,6 +816,7 @@ pub struct SystemHelper {
boot: WindowsBoot,
sync: Option<HelperSync<DalekVerifier>>,
last_diagnostic: Option<Instant>,
unsettled_msi: Option<UnsettledMsi>,
}
impl SystemHelper {
pub fn open() -> Result<Self> {
@@ -796,6 +840,7 @@ impl SystemHelper {
boot,
sync,
last_diagnostic: None,
unsettled_msi: None,
})
}
pub fn pin(&self) -> &Pin {
@@ -972,7 +1017,8 @@ impl SystemHelper {
ensure!(
job.execution_identity == "system"
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
&& matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit)),
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|| self.settings.permits_msi(&job)),
"SYSTEM_ABANDON_POLICY_DENIED"
);
self.sync()?;
@@ -1063,6 +1109,9 @@ impl SystemHelper {
),
"SYSTEM_SIGNED_SYNC_REQUIRED"
);
if job.action.windows_msi().is_some() {
return self.execute_msi(generation, request, &job, &permit, peer);
}
let mut provider = PreparedService::prepare(&self.settings, &job)?;
self.recheck()?;
peer.check()?;
@@ -1101,6 +1150,211 @@ impl SystemHelper {
ledger::finish(&self.db, &permit, &outcome)?;
Ok(outcome)
}
fn execute_msi(
&mut self,
generation: u64,
request: &Request,
job: &JobPayload,
permit: &ExecutionPermitPayload,
peer: &mut ipc::PeerProof,
) -> Result<Outcome> {
use crate::package::{Prepared, Run};
self.observe_unsettled_msi()?;
ensure!(
self.unsettled_msi.is_none(),
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
);
let began = Instant::now();
let original_request_sha256 = hash(&serde_json::to_vec(request)?);
let timeout = Duration::from_secs(job.max_runtime_seconds.into());
let m = job
.action
.windows_msi()
.context("SYSTEM_MSI_MANIFEST_REQUIRED")?;
ensure!(
self.settings.permits_msi(job),
"SYSTEM_MSI_RECIPE_NOT_ALLOWED"
);
// No implicit bootstrap: reject absent/unprotected cache before consume.
let _cache = PinnedFile::open(Path::new(crate::msi_cache::CACHE), true, &[], &[], false)
.context("MSI_CACHE_NOT_CONFIGURED")?;
self.recheck()?;
peer.check()?;
ensure!(
self.sync.as_ref().unwrap().can_start(
&self.db,
&self.guard,
generation,
&self.clock,
&self.boot
),
"SYSTEM_SIGNED_SYNC_REQUIRED"
);
let (_, fresh, recorded_at) =
verified_window(&self.settings.binding, request, &self.clock)?;
ensure!(
&fresh == permit && !STOP.load(Ordering::SeqCst),
"SYSTEM_MSI_START_FENCED"
);
ledger::begin_execution(
&mut self.db,
permit,
request,
self.boot.current_boot()?,
recorded_at,
)?;
self.sync.as_mut().unwrap().close();
let result = (|| -> Result<Outcome> {
ensure!(
began.elapsed() < timeout,
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
crate::helper_runtime::intent::Store::require_not_denied(
request,
self.boot.current_boot()?,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
let _copied_archive = crate::msi_cache::import(m, permit.grant_id)?;
ensure!(
began.elapsed() < timeout,
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let provider = Prepared::prepare(m, &m.recipe_sha256, began, timeout)?;
let run = provider.start(began, timeout, &STOP, || {
self.recheck()?;
peer.check()?;
ensure!(
!STOP.load(Ordering::SeqCst),
"SYSTEM_MSI_CANCELLED_BEFORE_START"
);
verified_window(&self.settings.binding, request, &self.clock)?;
crate::helper_runtime::intent::Store::require_not_denied(
request,
self.boot.current_boot()?,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
Ok(())
})?;
let observation = match run {
Run::Noop(value) => *value, // Noop variant can itself be Unknown.
Run::Installer(mut child) => loop {
// Continue observing this original transaction after start.
// A lost clock/peer/agent-denial observation cannot free the
// lane or retroactively produce success; never kill/retry.
let fenced = STOP.load(Ordering::SeqCst)
|| self.clock.now().is_err()
|| peer.check().is_err()
|| self
.boot
.current_boot()
.and_then(|boot| {
crate::helper_runtime::intent::Store::require_not_denied(
request,
boot,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)
})
.is_err();
let cancelled = AtomicBool::new(fenced);
match child.poll(&cancelled) {
Ok(Some(mut value)) => {
if fenced {
value.state = "unknown";
value.code = "MSI_RUNNING_OBSERVATION_FENCED";
value.postconditions_passed = false;
}
if value.state == "unknown" {
self.unsettled_msi = Some(UnsettledMsi {
grant: permit.grant_id,
request_sha256: original_request_sha256.clone(),
installer: child,
});
}
break value;
}
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
Err(error) => {
let outcome = Outcome {
evidence: serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":true,"process_id":child.process_id(),"automatic_retry":false,"observer_error":safe_error(&error)}),
..Outcome::unknown("MSI_OBSERVER_FAILED_EFFECT_UNRESOLVED")
};
self.unsettled_msi = Some(UnsettledMsi {
grant: permit.grant_id,
request_sha256: original_request_sha256.clone(),
installer: child,
});
return Ok(outcome);
}
}
},
};
let mut evidence = serde_json::to_value(&observation)?;
evidence["provider"] = "windows.msi.fixture/1".into();
let mut outcome = Outcome {
state: observation.state.into(),
stdout: vec![],
stderr: vec![],
exit_code: observation.exit_code.map(|v| v as i32),
output_truncated: false,
reboot_required: observation.installer_reboot_required.unwrap_or(false),
error_code: if observation.state == "succeeded" {
String::new()
} else {
observation.code.into()
},
evidence,
};
if outcome.state == "succeeded" {
let fresh = self.clock.now().is_ok() && peer.check().is_ok();
if !fresh || began.elapsed() >= timeout {
outcome.state = "unknown".into();
outcome.error_code = "MSI_FINAL_OBSERVATION_FENCED".into();
outcome.evidence["postconditions_passed"] = false.into();
}
}
Ok(outcome)
})();
let outcome = result.unwrap_or_else(|error| {
let code = safe_error(&error);
Outcome {state:if began.elapsed() >= timeout {"unknown"} else {"failed"}.into(),
evidence:serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":false,"transaction_started":false,"automatic_retry":false}), ..Outcome::unknown(&code)}
});
ledger::persist_outcome(&self.db, permit, &outcome)?;
self.guard.check(&self.db)?;
ledger::finish(&self.db, permit, &outcome)?;
Ok(outcome)
}
fn observe_unsettled_msi(&mut self) -> Result<()> {
let Some(slot) = self.unsettled_msi.as_mut() else {
return Ok(());
};
self.guard.check(&self.db)?;
let (start, outcome): (Vec<u8>, Vec<u8>) = self.db.query_row(
"SELECT start,outcome FROM execution_evidence WHERE grant_id=?1",
[slot.grant.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let start: serde_json::Value = serde_json::from_slice(&start)?;
let original: Request = serde_json::from_value(start["request"].clone())?;
let saved: Outcome = serde_json::from_slice(&outcome)?;
ensure!(
hash(&serde_json::to_vec(&original)?) == slot.request_sha256
&& saved.state == "unknown",
"SYSTEM_MSI_UNSETTLED_ORIGINAL_BINDING"
);
if slot.installer.process_exited()? {
self.unsettled_msi = None;
}
// No ledger/outcome update here. An observed late exit never revises
// the original deadline outcome or grants permission for another job.
Ok(())
}
}
pub fn safe_error(error: &anyhow::Error) -> String {
if error.chain().any(|cause| {
@@ -1176,10 +1430,16 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
let server = ipc::Server::bind(helper.pin().clone())?;
scm_status(SERVICE_RUNNING, 0);
while !STOP.load(Ordering::SeqCst) {
// A failed observation keeps the owned slot and its handles locked.
if helper.observe_unsettled_msi().is_err()
&& let Some(sync) = &mut helper.sync
{
sync.close();
}
match server.receive() {
Ok(Some(mut incoming)) => {
let reply = helper.handle(&incoming.call, &mut incoming.peer);
if let Err(error) = server.reply(&reply) {
if let Err(error) = server.reply(&reply, &mut incoming.peer) {
if let Some(sync) = &mut helper.sync {
sync.close();
}
@@ -1230,6 +1490,56 @@ pub fn dispatch() -> Result<()> {
mod tests {
use super::*;
#[test]
fn old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi() {
let job = crate::helper_runtime::msi_test_job();
let m = job.action.windows_msi().unwrap();
let peer = PeerPin {
service_name: "synthetic".into(),
service_sid: "synthetic".into(),
user_sid: "synthetic".into(),
binary: PathBuf::from("synthetic"),
binary_sha256: "ab".repeat(32),
};
let mut settings = Settings {
schema_version: 1,
binding: Binding {
tenant_id: job.tenant_id,
asset_id: job.asset_id,
agent_id: job.agent_id,
enrollment_generation: 1,
assignment_version: 1,
public_key_hex: "ab".repeat(32),
},
agent: peer.clone(),
helper: peer,
allowed_services: vec![],
max_runtime_seconds: 30,
enable_effects: false,
allow_reboot: false,
allowed_msi_recipe_sha256: None,
};
let legacy = serde_json::to_value(&settings).unwrap();
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
let mut null = legacy.clone();
null["allowed_msi_recipe_sha256"] = serde_json::Value::Null;
assert!(serde_json::from_value::<Settings>(null).is_err());
assert!(!settings.permits_msi(&job));
settings.allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
assert!(!settings.permits_msi(&job));
assert_eq!(
settings.validate().unwrap_err().to_string(),
"SYSTEM_POLICY_PROFILE"
);
settings.schema_version = 2;
assert!(settings.permits_msi(&job));
assert!(!settings.enable_effects);
settings.max_runtime_seconds = 29;
assert!(!settings.permits_msi(&job));
settings.max_runtime_seconds = 30;
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
assert!(!settings.permits_msi(&job));
}
#[test]
fn service_adapter_exposes_only_implemented_states() {
assert_eq!(desired_state("running").unwrap(), SERVICE_RUNNING);
assert_eq!(desired_state("stopped").unwrap(), SERVICE_STOPPED);
+3
View File
@@ -18,6 +18,9 @@ pub mod inventory;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
pub mod package;
#[cfg(all(windows, feature = "system-helper"))]
pub mod msi_cache;
#[cfg(windows)]
pub mod native;
#[cfg(windows)]
+178
View File
@@ -0,0 +1,178 @@
//! Fixed public-byte staging and independent SYSTEM cache import. No IPC path,
//! URL or byte-array authority. Directories must be provisioned separately;
//! this module never installs/repairs an ACL, directory, policy or service.
use crate::helper_ipc::{self as ipc, PinnedFile};
use anyhow::{Context, Result, ensure};
use rmm_domain::windows_execution::ResolvedWindowsMsi;
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const AGENT_STATE: &str = r"C:\ProgramData\RustDiscovery\state";
pub const STAGE: &str = r"C:\ProgramData\RustDiscovery\state\msi-stage";
pub const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
fn name(m: &ResolvedWindowsMsi) -> Result<String> {
ensure!(m.validate(), "MSI_CACHE_MANIFEST");
Ok(format!("{}.msi", m.recipe.artifact.sha256))
}
fn regular(file: &File, directory: bool) -> Result<()> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
&& (directory || i.nNumberOfLinks == 1),
"MSI_CACHE_NONREGULAR"
);
Ok(())
}
/// Keep every actual parent open without DELETE sharing throughout the copy.
/// Source data/ACL is untrusted; only the original signed digest authorizes bytes.
fn parents(path: &Path) -> Result<Vec<File>> {
let mut held = Vec::new();
for p in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
ipc::wide(p).as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(
raw != INVALID_HANDLE_VALUE,
"MSI_CACHE_PARENT_NOT_CONFIGURED"
);
let file = unsafe { File::from_raw_handle(raw) };
regular(&file, true)?;
held.push(file);
}
Ok(held)
}
fn checked_bytes(path: &Path, m: &ResolvedWindowsMsi) -> Result<Vec<u8>> {
let _parents = parents(path)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
.context("MSI_STAGE_NOT_CONFIGURED")?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
ensure!(
file.metadata()?.len() == m.recipe.artifact.bytes && m.recipe.artifact.bytes <= 262144,
"MSI_CACHE_LENGTH"
);
let mut bytes = Vec::new();
(&mut file).take(262145).read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(&bytes)) == m.recipe.artifact.sha256,
"MSI_CACHE_DIGEST"
);
let again = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
regular(&again, false)?;
ensure!(ipc::file_identity(&again)? == id, "MSI_CACHE_FILE_REPLACED");
Ok(bytes)
}
pub fn stage_configured() -> bool {
crate::native::private_path(Path::new(STAGE), true).is_ok()
}
/// Called by LocalService only for the already approved original job/attempt.
pub fn stage(m: &ResolvedWindowsMsi, bytes: &[u8]) -> Result<()> {
crate::native::require_local_service()?;
let path = Path::new(STAGE).join(name(m)?);
let _parents = parents(&path)?;
crate::native::private_path(Path::new(STAGE), true)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(bytes)) == m.recipe.artifact.sha256,
"MSI_DOWNLOAD_DIGEST"
);
if path.try_exists()? {
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
return Ok(());
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&path)?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
file.write_all(bytes)?;
file.sync_all()?;
ensure!(ipc::file_identity(&file)? == id, "MSI_STAGE_FILE_CHANGED");
drop(file);
crate::native::private_path(&path, false)?;
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
Ok(())
}
/// Called ONLY after full independent helper authorization and durable consume.
/// Publish to the fixed SYS/Admin cache without replacing any existing entry.
/// Returned guards pin the copied archive until the provider holds its own.
pub fn import(m: &ResolvedWindowsMsi, grant: Uuid) -> Result<Vec<PinnedFile>> {
let file_name = name(m)?;
ensure!(!grant.is_nil(), "MSI_CACHE_GRANT");
let destination = Path::new(CACHE).join(file_name);
let _parents = parents(&destination)?;
let root = PinnedFile::open(Path::new(CACHE), true, &[], &[], false)
.context("MSI_CACHE_NOT_CONFIGURED")?;
if destination.try_exists()? {
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
return Ok(vec![root, archive]);
}
let source: PathBuf = Path::new(STAGE).join(name(m)?);
let bytes = checked_bytes(&source, m)?; // Never trust actor ownership/data.
let pending = Path::new(CACHE).join(format!("{}.{}.pending", m.recipe.artifact.sha256, grant));
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&pending)?;
regular(&file, false)?;
file.write_all(&bytes)?;
file.sync_all()?;
drop(file);
// Cache directory was already independently validated SYS/Admin-only. New
// SYSTEM-created files inherit that boundary; no ACL repair is performed.
let copied = PinnedFile::open(&pending, false, &[], &[], false)?;
checked_bytes(&pending, m)?;
drop(copied);
ensure!(
unsafe {
MoveFileExW(
ipc::wide(&pending).as_ptr(),
ipc::wide(&destination).as_ptr(),
0,
)
} != 0,
"MSI_CACHE_CREATE_ONLY_PUBLICATION"
);
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
Ok(vec![root, archive])
}
+28 -5
View File
@@ -17,9 +17,10 @@
use anyhow::{Result, ensure};
#[cfg(any(windows, test))]
use rmm_domain::windows_execution::{ResolvedWindowsMsi, valid_package_code};
use serde::Serialize;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub product_code: String,
pub package_code: Option<String>,
@@ -34,7 +35,7 @@ pub struct Snapshot {
}
impl Snapshot {
#[cfg(any(windows, test))]
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
pub(crate) fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
let p = &r.recipe.postcondition;
self.product_code == p.product_code
&& self.related_products == [p.product_code.clone()]
@@ -854,8 +855,17 @@ mod windows {
system_root: PathBuf,
}
impl Prepared {
pub fn prepare(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<Self> {
pub fn prepare(
r: &ResolvedWindowsMsi,
allowed_recipe_sha256: &str,
began: Instant,
timeout: Duration,
) -> Result<Self> {
validate(r, allowed_recipe_sha256)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let mut roots = Vec::new();
for path in [CACHE, FIXTURES] {
let file = OpenOptions::new()
@@ -872,9 +882,17 @@ mod windows {
false,
)?;
inspect_archive(&mut archive, r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let system_root = system_root()?;
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
let before = snapshot_for(r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
ensure!(
before.baseline_allowed(r),
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
@@ -911,6 +929,7 @@ mod windows {
/// config, privilege, policy, clock, reboot or foreign process occurs.
pub fn start(
mut self,
began: Instant,
timeout: Duration,
cancelled: &AtomicBool,
check_effect_fence: impl FnOnce() -> Result<()>,
@@ -923,7 +942,6 @@ mod windows {
);
// One original budget includes all synchronous verification and
// the eventual installer. A late Noop is not retroactive success.
let began = Instant::now();
let archive = inspect_archive(&mut self.archive, &self.recipe);
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(None));
@@ -1010,6 +1028,11 @@ mod windows {
timeout: Duration,
}
impl Installer {
/// Observe only this retained process handle. Never adopt a PID, kill,
/// restart, or revise an already persisted timeout outcome.
pub fn process_exited(&mut self) -> Result<bool> {
Ok(self.child.try_wait()?.is_some())
}
pub fn process_id(&self) -> u32 {
self.child.id()
}
+85 -2
View File
@@ -367,6 +367,25 @@ struct Agent {
impl Agent {
fn close_gate(&mut self) {
self.fence.close();
#[cfg(feature = "system-helper")]
if let Some(running) = &self.running
&& running.grant.execution_identity == "system"
{
running.cancel.store(true, Ordering::SeqCst);
let denied = (|| -> Result<()> {
let mut store = rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
let intent = store.by_grant(running.grant.grant_id)?;
ensure!(
intent.permit()? == running.grant,
"SYSTEM_CANCEL_GRANT_BINDING"
);
store.deny(&intent.request, Uuid::parse_str(&self.boot)?)
})();
if denied.is_err() {
self.helper_refused = true;
eprintln!("SYSTEM_CANCEL_PERSISTENCE_FAILED");
}
}
if let Some(sync) = &mut self.sync {
sync.close();
}
@@ -566,7 +585,11 @@ impl Agent {
}
#[cfg(feature = "system-helper")]
{
Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
(job.action.windows_msi().is_none()
|| (self.config.state_directory
== Path::new(rmm_agent_windows::msi_cache::AGENT_STATE)
&& rmm_agent_windows::msi_cache::stage_configured()))
&& Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
&& self
.helper
.as_ref()
@@ -983,9 +1006,69 @@ impl Agent {
let completed = self.completed_tx.clone();
let work_offer = offer.clone();
let work_grant = grant.clone();
let msi = job.action.windows_msi().cloned();
let address = self.config.connect_address;
let ca = self.ca.clone();
let state = self.config.state_directory.clone();
let request_for_stage = request.clone();
let binding_for_stage = binding.clone();
let worker = tokio::spawn(async move {
let staged = if let Some(m) = msi {
let result = async {
ensure!(
!worker_cancel.load(Ordering::SeqCst)
&& fence.allows_identity(generation, true, &clock),
"MSI_DOWNLOAD_FENCED"
);
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
let cert = protected_read(&state.join("device.pem"), 32768)?;
let key = protected_read(&state.join("device.key"), 16384)?;
let tls = crate::https_channel::mtls_client(address, &ca, &cert, &key)?;
let response = tls
.get(format!(
"https://{}:{}/agent/v1/artifacts/{}?job_id={}&attempt_id={}",
crate::https_channel::server_name()?,
address.port(),
m.recipe.artifact.artifact_id,
work_grant.job_id,
work_grant.attempt_id
))
.send()
.await?;
ensure!(
response
.headers()
.get("x-artifact-sha256")
.and_then(|v| v.to_str().ok())
== Some(m.recipe.artifact.sha256.as_str()),
"MSI_DOWNLOAD_METADATA"
);
let bytes = crate::https_channel::bounded_body(
response,
m.recipe.artifact.bytes as usize,
"application/octet-stream",
)
.await?;
ensure!(
!worker_cancel.load(Ordering::SeqCst)
&& fence.allows_identity(generation, true, &clock),
"MSI_DOWNLOAD_FENCED"
);
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
tokio::task::spawn_blocking(move || {
rmm_agent_windows::msi_cache::stage(&m, &bytes)
})
.await??;
Ok::<_, anyhow::Error>(())
}
.await;
result.is_ok()
} else {
true
};
let _result = helper
.delegate(intent, move || {
ensure!(staged, "MSI_DOWNLOAD_NOT_READY");
ensure!(
!worker_cancel.load(Ordering::SeqCst),
"CANCELLED_BEFORE_DISPATCH"
@@ -1298,7 +1381,7 @@ impl Agent {
#[cfg(feature="system-helper")]
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file() {
let mut store=rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.cancel_before_dispatch(intent.id)?;}
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.deny(&intent.request,Uuid::parse_str(&self.boot)?)?;store.cancel_before_dispatch(intent.id)?;}
}
if state=="accepted" {self.record(generation,&JobOffer::decode(bytes.as_slice())?,&grant,jobs::no_start("cancelled","CANCELLED_BEFORE_START"))?;needs_sync=true;}
}
+368
View File
@@ -0,0 +1,368 @@
#!/usr/bin/env python3
"""Source-bound Pipe-v2 pack and create-once native units, never deployment.
The access root only supplies the existing pinned SSH transport and immutable
native Core proofs. No credentials/devstate symlinks, copies, services or jobs.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import uuid
CODE = Path(__file__).resolve().parents[2]
ACCESS = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
sys.path.insert(0, str(ACCESS / 'deploy/windows'))
sys.path.insert(0, str(ACCESS / 'deploy'))
import client_bootstrap as cb
import auto_transport_acceptance as auto
import runtime_upgrade as previous
require = cb.contract.require
BUILD = CODE / 'devstate/windows-pipe-drain-build'
NATIVE = CODE / 'devstate/windows-client/native-pipe-v2'
# These imported transports read their original protected access configuration.
# Their new local upload/error receipts belong to this isolated checkout.
cb.EVIDENCE = CODE / 'devstate/windows-client'
CORE = ACCESS / 'devstate/core-no-start/build-de37ee99-11bf-465b-9519-45ad8f6e5b87/manifest.json'
CORE_SHA = '1bc082031fcad20d5a519b0004f63d499dbba2ea9ce25d56230d48d2556d474b'
LOCAL = CODE / 'devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json'
LOCAL_SHA = 'a7e3c604d4ad19feed0323ac23aa7a0290b6fb93bc57649cafbadbe5f293b1d4'
TARGET = 'x86_64-pc-windows-gnu'
NAMES = {'agent': 'rmm-agent-windows.exe', 'helper': 'rmm-helper-windows.exe',
'probe': 'RuntimeStateProbe.exe', 'system_probe': 'SystemStateProbe.exe',
'lib': 'windows-tests-lib.exe', 'bin': 'windows-tests-bin.exe'}
# Expected V2 native lists: unchanged names, two existing codec cases extended.
TESTS = {
'lib': sorted([
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
'clock::tests::suspend_closes_until_actual_post_resume_sync',
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
'clock::tests::wall_step_and_overflow_fail_closed',
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
'helper_ipc::tests::serialization_refuses_oversized_frame',
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
'helper_system::tests::service_adapter_exposes_only_implemented_states',
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
'journal::tests::durable_reopen_ack_identity_and_single_process',
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
'native::tests::boot_identity_survives_independent_native_queries',
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted']),
'bin': sorted([
'https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses'])}
COUNTS = {'lib': 23, 'bin': 7}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(path, value):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
cb.contract.write_private(path, value)
def private_file(path):
path = Path(path)
require(not path.is_symlink() and not path.parent.is_symlink(), 'private regular path')
info = path.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid()
and stat.S_IMODE(info.st_mode) == 0o600, 'private regular owner/mode')
return path
def sources():
require(ACCESS.is_dir() and not ACCESS.is_symlink() and cb.ROOT == ACCESS,
'original access checkout only; no copied configuration')
names = {'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'proto/agent.proto',
'deploy/windows/system_pipe_acceptance.py', 'docs/windows-helper-pipe-drain.md'}
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates').glob('*/Cargo.toml'))
for crate in ('agent-windows', 'agent-core', 'domain', 'protocol'):
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates' / crate).rglob('*')
if p.is_file() and p.suffix in ('.rs', '.c', '.h', '.idl', '.toml'))
names.update('crates/agent/src/' + n + '.rs' for n in ('https_channel', 'transport', 'wire_channel'))
require(all((CODE / n).is_file() and not (CODE / n).is_symlink() for n in names), 'complete fixed build sources')
transport = {}
for module in tuple(sys.modules.values()):
raw = getattr(module, '__file__', None)
if raw:
path = Path(raw).resolve()
if path.is_relative_to(ACCESS / 'deploy') and path.suffix == '.py':
transport[str(path.relative_to(ACCESS))] = sha(path)
require('deploy/windows/client_bootstrap.py' in transport, 'actual transport source binding')
return {'code': {n: sha(CODE / n) for n in sorted(names)}, 'access_transport': dict(sorted(transport.items()))}
def core_proof():
require(sha(CORE) == CORE_SHA, 'exact original Linux-first Core manifest')
manifest = cb.contract.protected_json(CORE)
result = {'manifest_sha256': CORE_SHA}
for platform, count in (('linux', 80), ('windows', 58)):
path = CORE.parent / (platform + '-passed.json')
proof = cb.contract.protected_json(path)
require(proof['verified'] is True and proof['platform'] == platform
and proof['manifest_sha256'] == CORE_SHA, 'actual same-manifest native Core proof')
actual = proof['native']['reports']
require(set(actual) == set(manifest['test_counts'][platform])
and sum(len(v['names']) for v in actual.values()) == count, 'all native Core reports')
for kind, item in actual.items():
n = manifest['test_counts'][platform][kind]
output = base64.b64decode(item['stdout_b64'], validate=True)
require(item['exit_code'] == 0 and item['timed_out'] is False
and item['names'] == manifest['test_names'][platform][kind]
and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
and re.search(rb'test result: ok\. ' + str(n).encode()
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', output),
'complete actual native Core result')
result[platform] = {'proof_sha256': sha(path), 'case_id': proof['case_id']}
for name, digest in manifest['source_files'].items():
if name.startswith(('crates/agent-core/', 'crates/domain/', 'crates/protocol/', 'proto/')):
require(sha(CODE / name) == digest, 'isolated common source equals actual native Core proof')
return result
def reused_qualification():
require(sha(LOCAL) == LOCAL_SHA, 'exact retained local qualification')
value = cb.contract.protected_json(LOCAL)
require(value['type'] == 'rmm.windows.pipe-drain-local-qualification'
and value['source_before_after_equal'] is True and value['native_executed'] is False
and value['clock_qualified'] is False and value['native_counts_expected'] == COUNTS
and len(value['commands']) == 4 and all(c['exit_code'] == 0 for c in value['commands']),
'actual previous cross-Clippy/release/unit-link qualification')
for name, digest in value['source_files'].items():
require(sha(CODE / name) == digest, 'all original qualified inputs remain unchanged')
for item in list(value['artifacts'].values()) + list(value['unit_links'].values()):
path = Path(item['path'])
target = LOCAL.parent / 'target'
require(path.is_relative_to(target), 'qualified link under private target')
current = target
for part in ('',) + path.relative_to(target).parts:
if part:
current = current / part
info = current.lstat()
require(not stat.S_ISLNK(info.st_mode) and info.st_uid in (0, os.getuid())
and info.st_mode & 0o022 == 0, 'protected original compiler output')
require(stat.S_ISREG(path.lstat().st_mode) and sha(path) == item['sha256']
and path.stat().st_size == item['bytes'], 'retained exact qualified links')
require(re.search(r'^pub const ADAPTER_QUALIFIED: bool = false;$',
(CODE / 'crates/agent-windows/src/clock.rs').read_text(), re.M), 'production clock remains closed')
return value
def command(args, folder, name):
with (folder / (name + '.stdout')).open('xb') as out, (folder / (name + '.stderr')).open('xb') as err:
result = subprocess.run(args, stdout=out, stderr=err)
save(folder / (name + '.json'), {'exit_code': result.returncode, 'local_only': True, 'arguments': args})
require(result.returncode == 0, 'local build failed; original stdout/stderr retained')
def build():
before, common, prior = sources(), core_proof(), reused_qualification()
folder = BUILD / ('build-' + str(uuid.uuid4()))
folder.mkdir(mode=0o700, parents=True)
save(folder / 'source-before.json', before)
save(folder / 'reused-qualification.json', {'path': str(LOCAL), 'sha256': LOCAL_SHA, 'value': prior})
image = prior['build_image']
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable compiler image')
target = LOCAL.parent / 'target'
# Only these two RELEASE examples were missing. Original Clippy, EXEs and
# unit links are hash-bound above and are deliberately not rerun/rebuilt.
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
'-v', str(CODE) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target',
'--entrypoint', 'cargo', image, 'build', '--manifest-path', '/src/Cargo.toml', '--locked', '--offline',
'--target', TARGET, '-p', 'rmm-agent-windows', '--features', 'system-helper', '--release',
'--example', 'runtime_state', '--example', 'system_state'], folder, 'release-examples')
selected = {'agent': Path(prior['artifacts']['agent']['path']), 'helper': Path(prior['artifacts']['helper']['path']),
'lib': Path(prior['unit_links']['lib']['path']), 'bin': Path(prior['unit_links']['bin']['path']),
'probe': target / TARGET / 'release/examples/runtime_state.exe',
'system_probe': target / TARGET / 'release/examples/system_state.exe'}
artifacts = {}
for kind, original in selected.items():
output, retained = folder / NAMES[kind], folder / (NAMES[kind] + '.linked')
original_sha = sha(original)
for destination in (retained, output):
shutil.copyfile(original, destination)
destination.chmod(0o600)
if kind in COUNTS:
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(folder) + ':/artifacts',
'--entrypoint', 'x86_64-w64-mingw32-strip', image, '--strip-debug', '/artifacts/' + NAMES[kind]],
folder, 'strip-' + kind)
require(sha(original) == sha(retained) == original_sha, 'original links retained unchanged')
data = output.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', 'Windows AMD64 PE')
artifacts[kind] = {'path': str(output), 'name': NAMES[kind], 'sha256': sha(output), 'bytes': len(data),
'original_link_path': str(retained), 'original_link_sha256': original_sha,
'release_build': kind not in COUNTS, 'debug_stripped': kind in COUNTS}
require(sources() == before and core_proof() == common and reused_qualification() == prior,
'compiler inputs, original links and native Core proof unchanged before/after')
manifest = {'schema_version': 1, 'type': 'rmm.windows.pipe-v2-build', 'source_files': before,
'source_before_after_equal': True, 'code_root': str(CODE), 'access_root': str(ACCESS),
'artifacts': artifacts, 'test_names_expected': TESTS, 'native_counts_expected': COUNTS,
'core_native_proofs': common, 'reused_local_qualification': {'path': str(LOCAL), 'sha256': LOCAL_SHA},
'build_image_id': image, 'transport_version': 2, 'raw_v1_controls_qualified': False,
'production_clock_qualified': False, 'native_executed': False}
save(folder / 'manifest.json', manifest)
print(json.dumps({'manifest': str(folder / 'manifest.json'), 'native_executed': False}))
SCRIPT = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('run','read')-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Pipe V2 unit case'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('native-pipe-v2-'+$p.id)
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private unit type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty unit ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit ACL'}}}
function WriteNew($path,$value){$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function ReadPrivate($path){Safe $path $false;if((Get-Item -LiteralPath $path).Length-gt196608){throw 'Unit report bound'};return (Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
Safe $root $true
if($p.action-eq'read'){
if(!(Test-Path -LiteralPath $case)){@{case_exists=$false;completed=$false;readback_only=$true}|ConvertTo-Json -Compress;exit 0}
Safe $case $true;$i=ReadPrivate (Join-Path $case 'intent.json');if($i.manifest_sha256-cne$p.manifest_sha256){throw 'Original unit intent'}
$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){ReadPrivate $result|ConvertTo-Json -Depth 16 -Compress;exit 0}
$lists=@{};$reports=@{};foreach($kind in @('lib','bin')){$file=Join-Path $case ('list-'+$kind+'.json');if(Test-Path -LiteralPath $file){$lists[$kind]=ReadPrivate $file};$file=Join-Path $case ('report-'+$kind+'.json');if(Test-Path -LiteralPath $file){$reports[$kind]=ReadPrivate $file}}
@{case_exists=$true;completed=$false;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $case 'started.json'));lists=$lists;reports=$reports}|ConvertTo-Json -Depth 16 -Compress;exit 0
}
if(Test-Path -LiteralPath $case){throw 'Existing unit case: readback only'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
function Run($exe,$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit process start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(30000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt65536-or$e.Result.Length-gt65536){throw 'Bounded unit output collection'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout=$o.Result;stderr=$e.Result}}finally{$c.Dispose()}}
$lists=@{};$paths=@{}
foreach($kind in @('lib','bin')){
$a=$p.artifacts.$kind;if($a.sha256-notmatch'^[a-f0-9]{64}$'-or$a.name-cne('windows-tests-'+$kind+'.exe')){throw 'Fixed test artifact'};$folder=Join-Path $root $a.sha256;Safe $folder $true;$exe=Join-Path $folder $a.name;Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$a.sha256-or(Get-Item -LiteralPath $exe).Length-ne$a.bytes){throw 'Exact unit artifact'}
$listed=Run $exe '--list --format terse';[string[]]$names=@($listed.stdout-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($names,[StringComparer]::Ordinal)
$value=@{sha256=$a.sha256;names=$names;listed=$listed};WriteNew (Join-Path $case ('list-'+$kind+'.json')) $value
if($listed.exit_code-ne0-or$listed.timed_out-or$names.Count-ne$p.counts.$kind-or(($names-join"`n")-cne(@($p.test_names.$kind)-join"`n"))){throw 'Exact complete native list before ANY tests'};$lists[$kind]=$value;$paths[$kind]=$exe
}
WriteNew (Join-Path $case 'both-lists-verified.json') @{manifest_sha256=$p.manifest_sha256;both_lists_verified_before_any_test=$true}
WriteNew (Join-Path $case 'started.json') @{start_once=$true};$reports=@{}
foreach($kind in @('lib','bin')){$run=Run $paths[$kind] '--test-threads=1';$value=@{sha256=$lists[$kind].sha256;names=$lists[$kind].names;listed=$lists[$kind].listed;result=$run};WriteNew (Join-Path $case ('report-'+$kind+'.json')) $value;$reports[$kind]=$value;if($run.exit_code-ne0-or$run.timed_out){throw 'Native unit execution failed; readback only'}}
$value=@{completed=$true;manifest_sha256=$p.manifest_sha256;reports=$reports;both_lists_verified_before_any_test=$true;bootstrap_administrator_units=$true;local_service_proof=$false;native_pipe_proof=$false;rmm_jobs=$false;product_state_writes=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
'''
def verified(path, current=True):
path = private_file(path)
require(path.parent.parent == BUILD and path.parent.name.startswith('build-')
and str(uuid.UUID(path.parent.name[6:])) == path.parent.name[6:], 'fixed private build namespace')
value = cb.contract.protected_json(path)
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['schema_version'] == 1
and value['source_before_after_equal'] is True and value['production_clock_qualified'] is False
and value['transport_version'] == 2 and value['raw_v1_controls_qualified'] is False
and value['native_executed'] is False
and value['reused_local_qualification'] == {'path': str(LOCAL), 'sha256': LOCAL_SHA}
and value['native_counts_expected'] == COUNTS and value['test_names_expected'] == TESTS
and value['code_root'] == str(CODE) and value['access_root'] == str(ACCESS), 'exact V2 build profile')
if current:
require(value['source_files'] == sources() and value['core_native_proofs'] == core_proof(), 'current source/Core proof binding')
require(set(value['artifacts']) == set(NAMES), 'six exact artifacts')
for kind, item in value['artifacts'].items():
output, original = private_file(item['path']), private_file(item['original_link_path'])
require(output == path.parent / NAMES[kind] and original == path.parent / (NAMES[kind] + '.linked')
and sha(output) == item['sha256'] and output.stat().st_size == item['bytes']
and sha(original) == item['original_link_sha256']
and item['release_build'] is (kind not in COUNTS)
and item['debug_stripped'] is (kind in COUNTS), 'exact retained delivery and original link')
return value
def native(path, ident=None):
path = path.resolve()
manifest = verified(path, current=ident is None)
if ident is None:
ident = str(uuid.uuid4());folder = NATIVE / ident;folder.mkdir(mode=0o700, parents=True)
save(folder / 'intent.json', {'id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
'runner_sha256': sha(__file__), 'script_sha256': hashlib.sha256(SCRIPT.encode()).hexdigest()})
before = {'counts': auto.scopes(), 'flags': auto.status()}
require(auto.flags_disabled(before['flags']), 'closed fault flags before native units')
save(folder / 'server-before.json', before)
for kind in COUNTS:
previous.upload(manifest['artifacts'][kind])
save(folder / 'started-local.json', {'start_once': True})
action = 'run'
else:
require(str(uuid.UUID(ident)) == ident, 'canonical original native case')
folder = NATIVE / ident;intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['manifest_sha256'] == sha(path) and intent['manifest_path'] == str(path)
and intent['runner_sha256'] == sha(__file__)
and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same original case; readback only')
action = 'read'
result = cb.powershell(SCRIPT, {'id': ident, 'action': action, 'manifest_sha256': sha(path),
'artifacts': {k: manifest['artifacts'][k] for k in COUNTS},
'counts': COUNTS, 'test_names': TESTS}, timeout=150)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
if result.get('completed') is not True:
print(json.dumps({'verified': False, 'case_id': ident, 'readback_only': True, 'completed': False,
'case_exists': result.get('case_exists'), 'tests_repeated': False}))
return
require(result['manifest_sha256'] == sha(path) and set(result['reports']) == set(COUNTS)
and result['both_lists_verified_before_any_test'] is True
and result['rmm_jobs'] is False and result['product_state_writes'] is False
and result['local_service_proof'] is False and result['native_pipe_proof'] is False,
'actual narrow unit result, no runtime proof')
for kind, actual in result['reports'].items():
run, listed = actual['result'], actual['listed']
names = re.findall(r'^(.+): test\r?$', listed['stdout'], re.M)
require(actual['sha256'] == manifest['artifacts'][kind]['sha256']
and names == actual['names'] == TESTS[kind] and len(set(names)) == COUNTS[kind]
and listed['exit_code'] == run['exit_code'] == 0 and not listed['timed_out'] and not run['timed_out']
and re.search(r'test result: ok\. ' + str(COUNTS[kind])
+ r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', run['stdout']),
'every exact named native unit passed, none skipped/filtered')
before = cb.contract.protected_json(folder / 'server-before.json')
require(auto.scopes() == before['counts'] and auto.status() == before['flags'], 'both central counts and closed flags unchanged')
if action == 'run':
verified(path) # Full before/after source and retained-artifact check.
proof = {'verified': True, 'case_id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
'native': result, 'no_jobs': True, 'clock_adapter_qualified': False,
'local_service_proof': False, 'native_pipe_proof': False}
destination = folder / 'passed.json'
if destination.exists():
require(cb.contract.protected_json(destination) == proof, 'retain exact original proof')
else:
save(destination, proof)
print(json.dumps({'verified': True, 'case_id': ident, 'tests': COUNTS, 'proof': str(destination)}))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('build-local', 'native-units', 'readback'))
parser.add_argument('--access-root', required=True, type=Path)
parser.add_argument('--manifest', type=Path)
parser.add_argument('--case')
args = parser.parse_args()
require(args.access_root == ACCESS and not args.access_root.is_symlink(), 'exact existing access root')
if args.phase == 'build-local':
require(args.manifest is None and args.case is None, 'build only')
build()
else:
require(args.manifest is not None and ((args.phase == 'readback') == bool(args.case)), 'explicit manifest and original readback case')
native(args.manifest, args.case)
if __name__ == '__main__':
try:
main()
except Exception as error:
print('WINDOWS_PIPE_V2_QUALIFICATION_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None
+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""Pure C fixture contract guards only; actual Cloud Linux first, then Windows.
No installer artifact is a delivery role. Lost replies allow same-case readback only.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import shlex
import shutil
import stat
import subprocess
import uuid
import vm_access_check as access
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/windows-exe-contract-guards'
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
PROFILE = 'windows-exe-pure-contract-guard-v1'
QUALIFICATION = ROOT / 'devstate/windows-exe-fixture/build-e85496e8-b6dd-4834-8c17-843ee5c5b3da/qualification.json'
QUALIFICATION_SHA = 'f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061'
GUARDS = {'linux': ('linux-precondition-guard', '5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439', 16128),
'windows': ('windows-precondition-guard.exe', '1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf', 15360)}
LINUX_REMOTE = '/var/lib/rmm-windows-exe-contract-guards'
def require(value, code):
if not value:
raise RuntimeError(code)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def object_pairs(items):
value = {}
for key, item in items:
require(key not in value, 'duplicate JSON field')
value[key] = item
return value
def private(path, directory=False):
item = Path(path).lstat()
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
'private owned regular path')
def load(path):
private(path)
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
def save(path, value):
private(Path(path).parent, True)
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
def setup_state():
os.umask(0o077)
STATE.parent.mkdir(mode=0o700, exist_ok=True)
metadata = STATE.parent.lstat()
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
'owned non-world-writable devstate parent')
STATE.mkdir(mode=0o700, exist_ok=True)
private(STATE, True)
def scripts():
return dict(linux_case_sha256=hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
windows_script_sha256=hashlib.sha256(WINDOWS.encode()).hexdigest())
def sources():
require(sha(QUALIFICATION) == QUALIFICATION_SHA, 'original fixture qualification')
q = load(QUALIFICATION)
require(q['no_installer_run'] is True and q['no_upload'] is True and q['source_before_after_equal'] is True, 'fixture-only qualification')
result = dict(q['source_files'])
for name in ('deploy/windows_exe_guard_acceptance.py', 'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py'):
result[name] = sha(ROOT / name)
require(all(sha(ROOT / name) == digest for name, digest in result.items()), 'exact current source provenance')
return result
def build():
setup_state(); before = sources(); folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
q = load(QUALIFICATION); artifacts = {}
for platform, (name, digest, length) in GUARDS.items():
item = q['artifacts'][name]; original = QUALIFICATION.parent / name
require(item['sha256'] == digest and item['bytes'] == length and sha(original) == digest
and original.stat().st_size == length, 'only original pure guard bytes')
destination = folder / name
with destination.open('xb') as out:
out.write(original.read_bytes()); out.flush(); os.fsync(out.fileno())
destination.chmod(0o600)
artifacts[platform] = dict(path=str(destination), sha256=digest, bytes=length, role='pure_precondition_guard')
require(sources() == before, 'source before/after equality')
manifest = dict(schema_version=1, type='rmm.windows.exe-pure-guard-build', profile=PROFILE,
qualification_path=str(QUALIFICATION), qualification_sha256=QUALIFICATION_SHA,
runner_sha256=sha(__file__), scripts=scripts(), source_files=before, source_before_after_equal=True,
artifacts=artifacts, installer_delivery=False, native_execution=False)
save(folder / 'manifest.json', manifest)
print(json.dumps(dict(manifest_path=str(folder/'manifest.json'), manifest_sha256=sha(folder/'manifest.json'), native_execution=False)))
def verified(path):
private(path.parent, True); value = load(path)
require(value['schema_version'] == 1 and value['type'] == 'rmm.windows.exe-pure-guard-build' and value['profile'] == PROFILE
and value['qualification_path'] == str(QUALIFICATION) and value['qualification_sha256'] == QUALIFICATION_SHA
and value['runner_sha256'] == sha(__file__) and value['scripts'] == scripts() and value['source_files'] == sources()
and value['source_before_after_equal'] is True and value['installer_delivery'] is False
and value['native_execution'] is False and set(value['artifacts']) == {'linux','windows'}, 'original guard-only manifest')
for platform, (name, digest, length) in GUARDS.items():
item = value['artifacts'][platform]; candidate = path.parent / name
private(candidate)
require(item == dict(path=str(candidate), sha256=digest, bytes=length, role='pure_precondition_guard')
and sha(candidate) == digest and candidate.stat().st_size == length, 'exact fixed guard delivery role')
return value
def access_settings(root, platform):
"""Read strictly parsed existing access only when the parent executes native."""
require(root == ACCESS_ROOT and not root.is_symlink(), 'original Main access-root only; no copied credentials')
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
if platform == 'linux':
cfg = access.load_config(root / 'credentials/linux-vm.conf')
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
else:
cfg = access.load_config(root / 'credentials/server.conf')
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
credentials = root / 'credentials'; private(credentials, True)
record = load(credentials / 'windows-dev-access.json')
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
expires = dt.datetime.fromisoformat(record['expires_at'])
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
key = str(Path(cfg['ssh_key_path']).expanduser())
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
private(credentials / 'windows-dev.known_hosts')
return prefix
def transport(prefix, command_text, data, folder, timeout=60):
"""No stdout/stderr escapes the private case directory on transport failure."""
try:
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
return value
except subprocess.TimeoutExpired as error:
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('native reply lost; read original case only') from None
def upload(prefix, item, destination, folder, kind):
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
if '-p' in args: args[args.index('-p')] = '-P'
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
try:
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
except subprocess.TimeoutExpired as error:
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('artifact transfer incomplete; no retry') from None
def linux_rpc(prefix, payload, folder):
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
return transport(prefix, 'python3 -', code.encode(), folder, timeout=25)
def windows_rpc(prefix, payload, folder):
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder, timeout=25)
def linux_case(p):
import resource
import stat
ident = str(uuid.UUID(p['id']))
require(ident == p['id'] and p['action'] in ('prepare','run','read') and p['profile'] == 'windows-exe-pure-contract-guard-v1'
and p['artifact'] == dict(sha256='5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439', bytes=16128)
and os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed pure Linux guard only')
root = Path('/var/lib/rmm-windows-exe-contract-guards'); case = root / ident
def safe(path, directory, executable=False):
item = path.lstat()
require(item.st_uid == 0 and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o500 if executable else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1), 'private guard scratch')
def write(path, value):
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd,'w') as out: json.dump(value,out); out.flush(); os.fsync(out.fileno())
os.umask(0o077)
if p['action'] == 'read' and not case.exists(): return dict(id=ident,status='remote_case_absent')
if p['action'] == 'prepare':
if not root.exists(): root.mkdir(mode=0o700)
safe(root,True); case.mkdir(mode=0o700); write(case/'intent.json',p); return dict(id=ident,prepared=True)
safe(root,True); safe(case,True); safe(case/'intent.json',False)
old=json.loads((case/'intent.json').read_bytes())
require({k:v for k,v in old.items() if k!='action'} == {k:v for k,v in p.items() if k!='action'}, 'original complete guard intent')
if p['action'] == 'read':
if not (case/'result.json').exists(): return dict(id=ident,status='started_without_result' if (case/'started.json').exists() else 'prepared_without_start')
safe(case/'result.json',False); require((case/'result.json').stat().st_size<=16384,'bounded guard receipt'); return json.loads((case/'result.json').read_bytes())
binary=case/'guard'; safe(binary,False)
require(binary.stat().st_size==p['artifact']['bytes'] and hashlib.sha256(binary.read_bytes()).hexdigest()==p['artifact']['sha256'],'exact pure guard bytes')
write(case/'started.json',dict(execute_once=True,manifest_sha256=p['manifest_sha256'])); binary.chmod(0o500)
temp=case/'tmp'; temp.mkdir(mode=0o700)
env={'PATH':'/usr/bin:/bin','LANG':'C','LC_ALL':'C','TMPDIR':str(temp)}
def limits():
resource.setrlimit(resource.RLIMIT_CORE,(0,0));resource.setrlimit(resource.RLIMIT_CPU,(3,3));resource.setrlimit(resource.RLIMIT_FSIZE,(4096,4096))
require(subprocess.run(['/usr/bin/unshare','--net','--','/usr/bin/true'],env=env,capture_output=True,timeout=3).returncode==0,'netns required')
with (case/'stdout.bin').open('xb') as out,(case/'stderr.bin').open('xb') as err:
timed=False
try: code=subprocess.run(['/usr/bin/unshare','--net','--',str(binary)],cwd=temp,env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=5,preexec_fn=limits).returncode
except subprocess.TimeoutExpired: timed=True;code=None
out.flush();err.flush();os.fsync(out.fileno());os.fsync(err.fileno())
raw=(case/'stdout.bin').read_bytes();errors=(case/'stderr.bin').read_bytes();require(len(raw)<=4096 and len(errors)<=4096,'bounded guard output')
value=dict(id=ident,platform='linux',profile=p['profile'],manifest_sha256=p['manifest_sha256'],runner_sha256=p['runner_sha256'],scripts=p['scripts'],
artifact=p['artifact'],exit_code=code,timed_out=timed,stdout_b64=base64.b64encode(raw).decode(),stderr_b64=base64.b64encode(errors).decode(),
network_namespace=True,environment_cleared=True,installer_executed=False,rmm_jobs=False,product_state_writes=False)
write(case/'result.json',value);return value
WINDOWS = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-exe-pure-contract-guard-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'-or$p.artifact.sha256-cne'1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf'-or$p.artifact.bytes-ne15360){throw 'Fixed pure Windows guard only'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-exe-contract-guards-'+$p.id)
function Assert-RmmGuardPath($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Guard path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private guard owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty guard ACL'};foreach($entry in $rules){if($entry.AccessControlType-ne'Allow'-or$entry.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($entry.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad guard ACL'}}}
function Write-RmmGuardNew($path,$value){$stream=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()}}
function Assert-RmmGuardIntent($old){foreach($field in @('id','profile','manifest_sha256','runner_sha256','linux_proof_sha256')){if($old.$field-cne$p.$field){throw 'Original guard binding'}};if($old.artifact.sha256-cne$p.artifact.sha256-or$old.artifact.bytes-ne$p.artifact.bytes-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original guard artifact/scripts'}}
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
Assert-RmmGuardPath $root $true
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Assert-RmmGuardPath $case $true;Write-RmmGuardNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
Assert-RmmGuardPath $case $true;$intent=Join-Path $case 'intent.json';Assert-RmmGuardPath $intent $false;Assert-RmmGuardIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
if($p.action-eq'read'){$report=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $report)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Assert-RmmGuardPath $report $false;if((Get-Item -LiteralPath $report).Length-gt16384){throw 'Report bound'};Get-Content -LiteralPath $report -Raw;exit 0}
$exe=Join-Path $case 'guard.exe';Assert-RmmGuardPath $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.artifact.sha256-or(Get-Item -LiteralPath $exe).Length-ne$p.artifact.bytes){throw 'Exact pure guard bytes'}
Write-RmmGuardNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $temp|Out-Null;Assert-RmmGuardPath $temp $true
$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$exe;$start.Arguments='';$start.WorkingDirectory=$temp;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$start.EnvironmentVariables.Clear();$start.EnvironmentVariables['SystemRoot']=$systemRoot;$start.EnvironmentVariables['WINDIR']=$systemRoot;$start.EnvironmentVariables['PATH']=$systemRoot+'\System32';$start.EnvironmentVariables['TEMP']=$temp;$start.EnvironmentVariables['TMP']=$temp
$child=New-Object Diagnostics.Process;$child.StartInfo=$start
try{if(!$child.Start()){throw 'Pure guard start'};$outputTask=$child.StandardOutput.ReadToEndAsync();$errorTask=$child.StandardError.ReadToEndAsync();$timed=$false;if(!$child.WaitForExit(5000)){$timed=$true;$child.Kill();if(!$child.WaitForExit(2000)){throw 'Guard process exit bound'}};if(!$outputTask.Wait(2000)-or!$errorTask.Wait(2000)){throw 'Guard output wait bound'};$stdout=$outputTask.Result;$stderr=$errorTask.Result;if($stdout.Length-gt4096-or$stderr.Length-gt4096){throw 'Guard output bound'};$exitCode=$child.ExitCode}finally{$child.Dispose()}
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;artifact=$p.artifact;linux_proof_sha256=$p.linux_proof_sha256;exit_code=$exitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stdout));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stderr));environment_cleared=$true;installer_executed=$false;rmm_jobs=$false;product_state_writes=$false;bootstrap_administrator_guard=$true;local_service_proof=$false};Write-RmmGuardNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 12 -Compress
'''
def check_result(manifest, platform, value, payload):
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
and value.get('scripts') == manifest['scripts'] and value.get('artifact') == payload['artifact']
and value.get('exit_code') == 0 and value.get('timed_out') is False and value.get('environment_cleared') is True
and all(value.get(flag) is False for flag in ('installer_executed','rmm_jobs','product_state_writes')),
'complete fixed guard Exit0 proof')
require(base64.b64decode(value['stdout_b64'], validate=True) == b''
and base64.b64decode(value['stderr_b64'], validate=True) == b'', 'pure assert guard has no output')
if platform == 'linux': require(value.get('network_namespace') is True, 'Linux network namespace')
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256']
and value.get('bootstrap_administrator_guard') is True and value.get('local_service_proof') is False, 'honest Linux-first Windows bootstrap scope')
def execute(path, platform, access_root, case_id=None):
setup_state(); path = path.absolute(); manifest = verified(path); prefix = access_settings(access_root, platform)
if case_id is None:
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
item = manifest['artifacts'][platform]
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'],
scripts=manifest['scripts'], artifact={key:item[key] for key in ('sha256','bytes')})
if platform == 'windows':
proof_path = path.parent/'linux-passed.json'; proof=load(proof_path)
require(proof['verified'] is True and proof['platform'] == 'linux' and proof['manifest_sha256'] == sha(path)
and proof['runner_sha256'] == manifest['runner_sha256'], 'same-manifest actual Linux guard FIRST')
linux_payload=dict(payload,id=proof['case_id'],artifact={key:manifest['artifacts']['linux'][key] for key in ('sha256','bytes')})
check_result(manifest,'linux',proof['native'],linux_payload)
payload['linux_proof_sha256']=sha(proof_path)
intent=dict(id=case_id,platform=platform,manifest_path=str(path),manifest_sha256=sha(path),runner_sha256=sha(__file__),
scripts=scripts(),access_root=str(access_root.absolute()),payload=payload)
save(folder/'intent.json',intent);save(folder/'started-local.json',dict(create_once=True,no_retry=True))
read_only=False
else:
require(str(uuid.UUID(case_id))==case_id,'canonical original case');folder=STATE/case_id;private(folder,True)
intent=load(folder/'intent.json');load(folder/'started-local.json')
require(intent['id']==case_id and intent['platform']==platform and intent['manifest_path']==str(path)
and intent['manifest_sha256']==sha(path) and intent['runner_sha256']==sha(__file__) and intent['scripts']==scripts()
and intent['access_root']==str(access_root.absolute()),'immutable original readback')
payload=intent['payload'];read_only=True
rpc=linux_rpc if platform=='linux' else windows_rpc
if not read_only:
prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder/'prepared-remote.json',prepared)
require(prepared==dict(id=case_id,prepared=True),'new guard scratch case')
destination=LINUX_REMOTE+'/'+case_id+'/guard' if platform=='linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-exe-contract-guards-'+case_id+'/guard.exe'
upload(prefix,manifest['artifacts'][platform],destination,folder,'pure-guard')
value=rpc(prefix,dict(payload,action='read' if read_only else 'run'),folder)
save(folder/('readback-'+str(uuid.uuid4())+'.json'),value)
if value.get('status'):
require(read_only and value.get('id')==case_id and value['status'] in ('remote_case_absent','prepared_without_start','started_without_result'),'read-only incomplete case')
print(json.dumps(dict(verified=False,case_id=case_id,platform=platform,status=value['status'],retry_allowed=False)));return
check_result(manifest,platform,value,payload)
proof=dict(verified=True,case_id=case_id,platform=platform,manifest_sha256=sha(path),runner_sha256=manifest['runner_sha256'],native=value)
destination=path.parent/(platform+'-passed.json')
if destination.exists(): require(load(destination)==proof,'preserve original identical proof')
else: save(destination,proof)
print(json.dumps(dict(verified=True,platform=platform,case_id=case_id,proof_sha256=sha(destination),installer_executed=False)))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('action',choices=('build-local','linux','windows','readback-linux','readback-windows'))
parser.add_argument('--manifest',type=Path);parser.add_argument('--case');parser.add_argument('--access-root',type=Path)
parser.add_argument('--execute-native-guard',action='store_true');args=parser.parse_args()
if args.action=='build-local':
require(not(args.manifest or args.case or args.access_root or args.execute_native_guard),'local manifest only');build()
elif args.action.startswith('readback-'):
require(args.manifest and args.case and args.access_root and not args.execute_native_guard,'same-case readback only')
execute(args.manifest,args.action.removeprefix('readback-'),args.access_root,args.case)
else:
require(args.manifest and args.access_root and args.execute_native_guard and not args.case,'explicit new native pure guard run')
execute(args.manifest,args.action,args.access_root)
if __name__=='__main__':
try: main()
except Exception as error:
print(json.dumps(dict(error='PURE_EXE_CONTRACT_GUARD_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
raise SystemExit(2) from None
+559
View File
@@ -0,0 +1,559 @@
#!/usr/bin/env python3
"""Windows MSI runtime Library/Binary units: Linux VM FIRST, then Windows VM.
Only fixed common test executables run in separate bootstrap scratch directories.
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
Native execution is explicit; any lost reply permits same-case readback only.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import stat
import subprocess
import uuid
import vm_access_check as access
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/windows-msi-runtime-units'
IMAGE = 'rust-discovery-durable-final-build:local'
PROFILE = 'windows-msi-runtime-units-v1'
LINUX_REMOTE = '/var/lib/rmm-windows-msi-runtime-units'
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
QUALIFICATION = ROOT / 'devstate/windows-msi-runtime/qualified-ee6681c7-8d9d-4af9-8947-5325e1ea2e0f/qualification.json'
QUALIFICATION_SHA = '17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816'
COMMON_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery-windows-msi-integration')
COMMON = COMMON_ROOT / 'devstate/windows-msi-contracts/build-484a3761-6c84-426f-968d-25a638e9c6f7/manifest.json'
COMMON_SHA = '2d96a07be72f3d71a8097510eb5f647ced6577086a45417c599b772018c29a53'
COMMON_PROOFS = {'linux':'09fa24e32cd3f3563e80e91265c6cc7c612321b0fdd1febe7aef3ab6de53cf2a',
'windows':'666ed196953abd0723de259a898b46c08ac84feee0140f1bb31d9db1fa1232c4'}
# Linux ten names were actually executed in the frozen local qualification;
# final Linux delivery --list/run is checked below. Windows is EXPECTED only.
EXPECTED = {'linux': {'lib': ['event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits',
'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable',
'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata',
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
'journal::tests::durable_reopen_ack_identity_and_single_process',
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority',
'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry',
'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload']},
'windows': {'lib': ['actions::tests::powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default',
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
'clock::tests::suspend_closes_until_actual_post_resume_sync',
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
'clock::tests::wall_step_and_overflow_fail_closed',
'event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits',
'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable',
'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata',
'event_log_job::tests::event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success',
'event_log_job::tests::ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves',
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
'helper_ipc::tests::serialization_refuses_oversized_frame',
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
'helper_runtime::intent::tests::additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger',
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
'helper_runtime::tests::msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit',
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
'helper_system::tests::old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi',
'helper_system::tests::service_adapter_exposes_only_implemented_states',
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
'journal::tests::durable_reopen_ack_identity_and_single_process',
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
'native::tests::boot_identity_survives_independent_native_queries',
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority',
'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry',
'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload',
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted'],
'bin': ['https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses']}}
COUNTS = {platform:{kind:len(names) for kind,names in values.items()} for platform,values in EXPECTED.items()}
KINDS = {'linux':('lib',),'windows':('lib','bin')}
def require(value, code):
if not value:
raise RuntimeError(code)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def object_pairs(items):
value = {}
for key, item in items:
require(key not in value, 'duplicate JSON field')
value[key] = item
return value
def private(path, directory=False):
item = Path(path).lstat()
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
'private owned regular path')
def load(path):
private(path)
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
def save(path, value):
private(Path(path).parent, True)
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
def setup_state():
os.umask(0o077)
STATE.parent.mkdir(mode=0o700, exist_ok=True)
metadata = STATE.parent.lstat()
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
'owned non-world-writable devstate parent')
STATE.mkdir(mode=0o700, exist_ok=True)
private(STATE, True)
def source_qualification():
require(sha(QUALIFICATION)==QUALIFICATION_SHA,'exact independently reviewed Runtime qualification')
value=load(QUALIFICATION)
require(value['type']=='rmm.windows.msi-runtime.local-source-qualification'
and value['source_before_after_equal'] is True and value['native_execution'] is False
and value['checks']['windows_default_alltargets_clippy']=='passed'
and value['checks']['windows_system_helper_alltargets_clippy']=='passed'
and value['checks']['windows_lib_bin_unit_link']=='passed_not_executed','real frozen source/Clippy/link qualification')
require(all(sha(ROOT/name)==digest for name,digest in value['source_files'].items()),'all 82 qualified compiler inputs unchanged')
for name,item in value['artifacts'].items():
file=QUALIFICATION.parent/name;private(file)
require(sha(file)==item['sha256'] and file.stat().st_size==item['bytes'],'unchanged qualified original/delivery artifact')
return value
def common_proof():
require(sha(COMMON)==COMMON_SHA,'exact existing common build, never relabelled')
manifest=load(COMMON)
require(manifest['profile']=='windows-msi-contracts-v1' and manifest['source_before_after_equal'] is True,
'original common contract profile')
for name,digest in manifest['source_files'].items():
require(sha(COMMON_ROOT/name)==digest,'preserved complete common source archive')
if name.startswith(('crates/agent-core/','crates/domain/','crates/protocol/','proto/')) or name in ('Cargo.toml','Cargo.lock'):
require(sha(ROOT/name)==digest,'Runtime uses the same actual native-qualified common source')
result={'manifest_sha256':COMMON_SHA}
for platform,total in (('linux',101),('windows',79)):
path=COMMON.parent/(platform+'-passed.json');require(sha(path)==COMMON_PROOFS[platform],'exact actual original common native proof')
proof=load(path);actual=proof['native']
require(proof['verified'] is True and proof['platform']==platform and proof['manifest_sha256']==COMMON_SHA
and actual['manifest_sha256']==COMMON_SHA and actual['runner_sha256']==manifest['runner_sha256']
and actual['scripts']==manifest['scripts'] and actual['product_state_writes'] is False and actual['rmm_jobs'] is False
and actual['all_lists_before_any_tests'] is True and set(actual['reports'])==set(manifest['test_counts'][platform]),'actual complete common profile proof')
for kind,item in actual['reports'].items():
require(item['names']==manifest['test_names'][platform][kind]
and item['sha256']==manifest['artifacts'][platform][kind]['sha256']
and item['exit_code']==0 and item['timed_out'] is False,'every original common native artifact/list/exit')
check_output(base64.b64decode(item['stdout_b64'],validate=True),manifest['test_counts'][platform][kind])
require(sum(len(item['names']) for item in actual['reports'].values())==total,'exact original native count')
result[platform]={'proof_sha256':sha(path),'case_id':proof['case_id'],'tests':total}
return result
def source_files():
value=source_qualification()
result=dict(value['source_files'])
for name in ('deploy/windows_msi_runtime_acceptance.py','deploy/vm_access_check.py','deploy/vm_mvp_acceptance.py'):
require(not (ROOT/name).is_symlink(),'regular local driver/transport input');result[name]=sha(ROOT/name)
return dict(sorted(result.items()))
def names(raw):
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
def check_list(raw, expected):
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
'terse list contains only exact tests, no benchmarks or extra entries')
def check_output(raw, count):
require(re.search(rb'^test result: ok\. ' + str(count).encode()
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
'all tests passed without skipped or filtered tests')
def command(args, folder, timeout=300):
index = len(list(folder.glob('command-*.json')))
try:
done = subprocess.run(args, capture_output=True, timeout=timeout)
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
require(done.returncode == 0, 'local qualification command failed; private output retained')
return done.stdout
except subprocess.TimeoutExpired as error:
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('local qualification timed out; no automatic retry') from None
def scripts():
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
def build():
setup_state();folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
before=source_files();qualified=source_qualification();common=common_proof();save(folder/'source-before.json',before)
image=qualified['image_id'];require(re.fullmatch(r'sha256:[a-f0-9]{64}',image),'immutable source-qualified compiler image')
target=STATE/'target';target.mkdir(mode=0o700,exist_ok=True);private(target,True)
docker=['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m',
'-v',str(ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','cargo',image]
options=['--manifest-path','/src/Cargo.toml','--locked','--offline','--target','x86_64-unknown-linux-gnu','-p','rmm-agent-windows','--lib']
command(docker+['clippy']+options+['--','-D','warnings'],folder)
raw=command(docker+['test']+options+['--release','--no-run','--message-format=json'],folder)
links=[]
for line in raw.splitlines():
try:item=json.loads(line)
except ValueError:continue
if item.get('reason')=='compiler-artifact' and item.get('executable') and item.get('profile',{}).get('test') and item['target']['name']=='rmm_agent_windows':links.append(target/Path(item['executable']).relative_to('/target'))
require(len(links)==1,'exact Linux library test link')
artifacts={'linux':{},'windows':{}}
for platform in KINDS:
destination=folder/platform;destination.mkdir(mode=0o700)
for kind in KINDS[platform]:
linked=links[0] if platform=='linux' else QUALIFICATION.parent/('windows-'+kind+'-tests.original.exe')
delivery_source=linked if platform=='linux' else QUALIFICATION.parent/('windows-'+kind+'-tests.exe')
original=destination/(kind+'.linked');output=destination/(kind+('.exe' if platform=='windows' else ''))
for source,dest in ((linked,original),(delivery_source,output)):shutil.copyfile(source,dest);dest.chmod(0o600)
original_sha=sha(linked)
if platform=='linux':command(['docker','run','--rm','--network','none','--read-only','-v',str(destination)+':/artifacts','--entrypoint','strip',image,'--strip-debug','/artifacts/lib'],folder)
require(sha(linked)==sha(original)==original_sha,'unchanged original linked bytes')
data=output.read_bytes()
if platform=='linux':require(data[:6]==b'\x7fELF\x02\x01' and data[18:20]==b'\x3e\0','Linux x64 ELF')
else:
offset=int.from_bytes(data[60:64],'little');require(data[:2]==b'MZ' and data[offset:offset+6]==b'PE\0\0\x64\x86','Windows x64 PE')
require(all(name.encode() in data for name in EXPECTED['windows'][kind]),'expected native names present in linked Windows bytes, not an executed list')
artifacts[platform][kind]=dict(path=str(output),sha256=sha(output),bytes=len(data),original_link_path=str(original),original_link_sha256=original_sha,debug_stripped_delivery=True)
item=artifacts['linux']['lib']
for mode,args in (('list',['--list','--format','terse']),('run',['--test-threads=1'])):
code='import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+'+repr(args)+',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
raw=command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,exec,size=128m','-v',item['path']+':/unit:ro','--entrypoint','python3',image,'-c',code],folder)
save(folder/('local-linux-lib-'+mode+'.json'),dict(stdout_b64=base64.b64encode(raw).decode()))
if mode=='list':check_list(raw.decode(),EXPECTED['linux']['lib'])
else:check_output(raw,10)
versions=command(['docker','run','--rm','--network','none','--read-only','-v',item['path']+':/unit:ro','--entrypoint','readelf',image,'--version-info','/unit'],folder).decode()
glibc=sorted(set(re.findall(r'GLIBC_(\d+\.\d+)',versions)),key=lambda x:tuple(map(int,x.split('.'))));require(glibc and tuple(map(int,glibc[-1].split('.'))) <= (2,34),'GLIBC at most 2.34')
item['glibc_max']=glibc[-1]
require(source_files()==before and common_proof()==common,'all sources, original qualification and common proofs unchanged')
manifest=dict(schema_version=1,profile=PROFILE,source_files=before,source_before_after_equal=True,
source_qualification=dict(path=str(QUALIFICATION),sha256=QUALIFICATION_SHA),common_native_proofs=common,
original_windows_clippy_and_units_reused=True,backend_and_installer_native_claim=False,
runner_sha256=sha(__file__),scripts=scripts(),test_names=EXPECTED,test_counts=COUNTS,artifacts=artifacts,
build_image_id=image,both_targets_clippy_D_warnings=True,linux_lists_actual=True,windows_lists_expected_until_native=True,
local_linux_tests_passed=10,native_linux_executed=False,native_windows_executed=False,product_state_writes=False,rmm_jobs=False)
save(folder/'manifest.json',manifest);print(json.dumps(dict(manifest=str(folder/'manifest.json'),manifest_sha256=sha(folder/'manifest.json'),linux_tests=10,windows_tests_expected=42,native_executed=False)))
def verified(path, new_run):
path = path.absolute(); private(path.parent, True)
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
value = load(path)
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
and value['source_qualification'] == dict(path=str(QUALIFICATION),sha256=QUALIFICATION_SHA)
and value['original_windows_clippy_and_units_reused'] is True and value['backend_and_installer_native_claim'] is False,
'original manifest/runner/remote scripts/profile binding')
if new_run: require(value['source_files'] == source_files() and value['common_native_proofs'] == common_proof(), 'new execution requires exact runtime/common source proofs')
for platform in COUNTS:
require(set(value['artifacts'][platform]) == set(KINDS[platform]), 'all exact fixed artifacts')
for kind, item in value['artifacts'][platform].items():
suffix = '.exe' if platform == 'windows' else ''
require(Path(item['path']) == path.parent / platform / (kind + suffix)
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
return value
def access_settings(root, platform):
"""Read strictly parsed existing access only when the parent executes native."""
require(root == ACCESS_ROOT and not root.is_symlink(), 'original Main access-root only; no copied credentials')
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
if platform == 'linux':
cfg = access.load_config(root / 'credentials/linux-vm.conf')
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
else:
cfg = access.load_config(root / 'credentials/server.conf')
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
credentials = root / 'credentials'; private(credentials, True)
record = load(credentials / 'windows-dev-access.json')
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
expires = dt.datetime.fromisoformat(record['expires_at'])
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
key = str(Path(cfg['ssh_key_path']).expanduser())
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
private(credentials / 'windows-dev.known_hosts')
return prefix
def transport(prefix, command_text, data, folder, timeout=60):
"""No stdout/stderr escapes the private case directory on transport failure."""
try:
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
return value
except subprocess.TimeoutExpired as error:
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('native reply lost; read original case only') from None
def linux_rpc(prefix, payload, folder):
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
return transport(prefix, 'python3 -', code.encode(), folder)
def windows_rpc(prefix, payload, folder):
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
def upload(prefix, item, destination, folder, kind):
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
if '-p' in args: args[args.index('-p')] = '-P'
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
try:
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
except subprocess.TimeoutExpired as error:
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('artifact transfer incomplete; no retry') from None
def linux_case(p):
import resource
import stat
ident = str(uuid.UUID(p['id']))
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-msi-runtime-units-v1', 'fixed unit case')
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'lib'}, 'fixed Linux root qualification')
root = Path('/var/lib/rmm-windows-msi-runtime-units')
def safe(path, directory):
s = path.lstat()
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
def write(path, value):
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
os.umask(0o077)
case = root / ident
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
if p['action'] == 'prepare':
if not root.exists(): root.mkdir(mode=0o700)
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
return dict(id=ident, prepared=True)
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
original = json.loads((case / 'intent.json').read_bytes())
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
if p['action'] == 'read':
if not (case / 'result.json').exists():
partial = {}
for kind in ('lib',):
for suffix in ('-list.json','-result.json'):
path = case / (kind + suffix)
if path.exists():
safe(path, False); require(path.stat().st_size <= 2*1024*1024, 'bounded original partial receipt')
partial[kind + suffix] = json.loads(path.read_bytes())
return dict(id=ident,status='started_without_result' if (case/'started.json').exists() else 'prepared_without_start',
both_lists_verified=(case/'all-lists-verified.json').exists(),tests_started=(case/'tests-started.json').exists(),partial=partial)
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
temp = case / 'tmp'; temp.mkdir(mode=0o700)
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
def limits():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
listings = {}
for kind in ('lib',):
binary = case / kind; safe(binary, False)
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
binary.chmod(0o500)
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
write(case / (kind+'-list.json'),dict(names=actual,exit_code=listed.returncode,sha256=p['artifacts'][kind]['sha256'],
stdout_b64=base64.b64encode(listed.stdout).decode(),stderr_b64=base64.b64encode(listed.stderr).decode()))
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
and actual == p['names'][kind] and len(actual) == {'lib':10}[kind], 'exact native test names before ANY test execution')
listings[kind] = actual
write(case/'all-lists-verified.json',dict(all_lists_before_any_tests=True,manifest_sha256=p['manifest_sha256']))
write(case/'tests-started.json',dict(execute_tests_once=True))
reports = {}
for kind in ('lib',):
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
timed = False
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
except subprocess.TimeoutExpired: timed = True; code = None
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
write(case / (kind + '-result.json'), reports[kind])
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
scripts=p['scripts'], reports=reports, all_lists_before_any_tests=True, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
write(case / 'result.json', value); return value
WINDOWS = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-msi-runtime-units-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-msi-runtime-units-'+$p.id)
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('lib','bin')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
Safe $root $true
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};$partial=@{};foreach($kind in @('lib','bin')){foreach($suffix in @('-list.json','-result.json')){$file=Join-Path $case ($kind+$suffix);if(Test-Path -LiteralPath $file){Safe $file $false;if((Get-Item -LiteralPath $file).Length-gt2097152){throw 'Partial report bound'};$partial[$kind+$suffix]=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json}}};@{id=$p.id;status=$status;all_lists_verified=(Test-Path -LiteralPath (Join-Path $case 'all-lists-verified.json'));tests_started=(Test-Path -LiteralPath (Join-Path $case 'tests-started.json'));partial=$partial}|ConvertTo-Json -Depth 16 -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
$lists=@{};$executables=@{}
foreach($kind in @('lib','bin')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};[string[]]$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($actual,[StringComparer]::Ordinal);$counts=@{lib=35;bin=7};$count=$counts[$kind];if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};WriteNew (Join-Path $case ($kind+'-list.json')) @{names=$actual;sha256=$item.sha256;listed=$list};$lists[$kind]=$actual;$executables[$kind]=$exe}
WriteNew (Join-Path $case 'all-lists-verified.json') @{all_lists_before_any_tests=$true;manifest_sha256=$p.manifest_sha256};WriteNew (Join-Path $case 'tests-started.json') @{execute_tests_once=$true}
$reports=@{};foreach($kind in @('lib','bin')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;all_lists_before_any_tests=$true;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
'''
def check_result(manifest, platform, value, payload):
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
and value.get('environment_cleared') is True and value.get('all_lists_before_any_tests') is True and set(value['reports']) == set(KINDS[platform]), 'complete native original binding')
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
for kind, item in value['reports'].items():
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
check_output(raw, COUNTS[platform][kind])
def execute(path, platform, access_root, case_id=None):
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
prefix = access_settings(access_root, platform)
if case_id is None:
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS[platform]}, names=EXPECTED[platform])
if platform == 'windows':
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS['linux']}, names=EXPECTED['linux'])
check_result(manifest, 'linux', proof['native'], linux_payload)
payload['linux_proof_sha256'] = sha(proof_path)
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
save(folder / 'intent.json', intent)
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
run_read = False
else:
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
payload = intent['payload']; run_read = True
rpc = linux_rpc if platform == 'linux' else windows_rpc
if not run_read:
result = rpc(prefix, dict(payload, action='prepare'), folder)
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
for kind in KINDS[platform]:
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-msi-runtime-units-' + case_id + '/' + kind + '.exe'
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
if result.get('status'):
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
check_result(manifest, platform, result, payload)
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
destination = path.parent / (platform + '-passed.json')
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
else: save(destination, proof)
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
manifest_sha256=sha(path), proof_sha256=sha(destination))))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
if args.action == 'build-local':
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
elif args.action.startswith('readback-'):
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
else:
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
execute(args.manifest, args.action, args.access_root)
if __name__ == '__main__':
try: main()
except Exception as error:
print(json.dumps(dict(error='WINDOWS_MSI_RUNTIME_UNIT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
raise SystemExit(2) from None
+69
View File
@@ -0,0 +1,69 @@
# Numerische Windows-Zeitdienstdiagnose
Stand2026-11-14: Diagnosequelle implementiert und unabhängig vom Produktions-
Clockpfad gebaut. Keine Lockerung von Statusguard, ALPC-/Identitätsprüfung,
`NativeClock.now()` oder `ADAPTER_QUALIFIED=false`. Keine neue Clockauthority.
Die feste zusätzliche Named-Pipe-Statusabfrage liefert ausschließlich acht
numerische Felder: Phase, tatsächliche RPC-Rückgabe samt Presenceflag,
aufgefangene Ausnahme und Strukturgrößen-/Zeigerpräsenz. Keine Quellen-/Peer-
Namen, Pointerwerte oder zusätzlichen Rückgabeeinträge werden veröffentlicht.
Eigener begrenzter Diagnoseworker; nach Timeout kein Ersatz/Retry.
Lokal tatsächlich bestanden: Windows-Example-Clippy mit Warnungen als Fehler,
fünf Linux-Clocktests, Windows-Testlink (nicht nativ ausgeführt) und Release-
Link.125Quellinputs vorher/nachher identisch. Originale Werkzeugabweichung
(Buildimage ohne WIDL) privat erhalten; erfolgreicher Build mit vorhandenem
unveränderlichem Clockimage. Artefakt `ecad703ad7208d55681c63ba9513fcf4c73b671951d4d1b5db1af9df49f43bdf`,
1779541Bytes. Privater Build `release-ca9a63b8-127c-4933-a45d-9e82449d6980`,
Qualifikation `36ce552e…`.
Danach tatsächlich auf der Windows-VM unter dem separaten LocalService-
Bootstrapdienst ausgeführt, Fall `2996df8c-b261-466a-8963-a526babf7f67`.
NativeReport und getrennter Readback identisch, eigener Dienst entfernt.
ALPC weiter1753/kein Endpunkt, keine erfolgreichen Identitätsnegativkontrollen.
Zusätzliche unabhängige Abfrage:1783, `stage=90`, `rpc_exception=1783`,
`native_rpc_return_present=0`, `status_present=0`. **Eine aufgefangene RPC-/
NDR-Ausnahme vor normaler Stub-Rückkehr ist belegt; der eigene nachgelagerte
Strukturguard wurde nicht erreicht.** Das Nullwertfeld `native_rpc_return=0`
ist ohne Presenceflag ausdrücklich kein erfolgreicher nativer Return.
Die genaue RPC-/NDR-Ursache bleibt offen. Source-/IDL-Prüfung folgt anhand
des [Microsoft-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
W32Time wurde für diese Diagnose nicht umkonfiguriert, keine Uhr gesetzt und
kein RMM-Job ausgeführt. Zentrale Windows0/0/0/0 und Linux30/30/26/0 samt
geschlossenen Testhooks/Rootpolicy erhalten. Dieses Ergebnis qualifiziert
weder Named-Pipe-Serveridentität noch eine vertrauenswürdige Uhr. Erst recht
öffnet es keinen Grant-/Jobpfad.
## Enger WIDL-Zeigervertrag: lokal korrigierter Kandidat
Die erhaltene generierte WIDL7-Typbeschreibung kodiert den ursprünglichen
Status-Ausgabeparameter als `FC_RP→FC_RP→STATUS`. Der dokumentierte Vertrag
verlangt außen eine Referenz, innen den Unique-Statuspointer. Auch die neu aus
Microsofts vollständigem IDL erzeugte WIDL7-Datei zeigt den doppelten Ref:
Es handelt sich präziser um die rekursive Parameterattributbehandlung dieses
Compilers, nicht lediglich um eine andere Schreibweise unseres Narrow-IDL.
[Pointerregeln](https://learn.microsoft.com/en-us/windows/win32/rpc/three-pointer-types),
[Typformat](https://learn.microsoft.com/en-us/windows/win32/rpc/pointers-tfs),
[WIDL7-Compilerquelle](https://raw.githubusercontent.com/wine-mirror/wine/wine-7.0/tools/widl/typegen.c).
Der enge Kandidat deklariert den inneren Typ ausdrücklich `[unique]` und lässt
das redundante äußere `[ref]` zugunsten des dokumentierten Parameterdefaults
weg. WIDL erzeugt tatsächlich `FC_RP→FC_UP→STATUS`; kein Stubbyte wurde gepatcht.
Ganze Procedureformatfolge/Opnum6 unverändert, alle19Statusfeldoffsets und120B-
Struktur gegen frisch erzeugte Microsoft-Full-IDL-Header per AMD64-Clangassert
geprüft. C/Auth/Statusguard/Clockgate unverändert. MicrosoftMIDL wurde mangels
nativer Werkzeuge ausdrücklich noch nicht ausgeführt.
Neuer privater Buildfall `f5805176-4a5a-468d-b1b2-088030253c8d`, Qualifikation
`e96baaf6…`:63Compilerinputs vorher/nachher gleich, fünf Clocktests tatsächlich
bestanden, beide WindowsGNU-Alltargets-Clippyprofile, Release- und Unitlink
bestanden. Ein zunächst0Tests selektierender Aufruf und ein falscher lokaler
Harnesslink bleiben als unvollständige Vorgängerlogs erhalten. Neues Artefakt
`91889303e1650d8612b946512f069a3421eb686c7bed315426c48bd62b18a1fd`,
Original-Linkdatei erhalten. Nur `native/w32time.idl` geändert, SHA `37da4acb…`.
**Native Prüfung dieses Kandidaten noch nicht ausgeführt.** Der tatsächliche
Auslöser der bisherigen1783-Ausnahme ist damit weiter nicht bewiesen. Kein
Clockvertrauen aus Codegenerierung oder lokalem Build, keine Rückstufung vom
unqualifizierten ALPC-Pfad auf eine nur vermeintlich authentisierte Pipe.
+69
View File
@@ -0,0 +1,69 @@
# Reine EXE-Fixture-Vertragsguards
Der getrennte Runner `deploy/windows_exe_guard_acceptance.py` liefert ausschließlich
`linux-precondition-guard` und `windows-precondition-guard.exe` aus der unveränderten
Fixture-Qualifikation `f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`.
Diese C-Programme prüfen mit `assert` nur Zustandsmatrix und feste Argumente. Sie
enthalten keine Installer-, Registry-, Datei-, Netzwerk- oder Dienstoperationen.
Die beiden eigentlichen Installer und ihre Originaldateien sind keine Deliveryrollen.
Das neue private Manifest liegt unter
`devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json`
mit SHA-256 `982096ec11d19d7a23901d2e2330152aa6ae8938ddb7aaac0d64a3633d1a4ac6`.
Es bindet beide Guardbytes, ursprüngliche Qualifikation, neun Fixture-/Normquellen,
Runner und vorhandene Zugangsparser. Die fünf Compilerquellen, ursprünglichen
Links und bisherigen Qualifikationsberichte bleiben erhalten.
Lokal tatsächlich bestanden: Python-Syntax, PowerShell-AST einschließlich Prüfung
auf Funktionsnamen mit vorhandenen Aliasen, Guardrollen-/Manifestprüfung,
begrenzte Nachwartezeiten und simulierter Antwortverlust mit ausschließlich
anschließendem Readback. Der private lokale Guardbericht hat SHA-256
`a9c3b0e2dfc5225b7ce4af7787cb8c138a878ac2d5b2fa3a6199d7820c69d997`.
Keine native VM-Ausführung, kein SSH-Zugriff und keine Installation wurden dafür
durchgeführt. Dies ist weder ein Produkt- noch ein LocalService-Nachweis.
Die folgenden Befehle sind **geplant, nicht ausgeführt**. Zuerst auf der echten
Cloud-Linux-VM, danach mit dessen vollständigem Exit-0-Bericht auf Windows:
```sh
python3 deploy/windows_exe_guard_acceptance.py linux \
--manifest /home/kevin/Schreibtisch/Coding/rust-discovery-windows-exe-fixture/devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json \
--access-root /home/kevin/Schreibtisch/Coding/rust-discovery \
--execute-native-guard
python3 deploy/windows_exe_guard_acceptance.py windows \
--manifest /home/kevin/Schreibtisch/Coding/rust-discovery-windows-exe-fixture/devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json \
--access-root /home/kevin/Schreibtisch/Coding/rust-discovery \
--execute-native-guard
```
Jeder Aufruf erzeugt einen neuen privaten Fall. Der entfernte Startintent wird vor
Ausführung dauerhaft und exklusiv erstellt. Linux verwendet einen eigenen
Netzwerk-Namespace, geleerte Umgebung und begrenzte Laufzeit/Dateiausgaben.
Windows verwendet einen eigenen Scratchpfad, geleerte Umgebung und begrenzte
Prozess- und Ausgabewartezeiten. Erfolg verlangt Exit 0 ohne Timeout und ohne
Ausgabe. Es gibt keine Rust-Testliste und keine zusätzlichen Vertragsfälle.
Nach verlorener Antwort ausschließlich `readback-linux` bzw. `readback-windows`
mit denselben Manifest-/Accessargumenten und `--case ORIGINAL-UUID` verwenden,
**ohne** `--execute-native-guard`. Fehlende oder teilweise Berichte erlauben weder
erneuten Upload noch erneuten Start. Der Mainpfad dient allein dem Lesen bereits
vorhandener streng geparster und hostschlüsselgebundener Bootstrapzugänge;
Quellen, Artefakte und Berichte bleiben im EXE-Worktree.
## Tatsächlicher Cloud-Linux-Guard
Root führte nach eigenem Quellenreview den festen reinen C-Guard auf der
permanenten Cloud-Linux-VM aus: Exit0, kein stdout/stderr, kein Timeout.
Fall `17f3b424-09ac-4501-90a0-a044d5fd733a`, ManifestSHA256
`982096ec11d19d7a23901d2e2330152aa6ae8938ddb7aaac0d64a3633d1a4ac6`,
LinuxproofSHA256
`ce46d28a52ec6d144cd284586a2a3ef7fdf9a809389ab8281ce8ebaf79545320`.
Neue eigene Bootstrap-Scratchdaten, leere Umgebung und neuer Netzwerknamespace;
kein Installer geliefert oder gestartet, keine Produktdaten oder Dienste geändert.
Dies ist ein ausgeführter C-Assertionguard, keine erfundene Rust-Testzahl oder
Installationsabnahme. Windows-Guard und beide tatsächlichen EXE-Installations-/
Upgrade-/Noop-/Fehlerabnahmen bleiben offen. Jede RMM-Paketwirkung benötigt
weiterhin den eigenen unveränderlichen Plan und tatsächliche WebUI-Genehmigung.
+165
View File
@@ -0,0 +1,165 @@
# Vorschlag für den engsten EXE-Vertrag nach Spezifikation1.19
Stand2026-11-14, **Root-Reviewentwurf, nicht beschlossen oder implementiert**.
Spezifikation1.19 erlaubt an dieser Stelle ausschließlich den bestehenden
MSI-Vertrag. Die folgenden Änderungen benötigen eine bewusste Präzisierung1.20
durch Root. Keine neuen Exporte, Capabilities, Policies oder Ausführungsgates
wurden aktiviert. Der Sourcebuild ist kein nativer Installationsnachweis.
## 1. Exakt zwei eigene Artefakte und ein typisierter Plan
Ausgangspunkt ist der geprüfte Fixturebuild
`build-e85496e8-b6dd-4834-8c17-843ee5c5b3da`, Qualification-SHA256
`f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`.
Die Kandidaten sind bewusst unsignierte Entwicklungsartefakte:
| Ziel | EXE-SHA256 | Bytes |
| --- | --- | --- |
| 1.0.0 | `9a972430614625b99985cd3db69f7f8f47e561c954697d57ba21e79fd5b787dc` | 23040 |
| 1.1.0 | `196d22893eaea74d332782c597d4cbce631522006786a4aae074ad0a2bea8c89` | 23552 |
Nur diese beiden Artefakte gehören zum ersten EXE-Profil; kein beliebiges EXE
mit ähnlich benannten Registrywerten. Ein anderer Build braucht eine neue
explizite Profil-/Rezeptentscheidung und eigene Qualifikation. Die einzige
abgeleitete Argumentliste lautet `--quiet --norestart`; keine Argumentfelder,
URLs, Repair-, Uninstall-, Shell-, Dienst- oder Rebootoptionen.
`Action::EnsurePackage` erhält **am Ende** ein optionales
`windows_exe_manifest: Option<Box<ResolvedWindowsExe>>`. Fehlend wird als None
ausgelassen; vorhandenes null, Enum-Objekte und unbekannte Felder werden
abgewiesen. JsonSchema beschreibt die optionale Eigenschaft ohne null.
Genau eines von APT/MSI/EXE darf vorhanden sein. Alte APT-/MSI- und Linux-
Job-/Planbytes müssen unverändert bleiben; kein JobPayload-/Grant-/IPC-
Versionswechsel. Die Action ist ausschließlich `execution_identity=system`,
`provider=exe`, `package=rmm-windows-exe-fixture`, `architecture=x64`,
`installation_context=machine`, `recipe_version=1`, exakte Version und Recipe-ID.
Vorgeschlagene kanonische Feldordnung:
* `ResolvedWindowsExe`: `recipe`, `recipe_sha256`.
* `WindowsExeRecipe`: `schema_version=1`, `recipe_id`, `recipe_version=1`,
`platform=windows`, `architecture=x64`, `context=machine`,
`command_profile=exe_fixture_quiet_no_reboot_v1`, `artifact`, `postcondition`,
`no_reboot=true`, optionales `predecessor`.
* `artifact`: `artifact_id`, `sha256`, `bytes`, mit exakt einem obigen Paar.
* `postcondition`: `registry_hive=hklm`, `registry_view=64` als strikter String,
`registry_key=SOFTWARE\\RustDiscovery\\ExeFixture`,
`product_id=RustDiscovery.ExeFixture`, `product_version`,
`payload_path=C:\\Program Files\\RustDiscoveryFixtures\\exe-payload.txt`,
`payload_sha256`, `payload_bytes=33`.
Die Recipe-IDs sind `rmm-windows-exe-fixture-install-1.0` und
`rmm-windows-exe-fixture-upgrade-1.1`. `predecessor` ist für1.0 abwesend und
für1.1 zwingend die vollständige feste1.0-Nachbedingung, ebenfalls strict
nonnull/None-omit. Keine frei wählbaren Registrywerte oder Zielpfade.
`recipe_version` ist der String `"1"`, nicht die JSON-Zahl1; `schema_version`
ist die Zahl1. Der Recipehash ist SHA256 der exakten Domain-Serialisierung einschließlich
Artifact-ID; alle folgenden Bindungen verwenden dieselben Bytes.
## 2. Tenantkatalog, Genehmigung und ausdrückliche SYSTEM-Obergrenze
Eine eigene immutable `windows_exe_recipes`-Tabelle folgt dem MSI-Muster:
Tenant-/Rezept-/Versions- und Tenant-/Recipehash-Eindeutigkeit, zusammengesetzter
FK auf Tenant/Artifact-ID/SHA/Bytes, FORCE RLS, nur SELECT/INSERT, Verbot von
UPDATE/DELETE. Import/List sind vom MSI-/APT-Katalog getrennt. Kein zusätzlicher
generischer Downloadpfad: pro Job genau eine automatische Artifactreferenz,
vollständige Recipe- und Artifactmengen des Plans; zunächst homogene EXE-Pläne.
Plan, Submit, WebUI-Genehmigung, Delivery, Permit und mTLS-Artifactdownload
prüfen dieselbe Bindung und die aktuellen Rechte erneut.
Bestehende Rechte `operations:plan`, `operations:submit`, `plans:approve` und
`system:execute` bleiben ihre jeweiligen Voraussetzungen. Policies genehmigen
weiterhin nichts. Eine neue zentrale **und** lokale SYSTEM-Policy/Settings-
Schema3 ergänzt höchstens zwei eindeutige `allowed_exe_recipe_sha256`.
Schema1 bleibt SCM-only, Schema2 SCM/MSI-only; beide verweigern EXE. Schema3
behält die vorhandenen MSI-Hashes und ergänzt EXE nur ausdrücklich. Das neue
optionale Feld fehlt in alten Serialisierungen; null und fremde Hashes werden
abgewiesen. Tenant/Asset/Agent/Generationen/Principals und Helper-Policy-/Binary-
Pins bleiben vollständig gebunden, `allow_reboot=false` bleibt Pflicht;
maximal120Sekunden Originalbudget und65536Ausgabebytes wie beim MSI-Profil.
Zusätzlich nötig sind die vorhandenen Windows-/Sync-/Helper- und
`ensure_package`/`system:ensure_package`-Capabilities sowie die **neue enge**
`package.exe.fixture/1`; keine allgemeine SYSTEM-EXE- oder Skriptautorität.
Alle bleiben bis getrennter nativer Qualifikation deaktiviert. Die WebUI zeigt
SYSTEM, Recipe-/Artifacthash, feste Argumente, Budget, Vorgänger und vollständige
Nachbedingungen ausschließlich aus verifizierten gespeicherten Planbytes.
Jobs/Payload/ResolvedTargets/Preview-Aliases und spätere Mutationen werden wie
bei MSI gegengeprüft; echte Domain-Goldenbytes verhindern None-/Feldordnungsfehler.
## 3. Derselbe Delegationskern, ein enger EXE-Provider
Der vorhandene mTLS-Client lädt nur das genehmigte Job-/Attempt-Artifact mit
exakter Länge/SHA und höchstens256KiB. Ein fest vorprovisionierter Actor-
Stagingbereich `exe-stage` und SYS-Cache `<sha>.exe` erweitern die vorhandenen
Cachehelfer über einen **geschlossenen MSI/EXE-Typ**, nicht über Callerpfade,
URLs oder IPC-Bytearrays. SYSTEM prüft erneut Parent-/Reparse-/ACL-/File-ID-
Bindung sowie Bytes/SHA, kopiert unabhängig in den geschützten Cache und hält
die eigenen Archivhandles. Fehlende Konfiguration führt zu not_configured;
keine implizite Ordner-/ACL-Reparatur.
OriginalRequest-/Grant-/Boot-/Helper-Lineage, Intent-CAS, dauerhafter Cancel-
Deny, Abandon, RawFullTupleMirror und SignedSync werden **nicht dupliziert**.
Historische und aktuelle Auth-/Clock-/Scope-/Policyprüfungen bleiben erhalten.
Atomarer Helper-Start erfolgt vor Cache-/Installerwirkung; Abandon führt keine
Cache-/Providerarbeit aus. Das ursprüngliche monotone Gesamtbudget umfasst
Cache, Metadaten, Noop, Start, Beobachtung und Nachprüfungen. Frische Peer-/
Clock-/Fence-/Cancelprüfung unmittelbar vor Noop oder Start, ohne langlebigen
SQLite-Lesesnapshot. Der letzte Read→Spawn-Abstand ist keine Rollbackgarantie.
Ein neuer enger EXE-Provider startet ausschließlich das gehaltene Cacheartefakt
mit den festen Argumenten, ohne Shell/Netz/weitere Prozesse. Die bisherige
`UnsettledMsi`-Verwaltung wird am vorhandenen Dispatcher zu einem geschlossenen
`OwnedPackageChild::{Msi,Exe}` erweitert: **ein** gemeinsamer gesperrter Slot und
Paketressourcen-Lock, OriginalRequest-/Grantbindung, Child- und Archivhandles.
Nach unklarem Timeout bleiben diese erhalten; keine weiteren MSI-/EXE-Starts,
bis derselbe Prozess nachweislich zur Ruhe gekommen ist. Kein globales Kill,
PID-Adoption, automatischer Retry oder nachträgliches Umschreiben des Unknown.
Helpercrash hebt die ursprüngliche Ledgersperre nicht auf. Cancel nach Start
liefert keine globale Prozessbeendigung oder Zusage zurückgenommener Wirkung;
derselbe Versuch wird weiter beobachtet und sein Ausgang ehrlich festgehalten.
## 4. Unabhängige Zustands- und Ergebnisregeln
Der Provider liest nativ ausschließlich HKLM64 und die feste Nutzdatei:
genau7 korrekt typisierte Fixturewerte, keine Unterkeys/Registrylinks; gehaltene
geschützte Nonreparse-Datei mit File-ID, genau33Bytes und festem SHA. Payload1.0
hat SHA `7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf`,
Payload1.1 `e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0`.
Die übrigen Registrywerte/-typen stehen unverändert im Fixture-README.
Kein Erfolg aus stdout oder EXE-Exit allein, kein Win32_Product-Aufruf.
| Beobachtung innerhalb des Originalbudgets | Dauerhaftes Ergebnis |
| --- | --- |
| Unabhängig exakt gewünschter Zustand, frischer Fence | erfolgreicher Provider-Noop, kein Child, Exit=None |
| 1.0: vollständig leer; 1.1: vollständig exakt1.0 | einziger jeweils zulässiger Startbestand |
| Widersprüchlicher/teilweiser Bestand vor Start | verweigert, keine automatische Reparatur |
| Child Exit0 und unabhängige vollständige Zielnachbedingungen | erfolgreich; Prozessstart ist kein Beweis tatsächlich veränderter Bytes |
| Exakter Fixture-Exit10 vor eigener Mutation | failed; ursprünglicher Grant bleibt konsumiert, kein erfundenes NoStart/Unlock |
| Exit20 nach möglicher Teilwirkung | unknown, auch wenn der aktuelle Bestand zufällig vollständig erscheint |
| Unerwarteter Exit, unklare Beobachtung, überschrittenes Budget | unknown bei möglicher Wirkung, kein Retry/Retro-Success |
MSI-Codes3010/1641/1618 bekommen **keine** EXE-Sonderbedeutung. Der feste
Fixturecode enthält keinen Rebootaufruf; Exit0 beweist keine allgemeine
Rebootfreiheit beliebiger EXEs oder Abwesenheit eines ambienten Pendingflags.
Nur der normale signierte Sync darf verbrauchte Ressourcen freigeben.
## 5. Kleinste Dateigrenze und fehlende Nachweise
| Bereich | Geplanter Eingriff nach Root-Entscheidung |
| --- | --- |
| Norm | Root: Spezifikation1.20, project-decisions, development; die beschriebenen engen Ausnahmen ausdrücklich festhalten |
| Domain | neu `windows_exe.rs`; `lib.rs`/`jobs.rs` additive Typen/Validatoren/Codec-Goldens, keine alten Feldänderungen |
| Backend | neuer EXE-Katalog und Migration nach0014; vorhandene Jobs/Policy/Gateway/Artifact-Routen um genau den neuen Typ ergänzen |
| WebUI | bestehende API/Safety/Main und betroffene Tests; verifizierte Projektion und eigener Katalogimport/-list |
| Windows | neuer `exe_package.rs`; vorhandene Cachehelfer, SYSTEM-Dispatcher/Settings, helper_runtime/runtime/lib; Intent-/IPC-Operationsvertrag unverändert |
| Core/Protocol | keine neue Zustandsmaschine, kein Unlock-/Grantcodec; Domain-gesteuerte Scopeprüfung nur falls technisch erforderlich additiv |
Bereits vorhanden: Fixture-Source-Review und lokaler GNU-Build mit ausgeführtem
reinem Linux-Guard; Windows-Guard und Installer nur gebaut. Offen sind echte
Linux→Windows-Guardabnahme, Domain/Schema-/RLS-/Plan-/Policy-/UI-Belege,
nativer sicherer Cache-/PERSIST-/HKLM64-/File-ID-Nachweis sowie separat per
WebUI genehmigte1.0-Installation,1.1-Upgrade und Noops/Fehlerpfade. Source,
Build, native Unitqualifikation und echte Installerwirkung bleiben getrennte
Abnahmeschritte. Vor deren Nachweis keine Ready-/Capability-/Clock-Gateflips;
keine EXE-Ausführung auf dem Notebook.
+60
View File
@@ -0,0 +1,60 @@
# Windows EXE-Fixture: Quelle und lokale Artefakte
Stand 2026-11-14, eigener Zweig `codex/windows-exe-fixture` ab `287a784`.
Nur die fünf neuen Dateien unter `tools/windows-exe-fixture/` und diese Notiz.
Kein Domain-/Core-/MSI-/Runtime-/Helper-/Backend-/UI- oder Normvertrag geändert;
kein EXE-Provider exportiert. Der feste MSI-Schnitt aus Version1.19 bleibt
unverändert. Die zusätzliche Fixture deckt noch keine EXE-Abnahme ab.
Die Quelle ist ein kleines, eigenständiges SYSTEM-/AMD64-Programm ohne freien
Pfad, URL oder Command. Genau `--quiet --norestart`; eigene HKLM64-Kennung und
33Byte-Nutzdatei getrennt vom MSI. Ausgangsbestand, Zielversion, Bytehash und
Noop-/Upgradegrenzen stehen im [README](../tools/windows-exe-fixture/README.md).
Nach dem ersten möglichen Schreibzugriff bleibt ein Fehler unbestimmt, ohne
Retry, Repair oder Rollback. Produktregistry und Nutzdatei müssen durch den
späteren Provider unabhängig gelesen werden. Geschützter Fixtureordner ist
Voraussetzung; keine stillschweigende ACL-Reparatur.
## Tatsächlich lokal ausgeführt
`python3 tools/windows-exe-fixture/build.py`, privater finaler Fall
`devstate/windows-exe-fixture/build-e85496e8-b6dd-4834-8c17-843ee5c5b3da/`.
Qualification-SHA256
`f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`.
Neun Quellen-/Norminputs vor und nach dem Build identisch; festes vorhandenes
Dockerimage, Netzwerk aus, Build unter Host-UID/GID, kein Zugriff auf Zugänge.
- Linux: reiner Zustands-/Argumentguard im Container kompiliert und tatsächlich
mit Exit0 ausgeführt, `-std=c11 -O2 -Wall -Wextra -Werror`.
- Windows: derselbe reine Guard und beide Installer mit GNU/Werror kompiliert,
nur gelinkt, **nicht ausgeführt**. AMD64-PE-Strukturen geprüft.
- Installer1.0:23040Bytes,
SHA256`9a972430614625b99985cd3db69f7f8f47e561c954697d57ba21e79fd5b787dc`.
- Installer1.1:23552Bytes,
SHA256`196d22893eaea74d332782c597d4cbce631522006786a4aae074ad0a2bea8c89`.
- Windowsguard:15360Bytes,
SHA256`1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf`.
- Linuxguard:16128Bytes,
SHA256`5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439`,
nur`libc.so.6`, höchste referenzierte glibc2.34.
- Installerimports ausschließlich ADVAPI32/bcrypt/KERNEL32/msvcrt. Originale
Linkdateien und getrennte Stripdateien erhalten. Fixtureartefakte ausdrücklich
unsigniert; kein produktiver Installer-/Signiernachweis.
Ein ursprünglicher Build kompilierte erfolgreich, konnte seine root-owned
600-Artefakte aber nicht im Hostprozess lesen. Dieser unvollständige Fall samt
Fehlerbeleg bleibt erhalten; der Builder verwendet danach explizit Host-UID/GID.
Der nächste erfolgreiche Zwischenbuild vor der ergänzten nativen AMD64-Prüfung
bleibt ebenfalls historisch erhalten. Nur der obige finale Fall ist der aktuelle
lokale Quellen-/Artefaktbeleg.
## Geplant, nicht ausgeführt
Zuerst denselben wirkungslosen Guard auf der Cloud-Linux-VM, danach auf Windows
nachweisen. Danach benötigen EXE-Rezept, Katalog-/Artefaktbindung, eigene
SYSTEM-Policy, Helpercache, Provider-Outcome-/Cancel-/Unknown-Grenzen und WebUI
jeweils ihre explizite Vertragserweiterung und Qualifikation. Es gibt keinen
Installationsbootstrap oder freigabefähigen RMM-EXE-Job in dieser Lieferung.
Native Erstinstallation,1.0→1.1, Noops, Registry64-/ACL-/Handle-/Teilwirkungs-
und Absturznachweise sind offen. Jede Zielwirkung braucht den festen realen
WebUI-Plan; Linux-/Windows-Guard oder Crossbuild ersetzt dies nicht.
+112
View File
@@ -0,0 +1,112 @@
# Windows Helper: begrenzte Transportbestätigung
Dieser Schnitt ist im isolierten Zweig `codex/windows-pipe-drain` implementiert.
Eine native Ausführung des neuen Framings und ein Komponentenupgrade sind noch
nicht nachgewiesen. Die bestehenden Nachweise des Agenten `89004ad3…` und Helpers
`e6aacbdd…` bleiben historische Belege ihres ursprünglichen Framings.
## Anlass und Beleggrenze
Beim tatsächlichen Agenten wurde `client_read_reply / HELPER_PIPE_IO / 233`
beobachtet; die Helperdiagnose war nicht vorhanden. Der bisherige Dienst rief
auch nach erfolgreichem Schreiben der Antwort sofort `DisconnectNamedPipe` auf.
Microsoft dokumentiert, dass dabei ungelesene Pipebytes verworfen werden. Das
ist ein konkreter möglicher Fehlerpfad, aber kein Nachweis, dass genau dieser
Pfad die beobachtete Störung verursacht hat.
[DisconnectNamedPipe](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)
Eine fehlende Diagnose beweist weder einen erfolgreichen Peercheck noch eine
bestimmte Ablehnung: strukturierte `Denied`-Antworten erzeugen keinen privaten
Pipefehlerbeleg, Connect-Leerlauf kann ohne Beleg enden, und das begrenzte
Diagnoseschreiben selbst kann fehlschlagen. Diese Pfade werden hier nicht
umgedeutet oder gelockert.
## Framing v2 und Reihenfolge
Agent und Helper verwenden ausschließlich `\\.\pipe\RustDiscovery-System-v2`.
Jeder JSON-Frame beginnt mit acht ASCIIbytes `RDPIPC02`, gefolgt von vier Bytes
Länge in Big Endian und den bisherigen, maximal 1 MiB großen JSONbytes.
V1 und V2 haben unterschiedliche Endpunkte; zusätzlich verweigert der V2-Parser
alte oder fremde Framingtags. Es gibt keinen stillen Fallback. Beide EXEs müssen
als gemeinsam qualifiziertes, gegenseitig gepinntes Paar bereitgestellt werden.
Die JSONschemas von Call/Reply, `helper.system.v1`, Systempolicy-Schema 1 und
RMM-Jobbytes ändern sich nicht.
Nach dem vollständigen Lesen der Antwort prüft der Agent weiterhin den tatsächlichen
Helperprozess, Schema, Challenge, Enrollmentbindung, Policyhash, Helperbinaryhash
und die Operation/Antwort-Zuordnung. Erst danach schreibt er genau 56 Bytes:
`RDPACK02` (8), ursprüngliche UUID-Challenge in UUID-Bytefolge (16), SHA-256 der
**exakt empfangenen JSON-Antwortbytes** (32). Es findet keine Re-Serialisierung
für diese Prüfsumme statt. Auch eine vollständig geprüfte `Denied`-Antwort wird
so transportseitig bestätigt, ohne sie in einen Erfolg umzuwandeln.
Der Helper prüft denselben bereits authentifizierten Peer vor dem Schreiben und
nach dem Lesen der Bestätigung. Schreiben, Empfang und Prüfung der Bestätigung
teilen dieselbe bisherige Antwortdeadline von fünf Sekunden; der Client behält
seine bisherige Gesamtdeadline. Erst danach trennt die Dienstschleife die Pipe.
Fehlende, falsche oder verspätete Bestätigung schließt den bestehenden Syncgate
und trennt die Verbindung über den bisherigen Fehlerpfad; statische Diagnosen
unterscheiden `server_drain_receipt` und `client_drain_receipt`. Es gibt keinen
weiteren Aufruf, Retry oder erneute Ausführung.
Diese Bestätigung bestätigt nur den Empfang der Antwortbytes. Sie ist kein
JobResult-, Journal-, SignedSync-, Grant-, Freigabe- oder Wirkungsbeleg und löscht
keinen dauerhaften Zustand. Ein bereits ausgeführter Auftrag wird durch einen
fehlenden Transport-ACK nicht zurückgenommen oder wiederholt.
`FlushFileBuffers` wird nicht verwendet: dieser synchrone Pipeaufruf wartet laut
Microsoft bis zum Lesen aller gepufferten Daten und bietet hier keine passende
begrenzte Warteoperation.
[FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers)
## Prüfung und verbleibender nativer Nachweis
Die bestehenden IPC-Codecfälle prüfen zusätzlich fremde/alte Frameversionen,
begrenzte Längen sowie manipulierte ACK-Tags, Challenge und Prüfsumme. Eine andere
JSON-Bytefolge mit gleichem JSON-Inhalt darf den ursprünglichen Frame nicht
bestätigen. Die bestehenden Unitfallzahlen bleiben dadurch unverändert.
Lokale Qualifikation wird separat in einem geschützten `devstate/`-Beleg mit
Quellen- und Artefakthashes erfasst. Cross-Clippy und Linken sind kein nativer
Pipebeleg. Vor einem Zielupgrade sind unabhängiger Quellreview, die nativen
Windows-Units des gleichen Manifests und ein eigener erhaltender Paarupgrade mit
explizitem Backup sowie anschließendem tatsächlichen Agent/Helper-Austausch
notwendig. Alle Produktgates bleiben geschlossen.
Lokale Ausführung: Default- und `system-helper`-Clippy für alle Windows-GNU-Targets
mit `-D warnings`, Release-Build beider EXEs und Linken beider Unitprogramme waren
erfolgreich. 61 gebundene Quelldateien blieben vor/nach dem Lauf gleich. Die
bestehenden 23 Library- und 7 Binary-Unitfälle sind weiterhin die **erwartete**
native Liste; hier wurde kein Windows-Testprogramm ausgeführt. Geschützter
Beleg: `devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json`.
## Separater Build-/Unitrunner
`deploy/windows/system_pipe_acceptance.py` erstellt einen neuen Pack unter
`devstate/windows-pipe-drain-build/`. Er prüft den unveränderten lokalen
Qualifikationsbeleg samt ursprünglichen Links und verwendet die bereits
bestandenen Clippy-/Release-/Unitlinkschritte wieder. Nur die fehlenden beiden
Release-Stateprobes werden ergänzt. Alle sechs Auslieferungsdateien erhalten
eine unveränderte `.linked`-Kopie; ausschließlich die Unit-Auslieferungskopien
werden von Debuginformationen befreit. Neue Quellen einschließlich Runner,
Compilerimage, Cargo-/Protoinputs und tatsächlich verwendeter Bootstrapmodule
sind vor/nach dem Build gebunden.
`--access-root` muss der ursprüngliche Hauptcheckout sein. Nur dort werden die
vorhandenen geschützten Zugangskonfigurationen für den bereits gepinnten
Bootstraptransport und die tatsächlichen Linux-80-/Windows-58-Corebelege gelesen.
Es werden keine Zugangsdaten oder Main-`devstate`-Bäume kopiert oder verlinkt.
Neue Build-, Upload- und Unitfallbelege gehören zum isolierten Pipeworktree.
Der Native-Unitfall verwendet den neuen Namespace `native-pipe-v2`. **Beide**
vollständigen nativen Listen müssen exakt den erwarteten 23 Library- und 7
Binary-Namen entsprechen, bevor irgendein Unitfall ausgeführt wird. Intent,
Listen, Start und einzelne Testergebnisse werden create-only gespeichert.
Nach einem Antwortverlust darf ausschließlich derselbe Fall gelesen werden;
auch ein fehlender oder unvollständiger Fall löst keinen erneuten Start aus.
Die Units laufen als Bootstrapadministrator, nicht als Produkt-LocalService,
und beweisen keinen tatsächlichen Pipeaustausch. Zentral gespeicherte
Gerätezähler und geschlossene Fault-/Policyflags werden vor/nach verglichen.
Der bestehende rohe `helper_peer_controls::raw`-Probe schreibt weiterhin einen
V1-Header. Sein Ablehnungsresultat ist deshalb **kein** V2-Peernegativnachweis;
Runner und Manifest behaupten ausdrücklich keine solche Qualifikation.
+4 -10
View File
@@ -16,8 +16,8 @@ Die zunächst tatsächlich lokal aus den Release-Testprogrammen ermittelten
Linuxlisten enthalten Domain20, Corecontracts8, Helpersync26, Agentsync26 und
Unixhelper21: insgesamt101 Fälle. Der zusätzliche MSI-Corevertrag heißt
`historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority`.
Die später tatsächlich nativ bestätigte Windowsliste enthält
20+7+26+26=79. Nur der Unix-OpenSSL-Vergleich und die gesamte
Die Windowsliste ist bis zur tatsächlichen nativen Ausgabe ausdrücklich
**erwartet**:20+7+26+26=79. Nur der Unix-OpenSSL-Vergleich und die gesamte
Unixhelper-Dateiguardsuite entfallen dort. Es gibt keine Mindestzahlen oder
Überspringen/Filtern von Fällen zur Erfüllung dieser Zahlen.
@@ -54,7 +54,7 @@ Die reine lokale Listenerhebung davor sowie Compiler-/Fehlerausgaben bleiben
privat erhalten. Es wurden durch diesen Arbeitsschritt keine VM-/SSH-Aufrufe,
Upload-, Server-, Dienst-, Registry- oder Installeraktionen ausgeführt.
## Native Abnahme und deren Grenzen
## Noch geplante native Abnahme
Nach unabhängiger Prüfung führt Root zuerst dieselben Lieferdateien auf der
tatsächlichen Linux-VM aus. Erst deren erfolgreicher, unveränderlich an dasselbe
@@ -77,13 +77,7 @@ bestanden: Fall `d015f861-e459-4b82-8ce5-460c3e4c570c`, gemeinsames Manifest
`2d96a07be72f3d71a8097510eb5f647ced6577086a45417c599b772018c29a53`,
Linuxproof-SHA256
`09fa24e32cd3f3563e80e91265c6cc7c612321b0fdd1febe7aef3ab6de53cf2a`.
Anschließend nach dem ausdrücklich bestätigten manuellen Konsolenneustart
auf der Windows-VM alle79Prüfungen ohne Skips bestanden: Fall
`1b1aeff3-a08f-4760-8225-8247df451fec`, Windowsproof-SHA256
`666ed196953abd0723de259a898b46c08ac84feee0140f1bb31d9db1fa1232c4`.
Der Windowsbeleg bindet denselben Manifest- und originalen Linuxproofhash.
Alle vier nativen Listen wurden vor irgendeinem Test exakt geprüft; keine
Produktdienste oder Produktdaten geändert. Der reine Unit-PASS
Windows79 weiterhin **geplant, nicht nativ ausgeführt**. Der Linux-Unit-PASS
ist keine Installation-/Upgrade-/Noop-Abnahme: jede tatsächliche
Paketwirkung benötigt weiterhin ihren eigenen unveränderlichen Antrag und die
Genehmigung in der WebUI.
+84
View File
@@ -0,0 +1,84 @@
# Getrennter MSI-Runtime-Unitpack
`deploy/windows_msi_runtime_acceptance.py` ergänzt ausschließlich die Units der
aktuellen Windows-Runtime. Er verändert keine historischen Runner oder
Manifeste. Der vorhandene Common-Pack bleibt mit seinen tatsächlichen
Linux101-/Windows79-Belegen separat gebunden; dessen gemeinsame Core-/Domain-/
Proto-/Cargoquellen sind zur Runtime identisch. Er wird nicht als Runtime-Test
umetikettiert.
## Tatsächliche lokale Qualifikation
Der eingefrorene Runtime-Quellenbeleg
`17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816`
bindet82 Compilerinputs und die unabhängig geprüften acht Runtimeänderungen.
Seine bestandenen Windows-GNU-Clippy-Läufe sowie seine unveränderten Windows-
Library-/Binary-Testdateien und Original-Links werden direkt wiederverwendet.
Es findet keine erneute Windows-Kompilierung oder Strip-Operation statt.
Zusätzlich gebaut und ausgeführt wurden nur die fehlende Linux-Release-
Library-Lieferdatei sowie deren Clippyprüfung. Die vollständige tatsächliche
Liste enthält10 Fälle: vier Journal-, drei Eventlog-Vertrags- und drei MSI-
Klassifikations-/Nachbedingungsfälle. Alle10 Lieferbyte-Tests bestanden ohne
Skip, Filter oder Fehler im isolierten lokalen Offlinecontainer. Die Datei
benötigt maximal GLIBC2.34; der unveränderte Original-Link ist archiviert.
Für Windows sind35 Library- und7 Binaryfälle **erwartet**, insgesamt42.
Die Namen wurden aus dem vorhandenen nativen23er-Profil und den additiven
kompilierten Testfällen vollständig aufgelöst und in den qualifizierten
Windowsbytes gefunden. Das ist kein ausgeführtes Windows-`--list` und kein
nativer42er-PASS. Die echte vollständige Liste muss vor dem ersten Windows-
Unitfall exakt übereinstimmen. Neue Testfälle wurden dafür nicht geschrieben.
Das neue Manifest bindet85 Inputs: die82 unveränderten Compilerinputs, den
neuen Runner und seine zwei Parser-/Bootstrapquellen. Python-Syntax,
PowerShell-AST und gezielte lokale Driverguards sind geprüft. Ein reiner
Mocklauf mit verlorener Antwort erlaubte nachfolgend nur den gleichen
Readbackfall; es erfolgte kein erneuter Upload oder Ausführungsaufruf.
Geschütztes Buildmanifest:
`devstate/windows-msi-runtime-units/build-9458b2f4-3e1b-4931-ae68-f9306993ce12/manifest.json`,
SHA256 `620255bcc57de32044cf23331511937565ac3415514f6ce4d953dad7c5286250`.
## Getrennt geplante native Schritte
Nach Root-Review wird zuerst ausschließlich die neue Linux-Library auf der
Cloud-Test-VM geprüft. Erst deren unveränderlicher gleiches-Manifest-PASS erlaubt
den neuen Windows-Unitfall. Beide Windowslisten müssen vor irgendeinem
Testfall stimmen. Die Vorgängerbelege Linux101/Windows79 bleiben dabei erhalten.
Alle neuen Bootstrapfälle, Listen und Resultate sind create-only; Antwortverlust
oder fehlende Teilresultate erlauben ausschließlich gleichnamigen Readback,
keinen Retry oder automatisches Resume. Prozess- und Ausgabe-Nachwartezeiten
sind begrenzt. Linux verwendet einen eigenen Netzwerknamespace und temporäre
Dateien; Windows läuft ehrlich als Bootstrapadministrator.
Native Ausführung liest den expliziten ursprünglichen Main-`--access-root`
ausschließlich für den vorhandenen gepinnten SSH-Transport. Keine Credential-
oder Main-`devstate`-Kopien/Symlinks. Neue Belege gehören zum isolierten
Runtimeworktree. Produktdienste, Journale, Identitäten, Schlüssel, Capabilities,
Clock- und SYSTEM-Policies werden nicht verändert.
Die unten belegte Linux10-Phase ist inzwischen nativ bestanden; die
Windows42-Phase bleibt **geplant, nicht ausgeführt**. Der Pack
belegt keine LocalService-/SYSTEM-Ausführung, keinen Cache-/PERSIST-Datei-
Parallelzugriff, keinen MSI-Installations-/Upgrade-/Noop-Job und keinen
vertrauenswürdigen Windowsclockadapter. Diese Abnahmen bleiben getrennt und
unterliegen vor jeder tatsächlichen RMM-Wirkung weiterhin der WebUI-Grenze.
## Tatsächlich auf der Cloud-Linux-VM bestanden
Root führte nach unabhängigem Driverreview dieselbe Lieferdatei auf der
permanenten x86-64-Linux-VM aus. Alle10Tests ohne Skips/Filter bestanden,
Fall `050c33bd-026e-4f89-83e5-d84b1d468827`, ManifestSHA256
`620255bcc57de32044cf23331511937565ac3415514f6ce4d953dad7c5286250`,
LinuxproofSHA256
`679ac094e60f6a5f18c2e461d55ef0a447517287c3eb80f2d9a1b9a5a5fe31dd`.
Die exakte vollständige native Liste wurde vor irgendeinem Test geprüft;
eigenes Bootstrap-Scratchverzeichnis, leere Prozessumgebung und neuer
Netzwerknamespace. Keine RMM-Dienste, Produktdaten, PKI oder Paketstände geändert.
Windows35+7 bleiben **erwartet, noch nicht nativ ausgeführt**. Der befristete
Entwicklungszugang war abgelaufen; Serverhälfte separat erneuert, konkrete
Konsolenrecovery durch den Benutzer noch offen. Kein Ersatz des Windowsbelegs
und keine Paket-/SYSTEM-/Clock-/Jobcapability aus dem Linux-PASS ableiten.
+89
View File
@@ -0,0 +1,89 @@
# Windows MSI runtime: implementierter, noch nicht nativ abgenommener Schnitt
Stand 2026-11-14, isolierter Zweig `codex/windows-msi-runtime`, Basis `66c1855`.
Dies ist ein Quellen-/Lokalnachweis. Es wurde damit kein Windows-Installer,
RMM-Job, Dienstwechsel oder Bootstrap am Ziel ausgeführt. Die nativen
Domain-/Backend-Nachweise des vorhergehenden M4-Schritts ersetzen die folgenden
noch offenen Runtime-Nachweise nicht.
## Implementierte Grenze
Der Network-Agent lädt ausschließlich das im genehmigten Originaljob gebundene
MSI-Artefakt über den bestehenden mTLS-Client und den festen Agent-Endpunkt.
Es gibt keine Installer-URL, Weiterleitung, Bearer-Abkürzung oder abgeschaltete
TLS-Prüfung. Länge und SHA-256 sind auf das Manifest und höchstens 256 KiB
begrenzt. Das Staging liegt unter dem festen Agentzustandsverzeichnis.
Der SYSTEM-Helper nimmt weiterhin nur die originale signierte Request an,
keinen Callerpfad und keine Installerbytes. Settings-Schema 1 bleibt SCM-only;
Schema 2 kann höchstens zwei genaue Recipe-SHA-256 freigeben. Fehlende neue
Settings-Felder werden beim Serialisieren ausgelassen; vorhandenes `null` ist
kein erlaubter Recipe-Allowlistwert. Die lokale Allowlist begrenzt ausschließlich
und ersetzt weder Plan, Startgrant, Clock noch signierten Sync.
Vor einer SYSTEM-Cachekopie persistiert der Helper den atomaren Originalstart
mit Verbrauch. Die Kopie verwendet den manifestabgeleiteten SHA-Pfad, prüft
Nicht-Reparse, Elternhandles, File-ID, Länge, Hash und die SYS/Admin-Cachegrenze.
Neue Cacheeinträge werden ohne Ersetzen bestehender Dateien veröffentlicht.
Cache/Staging müssen vorher eingerichtet sein; der Runtimecode repariert weder
ACLs noch Verzeichnisse. Der Provider hält eigene Archiv-/Prozesshandles.
Ein originales monotones Laufzeitbudget umfasst SYSTEM-Cacheaufbereitung,
MSI-Metadaten, unabhängige Bestandsprüfung, Noopentscheidung und Installerlauf.
Die festen Argumente und MSI-Tabellenprüfungen bleiben erhalten. Erfolg benötigt
unabhängige Product-/Family-/PackageCode-/Payload-Nachbedingungen; `3010` bleibt
als Rebootbedarf sichtbar, `1641` unklar, `1618` ein fehlgeschlagener eigener
Start. Noop hat keinen Installerexitcode. Weder automatischer Reboot noch
allgemeines `msiexec`-Kill oder automatischer Wiederholungsstart sind enthalten.
Die vorhandene Intentzeile besitzt zusätzlich eine dauerhafte, ausschließlich
verweigernde Abbruchmarkierung. Sie ist nur von 0 nach 1 änderbar; Originalbytes,
Grant und `may_have_dispatched` werden dabei nicht zurückgesetzt. Eine eng
geprüfte additive Migration akzeptiert nur die bisherige genaue Tabellen- und
Triggerdefinition. Der Helper liest die vollständige Originalbindung über eine
jeweils frische gewöhnliche Read-only-Verbindung vor Noop/Start und während der
Beobachtung. Fehlende, fehlerhafte oder gesperrte Beobachtung verweigert. Dies ist
keine zusätzliche Ausführungsautorität. Zwischen letzter Prüfung und OS-Start
bleibt das übliche kleine Rennen; es gibt kein behauptetes Rückgängigmachen.
Nach unklarem Timeout oder Beobachtungsfehler hält der Helper den eigenen Child,
Archivhandles und Originalgrant-/Requestbindung in einem ungeklärten Slot.
Weitere MSI-Starts werden bis zur Beobachtung desselben Prozessendes verweigert.
Ein späterer Exit ändert das bereits persistierte `unknown` nicht. Nach einem
Helperabsturz bleibt die ursprüngliche Ledger-Sperre bestehen. Intent, Abandon,
RawMirror und signierter Core-Sync behalten ihre strengen Originalbindungen;
keine Missing-row-Regel wurde gelockert.
## Tatsächlich lokale Prüfung
Der private Fall `qualified-ee6681c7-8d9d-4af9-8947-5325e1ea2e0f` unter
`devstate/windows-msi-runtime/` bindet 82 Compiler-/Manifestquellen vor und nach
allen qualifizierten Prüfungen identisch. Qualification-SHA-256:
`17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816`.
- Linux-Container: 10 Bibliothekstests ausgeführt, 10 bestanden, 0 ignoriert.
- Windows-GNU: Default- und SYSTEM-Feature-Alltargets-Clippy mit `-D warnings`
bestanden.
- Windows-GNU: Lib-/Agent-Bin-Unittests gelinkt, nicht ausgeführt.
- Windows-GNU: beide Releasebinaries gelinkt; AMD64-PE geprüft. Originale und
mit `--strip-all` bearbeitete Auslieferungsdateien sind getrennt erhalten.
- `git diff --check` bestanden. Keine Domain-/Core-/Server-/Web- oder
Root-Cargo-/Lockänderung.
Release-Auslieferung Agent:
`7d9b1221ccb3587437d0866296472330947a16445c4e40069981fc4197242d83`.
Release-Auslieferung Helper:
`96589d53d366a0ccbd60c301fd3d1f03cd4d9f93d85bdcb3ce9b7f4647afc273`.
Die Zwischenbelege vor der ergänzten laufenden Abbruchbeobachtung bleiben
historisch erhalten und sind nicht die finale Qualification.
## Noch offen
Die Windows-Unitbinaries, Cache-/Staging-ACLs und gehaltenen Handles, tatsächliche
PERSIST-Migration mit konkurrierender Deny-Lesung, Installer 1.0, MajorUpgrade
1.1, beide Noops und die Abbruch-/Unklarheitsfälle müssen auf der Windows-VM
nachgewiesen werden. Installerjobs benötigen jeweils die reale WebUI-Grenze.
Capabilityliste bleibt passiv, Clock-Gate unqualifiziert, Job-/Effektdefaults
bleiben geschlossen. Diese Implementierung behauptet weder native MSI-Abnahme
noch Windows-MVP-Abschluss. EXE, WinGet, allgemeine Installerargumente oder eine
neue Rebootstrecke gehören nicht zu diesem Schnitt.
+71
View File
@@ -0,0 +1,71 @@
# Eigene EXE-Fixture: nur Artefaktauthoring
Stand 2026-11-14. Dieser eigenständige C-Quelltext ist **nicht** in Domain,
Agent, Helper, Policy, Capability oder Backend eingebunden. Spezifikation1.19
bleibt der enge MSI-Vertrag; dieses zusätzliche EXE-Artefakt erteilt keine
Ausführungserlaubnis und ändert diesen Vertrag nicht. Keine Installation auf
Notebook oder VM durch den Builder. Die späteren EXE-Rezept-/Provider-/WebUI-
und nativen Fehlerabnahmen fehlen.
Die beiden fest kompilierten Versionen `10` / `11` bedeuten1.0.0 /1.1.0.
Einziger Installeraufruf ist jeweils `--quiet --norestart` in genau dieser
Reihenfolge. Es gibt keinen Pfad-, URL-, Command-, Repair-, Uninstall- oder
Rebootparameter. Der Prozess muss tatsächlich SYSTEM sein. Kein Netzwerk,
Dienststart, Unterprozess oder Neustartaufruf.
Feste eigene Nachbedingungen, getrennt vom MSI:
- Datei `C:\Program Files\RustDiscoveryFixtures\exe-payload.txt`, genau33Bytes.
- Version1.0.0: ASCII `RustDiscovery EXE fixture 1.0.0\r\n`, SHA256
`7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf`.
- Version1.1.0: ASCII `RustDiscovery EXE fixture 1.1.0\r\n`, SHA256
`e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0`.
- Registry **HKLM64** `SOFTWARE\RustDiscovery\ExeFixture`, genau7Werte und keine
Unterkeys: `ProductId=RustDiscovery.ExeFixture`, `Version`, `PayloadSHA256`,
`Architecture=x64`, `Context=machine` jeweilsREG_SZ; `PayloadBytes=33` und
`NoReboot=1` jeweilsREG_DWORD. Registry ist unabhängig von der Nutzdatei lesbar.
| Zielartefakt | Vollständiger Ausgangsbestand | Entscheidung |
| --- | --- | --- |
| 1.0 | Key und Datei fehlen | Erstinstallation |
| 1.0 | Registry und Datei exakt1.0 | Noop, keine Writeoperation |
| 1.0 | Exakt1.1 oder irgendein Teil-/Fremdzustand | Verweigern |
| 1.1 | Registry und Datei exakt1.0 | Upgrade auf1.1 |
| 1.1 | Registry und Datei exakt1.1 | Noop, keine Writeoperation |
| 1.1 | Leer oder irgendein Teil-/Fremdzustand | Verweigern |
Der bestehende geschützte Fixtureordner muss vorab vorhanden sein; der Installer
repariert keine Ordner/ACL. Gehaltene Elternhandles verweigern Umbenennung,
Reparse- und Hardlinkblätter werden verweigert, nur SYSTEM/Administrators dürfen
an Zielobjekten schreiben. Die Nutzdatei wird beim Upgrade anhand ihrer
ursprünglichen File-ID und Bytes erneut geprüft und exklusiv gegen weitere
Writer gehalten. Registrylinks/Fremdwerte werden nicht übernommen. Neue eigene
Datei-/Registryobjekte bekommen SYS/Admin-Schreibrechte und Benutzer-Leserechte;
eine vorhandene ACL wird nicht verändert.
**Nicht atomar:** Nutzdatei und Registry sind getrennte Wirkungen. Exit0 bedeutet
nur das vom Fixtureprozess selbst bestätigte vollständige Ergebnis oder Noop;
ein künftiger Provider muss Registry und Datei unabhängig nachprüfen. Exit10
verweigert vor einer eigenen Mutation. Exit20 bedeutet mögliche/teilweise Wirkung
nach der ersten Datei-/Keymutation, ausdrücklich **unknown**, kein Retry,
Rollback, Repair oder Freigabe des ursprünglichen Versuchs. Timeout/Prozessverlust
nach Übergabe kann unabhängig vom Exit ebenfalls unknown bedeuten. Diese eigenen
Exitcodes sind keine MSI-Exitsemantik.
## Lokaler Build
Geplanter Builderaufruf: `python3 tools/windows-exe-fixture/build.py`.
Der Builder verwendet nur das gepinnte vorhandene GNU-Buildimage, Netzwerk aus,
keine Hostinstallation. Er kompiliert/runnt zuerst den reinen Linux-Guard,
kompiliert dessen Windows-PE sowie beide Installer, erhält Original- und
Stripdateien und speichert einen create-only privaten Quell-/Compiler-/Hash-
Beleg unter `devstate/windows-exe-fixture/build-<UUID>/`. Er führt keine Windows-EXE
aus. Gehashte Fixtureartefakte sind zunächst bewusst **unsigniert**; das ist
kein Produktions-Signier- oder Installationsnachweis.
`contract_test.c` prüft ausschließlich die feste Zustands-/CLI-Matrix, ohne
Datei/Registry/Netz und ohne Simulation einer Installerwirkung. Derselbe Guard
muss später zuerst auf der Cloud-Linux-VM, danach auf der Windows-VM laufen.
Native HKLM64-/ACL-/File-ID-/Install-/Upgrade-/Noop-/Teilwirkungsnachweise sind
noch offen. Jede tatsächliche Installation benötigt einen neuen festen Plan und
die reale WebUI-Genehmigung; Bootstrap/SFTP allein ist kein Paketnachweis.
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Host-only, fixed-image EXE authoring. Never uploads or executes an installer."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import uuid
ROOT = Path(__file__).resolve().parents[2]
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
NAMES = ('contract.h', 'contract_test.c', 'fixture.c', 'build.py', 'README.md')
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def snapshot():
paths = [ROOT/'tools/windows-exe-fixture'/n for n in NAMES]
paths += [ROOT/n for n in ('AGENTS.md', 'Rust_RMM_Implementierungsspezifikation.md', 'docs/project-decisions.md', 'docs/development.md')]
return {str(p.relative_to(ROOT)): sha(p) for p in paths}
def write(path, value):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as f:
json.dump(value, f, indent=2, sort_keys=True);f.flush();os.fsync(f.fileno())
def main():
os.umask(0o077)
base = ROOT/'devstate/windows-exe-fixture';base.mkdir(parents=True, exist_ok=True, mode=0o700)
case = base/('build-'+str(uuid.uuid4()));case.mkdir(mode=0o700)
before = snapshot();write(case/'intent.json', {'image': IMAGE, 'source_files': before, 'build_only': True, 'native_installer_execution': False, 'network': False})
script = '''set -eu
cd /source
cc --version > /out/linux-compiler.txt
x86_64-w64-mingw32-gcc --version > /out/windows-compiler.txt
cc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -o /out/linux-precondition-guard
/out/linux-precondition-guard
x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -Wl,--no-insert-timestamp -o /out/windows-precondition-guard.original.exe
x86_64-w64-mingw32-strip --strip-all /out/windows-precondition-guard.original.exe -o /out/windows-precondition-guard.exe
for version in 10 11; do
x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror -municode -DFIXTURE_VERSION=$version fixture.c -Wl,--no-insert-timestamp,--nxcompat,--dynamicbase,--high-entropy-va -ladvapi32 -lbcrypt -o /out/RustDiscoveryExeFixture-$version.original.exe
x86_64-w64-mingw32-strip --strip-all /out/RustDiscoveryExeFixture-$version.original.exe -o /out/RustDiscoveryExeFixture-$version.exe
x86_64-w64-mingw32-objdump -p /out/RustDiscoveryExeFixture-$version.exe > /out/imports-$version.log
done
readelf -h /out/linux-precondition-guard > /out/linux-elf-header.log
readelf -d /out/linux-precondition-guard > /out/linux-elf-needed.log
readelf --version-info /out/linux-precondition-guard > /out/linux-elf-versions.log
chmod 600 /out/*
'''
args = ['docker', 'run', '--rm', '--user', str(os.getuid())+':'+str(os.getgid()), '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=64m', '-v', str(ROOT/'tools/windows-exe-fixture')+':/source:ro', '-v', str(case)+':/out', '--entrypoint', 'sh', IMAGE, '-c', script]
result = subprocess.run(args, capture_output=True, timeout=120)
write(case/'compiler-output.json', {'exit_code': result.returncode, 'stdout': result.stdout.decode(errors='replace'), 'stderr': result.stderr.decode(errors='replace')})
after = snapshot();write(case/'source-after.json', after)
if result.returncode != 0 or before != after:
raise RuntimeError('FIXTURE_BUILD_FAILED_RETAINED_'+case.name)
artifacts = {}
for path in sorted(case.glob('*.exe')):
b = path.read_bytes();pe = int.from_bytes(b[60:64], 'little')
if b[:2] != b'MZ' or b[pe:pe+4] != b'PE\0\0' or int.from_bytes(b[pe+4:pe+6], 'little') != 0x8664:
raise RuntimeError('FIXTURE_PE_AMD64_REQUIRED')
if not '.original.' in path.name and len(b) > 262144:
raise RuntimeError('FIXTURE_ARTIFACT_BUDGET')
artifacts[path.name] = {'sha256': sha(path), 'bytes': len(b), 'architecture': 'AMD64', 'authenticode': 'not_signed_fixture_only'}
artifacts['linux-precondition-guard'] = {'sha256': sha(case/'linux-precondition-guard'), 'bytes': (case/'linux-precondition-guard').stat().st_size}
imports = {str(v): [l.strip().split(':', 1)[1].strip() for l in (case/f'imports-{v}.log').read_text().splitlines() if 'DLL Name:' in l] for v in (10, 11)}
write(case/'qualification.json', {'image': IMAGE, 'source_files': before, 'source_before_after_equal': True, 'linux_pure_precondition_guard': 'passed_container_only', 'windows_pure_guard': 'linked_not_executed', 'windows_installer': 'linked_not_executed', 'cloud_linux_native_guard': 'not_executed', 'windows_native': 'not_executed', 'artifacts': artifacts, 'imports': imports, 'no_installer_run': True, 'no_upload': True})
print(json.dumps({'case': str(case.relative_to(ROOT)), 'qualification_sha256': sha(case/'qualification.json'), 'artifacts': artifacts}))
if __name__ == '__main__':
main()
+27
View File
@@ -0,0 +1,27 @@
#ifndef RMM_EXE_FIXTURE_CONTRACT_H
#define RMM_EXE_FIXTURE_CONTRACT_H
#include <wchar.h>
/* This authoring contract is NOT exported by an agent, helper or domain crate. */
enum fixture_state { FIXTURE_ABSENT, FIXTURE_10, FIXTURE_11, FIXTURE_CONFLICT };
enum fixture_step { FIXTURE_DENY, FIXTURE_INSTALL, FIXTURE_UPGRADE, FIXTURE_NOOP };
static enum fixture_state fixture_state(unsigned registry, unsigned payload) {
if (registry == 0 && payload == 0) return FIXTURE_ABSENT;
if (registry == 10 && payload == 10) return FIXTURE_10;
if (registry == 11 && payload == 11) return FIXTURE_11;
return FIXTURE_CONFLICT;
}
static enum fixture_step fixture_step(unsigned desired, enum fixture_state before) {
if (desired == 10) {
if (before == FIXTURE_ABSENT) return FIXTURE_INSTALL;
if (before == FIXTURE_10) return FIXTURE_NOOP;
} else if (desired == 11) {
if (before == FIXTURE_10) return FIXTURE_UPGRADE;
if (before == FIXTURE_11) return FIXTURE_NOOP;
}
return FIXTURE_DENY;
}
static int fixture_arguments(int argc, const wchar_t *const *argv) {
return argc == 3 && wcscmp(argv[1], L"--quiet") == 0
&& wcscmp(argv[2], L"--norestart") == 0;
}
#endif
+25
View File
@@ -0,0 +1,25 @@
/* Pure guard only. No OS, registry, file, installer or network operations. */
#include "contract.h"
#include <assert.h>
int main(void) {
const enum fixture_step expected[2][4] = {
{ FIXTURE_INSTALL, FIXTURE_NOOP, FIXTURE_DENY, FIXTURE_DENY },
{ FIXTURE_DENY, FIXTURE_UPGRADE, FIXTURE_NOOP, FIXTURE_DENY }
};
const wchar_t *good[] = { L"fixture.exe", L"--quiet", L"--norestart" };
const wchar_t *foreign[] = { L"fixture.exe", L"--quiet", L"C:\\somewhere" };
for (unsigned target = 0; target < 2; ++target)
for (unsigned state = 0; state < 4; ++state)
assert(fixture_step(10 + target, (enum fixture_state)state) == expected[target][state]);
assert(fixture_step(12, FIXTURE_ABSENT) == FIXTURE_DENY);
assert(fixture_state(0, 0) == FIXTURE_ABSENT);
assert(fixture_state(10, 10) == FIXTURE_10);
assert(fixture_state(11, 11) == FIXTURE_11);
assert(fixture_state(0, 10) == FIXTURE_CONFLICT);
assert(fixture_state(10, 11) == FIXTURE_CONFLICT);
assert(fixture_state(99, 99) == FIXTURE_CONFLICT);
assert(fixture_arguments(3, good));
assert(!fixture_arguments(2, good));
assert(!fixture_arguments(3, foreign));
return 0;
}
+208
View File
@@ -0,0 +1,208 @@
/* Fixed own EXE fixture authoring source. Not an exported RMM provider.
* No shell, network, service, reboot, repair, retry or caller-selected target.
* An error after the first file/key mutation returns20: effect unresolved.
*/
#define _WIN32_WINNT 0x0a00
#include <windows.h>
#include <sddl.h>
#include <aclapi.h>
#include <bcrypt.h>
#include <stdio.h>
#include <string.h>
#include "contract.h"
#if !defined(FIXTURE_VERSION) || (FIXTURE_VERSION != 10 && FIXTURE_VERSION != 11)
#error Compile exactly one fixed fixture version10 or11
#endif
static const wchar_t *const ROOT = L"C:\\Program Files\\RustDiscoveryFixtures";
static const wchar_t *const FILE_PATH = L"C:\\Program Files\\RustDiscoveryFixtures\\exe-payload.txt";
static const wchar_t *const PARENT_KEY = L"SOFTWARE\\RustDiscovery";
static const wchar_t *const PRODUCT_KEY = L"ExeFixture";
static const wchar_t *const HASH10 = L"7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf";
static const wchar_t *const HASH11 = L"e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0";
static const char *payload(unsigned version) {
return version == 10 ? "RustDiscovery EXE fixture 1.0.0\r\n" : "RustDiscovery EXE fixture 1.1.0\r\n";
}
static const wchar_t *version_text(unsigned version) {return version == 10 ? L"1.0.0" : L"1.1.0";}
static const wchar_t *hash_text(unsigned version) {return version == 10 ? HASH10 : HASH11;}
static int privileged_sid(PSID sid) {
return IsWellKnownSid(sid, WinLocalSystemSid) || IsWellKnownSid(sid, WinBuiltinAdministratorsSid);
}
static int protected_object(HANDLE handle, SE_OBJECT_TYPE kind, DWORD read_mask) {
PSID owner = NULL; PACL dacl = NULL; PSECURITY_DESCRIPTOR sd = NULL;
if (GetSecurityInfo(handle, kind, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&owner, NULL, &dacl, NULL, &sd) != ERROR_SUCCESS) return 0;
int valid = owner && privileged_sid(owner) && dacl && dacl->AceCount;
for (DWORD i = 0; valid && i < dacl->AceCount; ++i) {
PVOID raw = NULL;
if (!GetAce(dacl, i, &raw)) {valid = 0; break;}
ACCESS_ALLOWED_ACE *ace = raw;
if (ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE
|| ace->Header.AceSize < sizeof(*ace)) {valid = 0; break;}
if (ace->Header.AceFlags & INHERIT_ONLY_ACE) continue;
PSID who = &ace->SidStart;
if (!IsValidSid(who) || (!privileged_sid(who) && (ace->Mask & ~read_mask))) valid = 0;
}
LocalFree(sd); return valid;
}
static int system_process(void) {
HANDLE token = NULL; _Alignas(8) BYTE buffer[128]; DWORD bytes = sizeof(buffer);
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return 0;
int ok = GetTokenInformation(token, TokenUser, buffer, bytes, &bytes)
&& IsWellKnownSid(((TOKEN_USER *)buffer)->User.Sid, WinLocalSystemSid);
CloseHandle(token); return ok;
}
static int regular(HANDLE file, int directory, BY_HANDLE_FILE_INFORMATION *info) {
return GetFileInformationByHandle(file, info)
&& !(info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
&& !!(info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == directory
&& (directory || info->nNumberOfLinks == 1);
}
static int same_file(const BY_HANDLE_FILE_INFORMATION *a, const BY_HANDLE_FILE_INFORMATION *b) {
return a->dwVolumeSerialNumber == b->dwVolumeSerialNumber
&& a->nFileIndexHigh == b->nFileIndexHigh && a->nFileIndexLow == b->nFileIndexLow;
}
static int file_version(HANDLE file) {
BY_HANDLE_FILE_INFORMATION info; BYTE bytes[64], digest[32]; DWORD read = 0;
BCRYPT_ALG_HANDLE alg = NULL; BCRYPT_HASH_HANDLE hash = NULL; BYTE *object = NULL;
DWORD size = 0, got = 0; wchar_t hex[65]; int version = 99;
if (!regular(file, 0, &info) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)
|| info.nFileSizeHigh || info.nFileSizeLow != 33
|| SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER
|| !ReadFile(file, bytes, sizeof(bytes), &read, NULL) || read != 33) return 99;
if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) < 0) goto done;
if (BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&size, sizeof(size), &got, 0) < 0
|| size == 0 || size > 4096) goto done;
object = HeapAlloc(GetProcessHeap(), 0, size); if (!object) goto done;
if (BCryptCreateHash(alg, &hash, object, size, NULL, 0, 0) < 0
|| BCryptHashData(hash, bytes, read, 0) < 0
|| BCryptFinishHash(hash, digest, sizeof(digest), 0) < 0) goto done;
for (unsigned i = 0; i < 32; ++i) {
static const wchar_t digits[] = L"0123456789abcdef";
hex[2*i] = digits[digest[i] >> 4]; hex[2*i+1] = digits[digest[i] & 15];
}
hex[64] = 0;
if (!wcscmp(hex, HASH10) && !memcmp(bytes, payload(10), 33)) version = 10;
if (!wcscmp(hex, HASH11) && !memcmp(bytes, payload(11), 33)) version = 11;
done:
if (hash) BCryptDestroyHash(hash);
if (object) HeapFree(GetProcessHeap(), 0, object);
if (alg) BCryptCloseAlgorithmProvider(alg, 0);
return version;
}
static int string_value(HKEY key, const wchar_t *name, const wchar_t *expected) {
wchar_t data[128]; DWORD type = 0, size = sizeof(data);
return RegQueryValueExW(key, name, NULL, &type, (BYTE *)data, &size) == ERROR_SUCCESS
&& type == REG_SZ && size == (wcslen(expected) + 1) * sizeof(wchar_t)
&& !memcmp(data, expected, size);
}
static int dword_value(HKEY key, const wchar_t *name, DWORD expected) {
DWORD data = 0, type = 0, size = sizeof(data);
return RegQueryValueExW(key, name, NULL, &type, (BYTE *)&data, &size) == ERROR_SUCCESS
&& type == REG_DWORD && size == sizeof(data) && data == expected;
}
static int not_registry_link(HKEY key) {
DWORD type = 0, size = 0;
LSTATUS s = RegQueryValueExW(key, L"SymbolicLinkValue", NULL, &type, NULL, &size);
return s == ERROR_FILE_NOT_FOUND; /* Never follow/adopt a caller-created link. */
}
static int registry_version(void) {
HKEY parent = NULL, key = NULL; DWORD subkeys = 0, values = 0; int version = 99;
LSTATUS s = RegOpenKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, REG_OPTION_OPEN_LINK,
KEY_READ | KEY_WOW64_64KEY, &parent);
if (s == ERROR_FILE_NOT_FOUND) return 0;
if (s != ERROR_SUCCESS) return 99;
if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done;
s = RegOpenKeyExW(parent, PRODUCT_KEY, REG_OPTION_OPEN_LINK, KEY_READ | KEY_WOW64_64KEY, &key);
if (s == ERROR_FILE_NOT_FOUND) {version = 0; goto done;}
if (s != ERROR_SUCCESS || !protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ)
|| !not_registry_link(key)) goto done;
if (RegQueryInfoKeyW(key, NULL, NULL, NULL, &subkeys, NULL, NULL, &values,
NULL, NULL, NULL, NULL) != ERROR_SUCCESS || subkeys || values != 7) goto done;
unsigned candidate = string_value(key, L"Version", L"1.0.0") ? 10
: string_value(key, L"Version", L"1.1.0") ? 11 : 0;
if (candidate && string_value(key, L"ProductId", L"RustDiscovery.ExeFixture")
&& string_value(key, L"PayloadSHA256", hash_text(candidate))
&& string_value(key, L"Architecture", L"x64") && string_value(key, L"Context", L"machine")
&& dword_value(key, L"PayloadBytes", 33) && dword_value(key, L"NoReboot", 1)) version = (int)candidate;
done:
if (key) RegCloseKey(key);
if (parent) RegCloseKey(parent);
return version;
}
static int set_string(HKEY key, const wchar_t *name, const wchar_t *value) {
return RegSetValueExW(key, name, 0, REG_SZ, (const BYTE *)value,
(DWORD)((wcslen(value)+1)*sizeof(wchar_t))) == ERROR_SUCCESS;
}
static int write_registry(unsigned version) {
HKEY parent = NULL, key = NULL; PSECURITY_DESCRIPTOR sd = NULL; int ok = 0;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
L"D:P(A;;KA;;;SY)(A;;KA;;;BA)(A;;KR;;;BU)", SDDL_REVISION_1, &sd, NULL)) return 0;
SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE}; DWORD disposition = 0, bytes = 33, no_reboot = 1;
if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE,
KEY_READ | KEY_CREATE_SUB_KEY | KEY_WOW64_64KEY, &sa, &parent, &disposition) != ERROR_SUCCESS) goto done;
if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done;
if (RegCreateKeyExW(parent, PRODUCT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE,
KEY_READ | KEY_SET_VALUE | KEY_WOW64_64KEY, &sa, &key, &disposition) != ERROR_SUCCESS) goto done;
if (!protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(key)) goto done;
ok = set_string(key, L"ProductId", L"RustDiscovery.ExeFixture")
&& set_string(key, L"Version", version_text(version))
&& set_string(key, L"PayloadSHA256", hash_text(version))
&& set_string(key, L"Architecture", L"x64") && set_string(key, L"Context", L"machine")
&& RegSetValueExW(key, L"PayloadBytes", 0, REG_DWORD, (BYTE *)&bytes, sizeof(bytes)) == ERROR_SUCCESS
&& RegSetValueExW(key, L"NoReboot", 0, REG_DWORD, (BYTE *)&no_reboot, sizeof(no_reboot)) == ERROR_SUCCESS
&& RegFlushKey(key) == ERROR_SUCCESS;
done:
if (key) RegCloseKey(key);
if (parent) RegCloseKey(parent);
LocalFree(sd); return ok;
}
int wmain(int argc, wchar_t **argv) {
HANDLE parents[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
const wchar_t *const directories[] = {L"C:\\", L"C:\\Program Files", ROOT};
HANDLE file = INVALID_HANDLE_VALUE; BY_HANDLE_FILE_INFORMATION original = {0}, current;
int result = 10, observed_file = 0, observed_registry; PSECURITY_DESCRIPTOR sd = NULL;
SYSTEM_INFO platform; GetNativeSystemInfo(&platform);
if (platform.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64
|| !fixture_arguments(argc, (const wchar_t *const *)argv) || !system_process()) return 10;
for (unsigned i = 0; i < 3; ++i) {
parents[i] = CreateFileW(directories[i], FILE_READ_ATTRIBUTES | READ_CONTROL,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (parents[i] == INVALID_HANDLE_VALUE || !regular(parents[i], 1, &current)) goto done;
}
if (!protected_object(parents[2], SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done;
file = CreateFileW(FILE_PATH, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (file == INVALID_HANDLE_VALUE) {
if (GetLastError() != ERROR_FILE_NOT_FOUND) goto done;
} else {
if (!regular(file, 0, &original)) goto done;
observed_file = file_version(file);
}
observed_registry = registry_version();
enum fixture_step step = fixture_step(FIXTURE_VERSION, fixture_state((unsigned)observed_registry, (unsigned)observed_file));
if (step == FIXTURE_NOOP) {result = 0; goto done;}
if (step == FIXTURE_DENY) goto done;
if (file != INVALID_HANDLE_VALUE) {CloseHandle(file); file = INVALID_HANDLE_VALUE;}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
L"D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;BU)", SDDL_REVISION_1, &sd, NULL)) goto done;
SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE};
file = CreateFileW(FILE_PATH, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa,
step == FIXTURE_INSTALL ? CREATE_NEW : OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (file == INVALID_HANDLE_VALUE) goto done;
/* CREATE_NEW itself is the first possible mutation (an empty own file). */
if (step == FIXTURE_INSTALL) result = 20;
if (!regular(file, 0, &current) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done;
if (step == FIXTURE_UPGRADE && (!same_file(&original, &current) || file_version(file) != 10)) goto done;
if (registry_version() != observed_registry) goto done;
/* From this boundary onwards every error is effect-unresolved, no rollback. */
result = 20; DWORD written = 0;
if (SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER
|| !WriteFile(file, payload(FIXTURE_VERSION), 33, &written, NULL) || written != 33
|| !SetEndOfFile(file) || !FlushFileBuffers(file) || !write_registry(FIXTURE_VERSION)) goto done;
if (file_version(file) == FIXTURE_VERSION && registry_version() == FIXTURE_VERSION) result = 0;
done:
if (sd) LocalFree(sd);
if (file != INVALID_HANDLE_VALUE) CloseHandle(file);
for (unsigned i = 0; i < 3; ++i) if (parents[i] != INVALID_HANDLE_VALUE) CloseHandle(parents[i]);
return result;
}