Compare commits

..
7 Commits
Author SHA1 Message Date
kevin_janssen c02f1cc74f Merge commit 'cfbf1f7'
Rust development slice / linux (push) Failing after 6s
2026-11-15 01:59:35 +01:00
kevin_janssen 0d6d6551bc Merge branch 'codex/signed-clock' 2026-11-15 01:59:35 +01:00
kevin_janssen 2c0f07046e Qualify protected Chrony socket permissions on cloud Linux
Rust development slice / linux (push) Failing after 6s
2026-11-15 01:57:21 +01:00
kevin_janssen c68bc0153e Repair only the missing stopped SYSTEM capture fixture on Windows
Rust development slice / linux (push) Failing after 6s
2026-11-15 01:56:50 +01:00
kevin_janssen cfbf1f7bfc Verify health against exact retained original sync timestamps
Rust development slice / linux (push) Failing after 6s
2026-11-15 01:07:19 +01:00
kevin_janssen a56474805c Connect one-shot Linux updater worker flow behind the census gate
Rust development slice / linux (push) Failing after 7s
2026-11-15 00:18:43 +01:00
kevin_janssen d77279fb84 Expose the existing helper sync lease deadline without changing readiness
Rust development slice / linux (push) Failing after 7s
2026-11-15 00:01:16 +01:00
22 changed files with 2312 additions and 59 deletions
@@ -204,6 +204,10 @@ impl<V: Ed25519Verifier> HelperSync<V> {
self.lease = None;
self.capture = None;
}
/// Read-only bound of the existing confirmed lease; creates no readiness.
pub fn validity_deadline(&self) -> Option<DateTime<Utc>> {
self.lease.as_ref().map(|lease| lease.until)
}
pub fn active_generation(&self) -> Option<u64> {
self.lease.as_ref().map(|lease| lease.generation)
}
+1
View File
@@ -10,3 +10,4 @@ pub mod ledger;
pub mod reconcile;
pub mod update_handoff;
pub mod update_health_inventory;
pub mod update_health_sync;
+323
View File
@@ -0,0 +1,323 @@
//! Read-only original HelperSync evidence. Exact UTC bodies, not quantized
//! receipt scalars, bound the real local application time. Creates no lease.
use crate::{
auth::Binding,
helper_reconcile::{ExecutorLedgerGuard, SignedResponse},
reconcile::{Channel, verify_response},
update_handoff::{self, AppliedUpdateSync},
};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::{
agent_update::{UpdateInflightProof, inflight_decision, verify_inflight_proof},
jobs::hash,
reconciliation::ReconcileDecisionPayload,
};
use rmm_protocol::{SyncRequest, SyncResponse};
use rmm_updater_handoff::{Handoff, HealthReceipt, Phase};
use rusqlite::Connection;
use uuid::Uuid;
/// No deserializer or external construction. Raw request/response hashes and
/// actual local application come from the SAME guarded existing helper ledger.
pub struct Round {
applied: AppliedUpdateSync,
request: SyncRequest,
decision: ReconcileDecisionPayload,
}
impl Round {
pub fn applied(&self) -> &AppliedUpdateSync {
&self.applied
}
pub fn decision(&self) -> &ReconcileDecisionPayload {
&self.decision
}
}
pub fn read_round(
db: &Connection,
guard: &impl ExecutorLedgerGuard,
binding: &Binding,
grant: Uuid,
id: Uuid,
) -> Result<Round> {
guard.check(db)?;
let (request_len, response_len): (usize, usize) = db.query_row(
"SELECT length(request),length(response) FROM helper_sync_decisions WHERE decision_id=?1",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
ensure!(
request_len > 0
&& request_len <= rmm_domain::MAX_MESSAGE
&& response_len > 0
&& response_len <= 4 * rmm_domain::MAX_MESSAGE + 1024,
"UPDATE_HEALTH_STORED_SYNC_SIZE"
);
let applied = update_handoff::read_applied_sync(db, guard, grant, id)?;
let (raw, signed): (Vec<u8>, Vec<u8>) = db.query_row(
"SELECT request,response FROM helper_sync_decisions WHERE decision_id=?1",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let request = SyncRequest::decode(raw.as_slice())?;
let signed: SignedResponse = serde_json::from_slice(&signed)?;
let response = SyncResponse {
decision_bytes: signed.decision_bytes,
signature: signed.signature,
};
ensure!(
request.encode_to_vec() == raw
&& hash(&raw) == applied.request_sha256
&& hash(&response.encode_to_vec()) == applied.response_protobuf_sha256,
"UPDATE_HEALTH_STORED_SYNC_BYTES"
);
let unverified: ReconcileDecisionPayload = serde_json::from_slice(&response.decision_bytes)?;
// Historical verification only. Current clock/owner/boot/policy remain the
// calling Fullguard's independent prerequisites, never renewed by this read.
let decision = verify_response(
binding,
&request,
&Channel {
boot_id: unverified.boot_id,
connection_generation: unverified.connection_generation,
},
&response,
unverified.issued_at,
)?;
ensure!(
decision.decision_id == id && serde_json::to_vec(&decision)? == response.decision_bytes,
"UPDATE_HEALTH_ORIGINAL_SYNC_CODEC"
);
guard.check(db)?;
Ok(Round {
applied,
request,
decision,
})
}
pub struct VerifiedSpan {
applied: AppliedUpdateSync,
lower: DateTime<Utc>,
upper: DateTime<Utc>,
}
impl VerifiedSpan {
pub fn applied(&self) -> &AppliedUpdateSync {
&self.applied
}
pub fn lower(&self) -> DateTime<Utc> {
self.lower
}
pub fn upper(&self) -> DateTime<Utc> {
self.upper
}
}
pub fn verified_span(
db: &Connection,
guard: &impl ExecutorLedgerGuard,
binding: &Binding,
header: &Handoff,
receipt: &HealthReceipt,
health_key: [u8; 32],
) -> Result<VerifiedSpan> {
guard.check(db)?;
let applied = read_round(
db,
guard,
binding,
header.attempt.grant_id,
receipt.signed_sync_decision_id,
)?;
ensure!(
applied.applied.request_sha256 == receipt.signed_sync_request_sha256
&& applied.applied.response_protobuf_sha256 == receipt.signed_sync_response_sha256
&& receipt.inventory_ack_sha256 == applied.applied.response_protobuf_sha256
&& applied
.decision
.acknowledged_message_ids
.contains(&receipt.inventory_message_id),
"UPDATE_HEALTH_ORIGINAL_APPLIED_OR_ACK"
);
let prefix = services_prefix(&applied, header, receipt, health_key)?;
let original_prefix = UpdateInflightProof::from_bytes(&prefix).map_err(anyhow::Error::msg)?;
let current = update_handoff::current_proof(db, guard, header.attempt.grant_id)?
.context("UPDATE_HEALTH_ORIGINAL_CURRENT_PREFIX_MISSING")?;
ensure!(
original_prefix.delegation == current.delegation
&& original_prefix.events.len() <= current.events.len()
&& current.events[..original_prefix.events.len()] == original_prefix.events,
"UPDATE_HEALTH_ORIGINAL_PREFIX_NOT_RETAINED"
);
let invalid:usize=db.query_row("SELECT count(*) FROM agent_update_sync_applied WHERE grant_id=?1 AND length(decision_id)<>36",[header.attempt.grant_id.to_string()],|r|r.get(0))?;
ensure!(invalid == 0, "UPDATE_HEALTH_ORIGINAL_SYNC_ID_SIZE");
let mut query=db.prepare("SELECT decision_id FROM agent_update_sync_applied WHERE grant_id=?1 ORDER BY decision_id LIMIT 1025")?;
let ids = query
.query_map([header.attempt.grant_id.to_string()], |r| {
r.get::<_, String>(0)
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
ensure!(ids.len() <= 1024, "UPDATE_HEALTH_ORIGINAL_SYNC_LIMIT");
let mut confirming = None;
for id in ids {
let id: Uuid = id.parse()?;
if id == receipt.signed_sync_decision_id {
continue;
}
let (len,): (usize,) = db.query_row(
"SELECT length(request) FROM helper_sync_decisions WHERE decision_id=?1",
[id.to_string()],
|r| Ok((r.get(0)?,)),
)?;
ensure!(
len > 0 && len <= rmm_domain::MAX_MESSAGE,
"UPDATE_HEALTH_CONFIRMING_SIZE"
);
let raw: Vec<u8> = db.query_row(
"SELECT request FROM helper_sync_decisions WHERE decision_id=?1",
[id.to_string()],
|r| r.get(0),
)?;
let request = SyncRequest::decode(raw.as_slice())?;
if request.previous_decision_id != receipt.signed_sync_decision_id.to_string()
|| request.helper_previous_decision_id != receipt.signed_sync_decision_id.to_string()
{
continue;
}
// Hash/signature/application checks are mandatory AFTER this cheap
// candidate selection too. Caller request fields never prove an apply.
let round = read_round(db, guard, binding, header.attempt.grant_id, id)?;
ensure!(
services_prefix(&round, header, receipt, health_key)? == prefix && confirming.is_none(),
"UPDATE_HEALTH_CONFIRMING_PREFIX_OR_FORK"
);
confirming = Some(round);
}
let confirming = confirming.context("UPDATE_HEALTH_ACTUAL_CONFIRMING_ROUND_MISSING")?;
require_exact_span(
applied.decision.issued_at,
applied.applied.applied_at,
confirming.decision.issued_at,
receipt.signed_sync_applied_at,
)?;
ensure!(
applied.applied.applied_at < applied.decision.valid_until,
"UPDATE_HEALTH_ACTUAL_APPLY_EXPIRED"
);
guard.check(db)?;
Ok(VerifiedSpan {
applied: applied.applied,
lower: applied.decision.issued_at,
upper: confirming.decision.issued_at,
})
}
fn services_prefix(
round: &Round,
header: &Handoff,
receipt: &HealthReceipt,
key: [u8; 32],
) -> Result<Vec<u8>> {
let request = &round.request;
let decision = &round.decision;
ensure!(
!decision.ready
&& !decision.helper_ready
&& request.journal_complete
&& decision.connection_generation == receipt.connection_generation
&& decision.boot_id == header.boot_id
&& request.journal_id == header.agent_journal_id.to_string()
&& request.helper_journal_id == header.helper_journal_id.to_string(),
"UPDATE_HEALTH_CONFIRMING_CHANNEL"
);
let mut local = request.attempts.iter().filter(|a| {
a.job_id == header.attempt.job_id.to_string()
&& a.attempt_id == header.attempt.attempt_id.to_string()
});
let local = local
.next()
.context("UPDATE_HEALTH_ORIGINAL_ATTEMPT_MISSING")?
.clone();
ensure!(
request
.attempts
.iter()
.filter(|a| a.job_id == header.attempt.job_id.to_string()
&& a.attempt_id == header.attempt.attempt_id.to_string())
.count()
== 1,
"UPDATE_HEALTH_ORIGINAL_ATTEMPT_DUPLICATE"
);
let proof =
UpdateInflightProof::from_bytes(&local.update_handoff_bytes).map_err(anyhow::Error::msg)?;
let (observed, journal) = verify_inflight_proof(&proof, key).map_err(anyhow::Error::msg)?;
ensure!(
observed.bytes()? == header.bytes()?
&& journal.phase() == Phase::ServicesStarted
&& local.grant_id == header.attempt.grant_id.to_string()
&& local.consumption == "consumed"
&& local.state == "running"
&& local.job_payload_hash == header.attempt.job_payload_sha256
&& local.original_boot_id == header.boot_id.to_string()
&& local.outcome_bytes.is_empty()
&& local.outcome_sha256.is_empty()
&& local.result.is_none()
&& local.result_envelope.is_none(),
"UPDATE_HEALTH_ORIGINAL_INFLIGHT"
);
let signed = decision
.attempts
.iter()
.filter(|a| a.job_id == header.attempt.job_id && a.attempt_id == header.attempt.attempt_id)
.collect::<Vec<_>>();
ensure!(signed.len() == 1, "UPDATE_HEALTH_SIGNED_ATTEMPT");
let signed = signed[0];
ensure!(
signed.update_inflight.as_ref()
== Some(&inflight_decision(&proof, key).map_err(anyhow::Error::msg)?)
&& signed.grant_id == Some(header.attempt.grant_id)
&& signed.authorization_id == Some(header.attempt.authorization_id)
&& signed.plan_hash.as_deref() == Some(header.attempt.plan_sha256.as_str())
&& signed.job_payload_hash == header.attempt.job_payload_sha256
&& signed.action == "update_agent"
&& signed.execution_identity == "root"
&& signed.outcome_state == "running"
&& !signed.unlock
&& signed.outcome_bytes.is_empty()
&& signed.outcome_sha256.is_none(),
"UPDATE_HEALTH_SIGNED_ORIGINAL_INFLIGHT"
);
Ok(local.update_handoff_bytes)
}
fn require_exact_span(
lower: DateTime<Utc>,
actual: DateTime<Utc>,
upper: DateTime<Utc>,
wire_floor: u64,
) -> Result<()> {
ensure!(
lower <= actual && actual <= upper && wire_floor == u64::try_from(upper.timestamp())?,
"UPDATE_HEALTH_EXACT_ACTUAL_APPLY_SPAN"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_floor_does_not_admit_a_one_nanosecond_early_or_late_apply() {
let base = DateTime::from_timestamp(1000, 0).unwrap();
let lower = base + chrono::Duration::nanoseconds(100_000_001);
let upper = base + chrono::Duration::nanoseconds(200_000_001);
assert_eq!(lower.timestamp(), upper.timestamp());
require_exact_span(lower, lower, upper, 1000).unwrap();
require_exact_span(lower, upper, upper, 1000).unwrap();
assert!(
require_exact_span(lower, lower - chrono::Duration::nanoseconds(1), upper, 1000)
.is_err()
);
assert!(
require_exact_span(lower, upper + chrono::Duration::nanoseconds(1), upper, 1000)
.is_err()
);
assert!(require_exact_span(lower, lower, upper, 1001).is_err());
}
}
@@ -984,11 +984,13 @@ fn clean_ready_shared_lock_and_reopen_start_closed() {
let mut f = Fixture::new();
let mut sync = f.sync();
assert!(!sync.can_start(&f.db, &f.guard, 1, &f.clock, &f.boot));
assert_eq!(sync.validity_deadline(), None);
let snapshot = f.snapshot(&mut sync, 1);
let raw = f.request(&snapshot);
let d = f.decision(&snapshot, &raw, 1, true);
let applied = f.apply(&mut sync, &d, &raw).unwrap();
assert!(applied.ready);
assert_eq!(sync.validity_deadline(), Some(d.valid_until));
assert_eq!(sync.active_generation(), Some(1));
assert_eq!(applied.snapshot.previous_decision_id, Some(d.decision_id));
assert!(applied.unlocked_grants.is_empty());
@@ -1004,6 +1006,7 @@ fn clean_ready_shared_lock_and_reopen_start_closed() {
.is_err()
);
sync.close();
assert_eq!(sync.validity_deadline(), None);
assert!(!sync.can_start(&f.db, &f.guard, 1, &f.clock, &f.boot));
}
#[test]
@@ -1784,6 +1787,17 @@ fn update_inflight_negative_control_keeps_every_start_closed_and_owner_loss_is_t
decision.decision_id,
)
.unwrap();
let retained_round = rmm_agent_core::update_health_sync::read_round(
&f.db,
&guard,
&f.binding,
handoff.attempt.grant_id,
decision.decision_id,
)
.unwrap();
assert_eq!(retained_round.applied(), &local_apply);
assert_eq!(retained_round.decision().issued_at, decision.issued_at);
assert_eq!(retained_round.decision().valid_until, decision.valid_until);
assert_eq!(local_apply.applied_at, f.clock.now);
assert_eq!(local_apply.request_sha256, hash(&raw));
let proto = rmm_protocol::SyncResponse {
+6 -29
View File
@@ -335,38 +335,15 @@ impl<'a> FullUpdateGuard<'a> {
"UPDATE_HEALTH_CURRENT_LOCAL_CHANNEL_REQUIRED"
);
self.verify_current_services(&receipt.service_processes)?;
let applied = update_handoff::read_applied_sync(
let span = rmm_agent_core::update_health_sync::verified_span(
db,
self.executor,
self.original.permit().grant_id,
receipt.signed_sync_decision_id,
self.binding,
self.original.handoff(),
&receipt,
self.trust.health_public_key(),
)?;
ensure!(
applied.request_sha256 == receipt.signed_sync_request_sha256
&& applied.response_protobuf_sha256 == receipt.signed_sync_response_sha256
&& receipt.inventory_ack_sha256 == applied.response_protobuf_sha256,
"UPDATE_LOCAL_APPLIED_RAW_BINDING"
);
let response_raw: Vec<u8> = db.query_row(
"SELECT response FROM helper_sync_decisions WHERE decision_id=?1",
[receipt.signed_sync_decision_id.to_string()],
|r| r.get(0),
)?;
let response: rmm_agent_core::helper_reconcile::SignedResponse =
serde_json::from_slice(&response_raw)?;
let decision: rmm_domain::reconciliation::ReconcileDecisionPayload =
serde_json::from_slice(&response.decision_bytes)?;
let applied_seconds = u64::try_from(applied.applied_at.timestamp())?;
ensure!(
applied_seconds >= u64::try_from(decision.issued_at.timestamp())?
&& applied_seconds <= receipt.signed_sync_applied_at
&& !decision.ready
&& !decision.helper_ready
&& decision
.acknowledged_message_ids
.contains(&receipt.inventory_message_id),
"UPDATE_ACTUAL_LOCAL_APPLY_OR_INVENTORY_ACK"
);
let applied = span.applied().clone();
verify_local_inventory(&self.witnesses, &self.original, &receipt)?;
Ok(VerifiedHealth {
signed_sha256: hash(&serde_json::to_vec(signed)?),
+31 -5
View File
@@ -675,6 +675,17 @@ impl Drop for Client {
}
}
// Linux pathname DGRAM send requires socket write permission; read/execute
// bits grant no sending authority. Directory ancestry is separately held and
// verified. Neither group nor other may write this daemon-owned socket.
fn protected_server_socket(socket: Identity, uid: u32, gid: u32) -> bool {
socket.mode & libc::S_IFMT == libc::S_IFSOCK
&& socket.links == 1
&& socket.uid == uid
&& socket.gid == gid
&& socket.mode & 0o022 == 0
}
/// Root-only source broker primitive. No daemon discovery, adoption, commands,
/// configurable endpoint, retry, IP transport or time-setting entrypoint.
pub struct NativeTimeSource {
@@ -698,11 +709,11 @@ impl NativeTimeSource {
)?;
let server_identity = socket_identity(server_dir.as_raw_fd(), "chronyd.sock")?;
ensure!(
server_identity.mode & libc::S_IFMT == libc::S_IFSOCK
&& server_identity.links == 1
&& server_identity.uid == daemon.pin.daemon_uid
&& server_identity.gid == daemon.pin.daemon_gid
&& server_identity.mode & 0o007 == 0,
protected_server_socket(
server_identity,
daemon.pin.daemon_uid,
daemon.pin.daemon_gid,
),
"TIME_CHRONY_SOCKET_PROTECTION"
);
Ok(Self {
@@ -854,6 +865,21 @@ mod tests {
.unwrap();
let old = UnixDatagram::bind(path.join("own.sock")).unwrap();
let expected = socket_identity(dir.as_raw_fd(), "own.sock").unwrap();
let server = Identity {
mode: libc::S_IFSOCK | 0o755,
..expected
};
assert!(protected_server_socket(server, server.uid, server.gid));
for mode in [0o775, 0o757] {
assert!(!protected_server_socket(
Identity {
mode: libc::S_IFSOCK | mode,
..server
},
server.uid,
server.gid,
));
}
std::fs::rename(path.join("own.sock"), path.join("held.sock")).unwrap();
let new = UnixDatagram::bind(path.join("own.sock")).unwrap();
assert!(unlink_owned(dir.as_raw_fd(), "own.sock", expected).is_err());
+210
View File
@@ -0,0 +1,210 @@
//! Existing Agent singleton fence. No create, ACL change or Root-ledger alias.
//! The agent holds this exact lock before opening BOTH of its SQLite files.
use crate::retained::{RetainedSet, Retention};
use anyhow::{Context, Result, ensure};
use rmm_updater_linux::{
Budget,
files::{Directory, Identity},
services::StoppedServices,
};
use std::{
fs::{File, OpenOptions},
os::{
fd::AsRawFd,
unix::fs::{MetadataExt, OpenOptionsExt},
},
path::Path,
};
const PARENT: &str = "/var/lib/rmm-agent-remote";
const PATH: &str = "/var/lib/rmm-agent-remote/agent.lock";
pub struct BoundAgentLock {
directory: Directory,
file: File,
expected: Identity,
}
impl BoundAgentLock {
/// Open/bind before any stop, so a missing preservation witness cannot be
/// discovered only after stopping the Agent. Reading never takes its lock.
pub fn bind(retained: &RetainedSet) -> Result<Self> {
retained.verify()?;
let specs = retained.specs();
let spec = specs
.iter()
.find(|s| s.path == Path::new(PATH))
.context("UPDATE_AGENT_LOCK_WITNESS_REQUIRED")?;
ensure!(
spec.retention == Retention::ImmutableMetadata
&& spec.parent_uid == 993
&& spec.identity.uid == 993
&& spec.identity.gid == 984
&& spec.identity.mode & 0o7777 == 0o600
&& spec.identity.links == 1,
"UPDATE_AGENT_LOCK_PROVISIONING"
);
let directory = Directory::open(Path::new(PARENT), 993, true)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
.open(PATH)?;
let result = Self {
directory,
file,
expected: spec.identity.clone(),
};
result.verify()?;
Ok(result)
}
fn verify(&self) -> Result<()> {
self.directory.verify()?;
let held = self.file.metadata()?;
let named = std::fs::symlink_metadata(PATH)?;
ensure!(
held.is_file()
&& held.len() == 0
&& named.is_file()
&& !named.file_type().is_symlink()
&& identity(&held) == self.expected
&& identity(&named) == self.expected,
"UPDATE_AGENT_LOCK_IDENTITY_CHANGED"
);
Ok(())
}
pub fn identity(&self) -> &Identity {
&self.expected
}
/// Real, fresh stopped-service proof precedes the existing nonblocking
/// singleton acquisition. A running/restarted Agent makes this fail closed.
pub fn acquire(self, stopped: &StoppedServices, budget: &Budget) -> Result<HeldAgentLock> {
stopped.verify_still_stopped(budget)?;
let result = self.acquire_existing()?;
stopped.verify_still_stopped(budget)?;
Ok(result)
}
fn acquire_existing(self) -> Result<HeldAgentLock> {
self.verify()?;
ensure!(
unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"UPDATE_AGENT_STARTUP_BUSY"
);
let result = HeldAgentLock { bound: self };
result.verify()?;
Ok(result)
}
}
pub struct HeldAgentLock {
bound: BoundAgentLock,
}
impl HeldAgentLock {
pub fn verify(&self) -> Result<()> {
self.bound.verify()
}
pub fn identity(&self) -> &Identity {
self.bound.identity()
}
/// Only the live Engine calls this after SQLite close and actual original
/// Root flock return, before the explicit once-only service start sequence.
pub(crate) fn return_after_root_release(self, budget: &Budget) -> Result<()> {
budget.check()?;
self.verify()?;
ensure!(
unsafe { libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN) } == 0,
"UPDATE_AGENT_STARTUP_RETURN_FAILED"
);
Ok(())
}
}
impl Drop for HeldAgentLock {
fn drop(&mut self) {
unsafe {
libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN);
}
}
}
fn identity(meta: &std::fs::Metadata) -> Identity {
Identity {
device: meta.dev(),
inode: meta.ino(),
uid: meta.uid(),
gid: meta.gid(),
mode: meta.mode(),
links: meta.nlink(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::retained::RetainedFileSpec;
use std::os::unix::fs::PermissionsExt;
struct Cleanup;
impl Drop for Cleanup {
fn drop(&mut self) {
std::fs::remove_dir_all(PARENT).unwrap();
}
}
#[test]
fn existing_agent_lock_blocks_aliases_and_rejects_samebyte_inode_substitution() {
// Private network-none/root container fixture ONLY; no host path/test.
assert_eq!(unsafe { libc::geteuid() }, 0);
assert!(!Path::new(PARENT).exists());
std::fs::create_dir_all(PARENT).unwrap();
let _cleanup = Cleanup;
std::fs::set_permissions(PARENT, std::fs::Permissions::from_mode(0o700)).unwrap();
let file = OpenOptions::new()
.create_new(true)
.read(true)
.write(true)
.mode(0o600)
.open(PATH)
.unwrap();
for path in [PARENT, PATH] {
let path = std::ffi::CString::new(path).unwrap();
assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0);
}
let retained = RetainedSet::capture(vec![RetainedFileSpec {
path: Path::new(PATH).to_owned(),
parent_uid: 993,
identity: identity(&file.metadata().unwrap()),
retention: Retention::ImmutableMetadata,
}])
.unwrap();
let bound = BoundAgentLock::bind(&retained).unwrap();
// The existing Agent's separately opened descriptor owns the lock.
assert_eq!(
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
0
);
assert!(bound.acquire_existing().is_err());
assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) }, 0);
let held = BoundAgentLock::bind(&retained)
.unwrap()
.acquire_existing()
.unwrap();
assert_ne!(
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
0
);
held.verify().unwrap();
std::fs::rename(PATH, Path::new(PARENT).join("agent.lock.previous")).unwrap();
let replacement = OpenOptions::new()
.create_new(true)
.read(true)
.write(true)
.mode(0o600)
.open(PATH)
.unwrap();
let path = std::ffi::CString::new(PATH).unwrap();
assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0);
assert_eq!(replacement.metadata().unwrap().len(), 0);
assert!(held.verify().is_err());
assert!(BoundAgentLock::bind(&retained).is_err());
drop(held);
assert_eq!(
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
0
);
}
}
+71 -20
View File
@@ -53,7 +53,7 @@ pub struct BridgeContext<'a> {
}
pub struct FullBridge<'a> {
context: BridgeContext<'a>,
prefix: UpdateInflightProof,
prefix: Option<UpdateInflightProof>,
poisoned: bool,
finalized: bool,
}
@@ -76,7 +76,27 @@ impl<'a> FullBridge<'a> {
);
Ok(Self {
context,
prefix,
prefix: Some(prefix),
poisoned: false,
finalized: false,
})
}
/// First read obtains the actual original prefix from the authenticated
/// Full process/ledger. No event is synthesized from a caller's header.
pub fn original(context: BridgeContext<'a>) -> Result<Self> {
ensure!(
context.generation == Generation::Original,
"UPDATE_BRIDGE_ORIGINAL_ONLY"
);
context.handoff.validate()?;
ensure!(
context.delegation.handoff_sha256 == rmm_domain::jobs::hash(&context.handoff.bytes()?)
&& context.delegation.owner_nonce == context.handoff.owner_nonce,
"UPDATE_BRIDGE_ORIGINAL_HEADER"
);
Ok(Self {
context,
prefix: None,
poisoned: false,
finalized: false,
})
@@ -87,8 +107,21 @@ impl<'a> FullBridge<'a> {
.updater
.verify_delegation(context.delegation, context.budget)?;
context.budget.check()?;
let (_, journal) = verify_inflight_proof(&self.prefix, context.health_public_key)
.map_err(anyhow::Error::msg)?;
if self.prefix.is_none() {
ensure!(
matches!(method, NativeControlOperation::ReadOriginal),
"UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED"
);
}
let journal = self
.prefix
.as_ref()
.map(|prefix| {
verify_inflight_proof(prefix, context.health_public_key)
.map(|(_, journal)| journal)
.map_err(anyhow::Error::msg)
})
.transpose()?;
match &method {
NativeControlOperation::ReadOriginal => {}
NativeControlOperation::ClaimStop {
@@ -96,31 +129,43 @@ impl<'a> FullBridge<'a> {
..
} => ensure!(
context.generation == Generation::Original
&& journal.phase() == Phase::StopIntent
&& *expected_head_sha256 == self.prefix.head_sha256,
&& journal
.as_ref()
.is_some_and(|j| j.phase() == Phase::StopIntent)
&& Some(expected_head_sha256.as_str())
== self.prefix.as_ref().map(|p| p.head_sha256.as_str()),
"UPDATE_BRIDGE_CLAIM_PHASE"
),
NativeControlOperation::ObserveStarts { .. } => ensure!(
context.generation == Generation::Replacement
&& journal.phase() == Phase::LedgerReturnIntent,
&& journal
.as_ref()
.is_some_and(|j| j.phase() == Phase::LedgerReturnIntent),
"UPDATE_BRIDGE_START_PHASE"
),
NativeControlOperation::Health { receipt } => {
ensure!(
context.generation == Generation::Replacement
&& journal.phase() == Phase::ServicesStarted,
&& journal
.as_ref()
.is_some_and(|j| j.phase() == Phase::ServicesStarted),
"UPDATE_BRIDGE_HEALTH_PHASE"
);
journal.prepare(
u64::try_from(context.clock.now()?.timestamp())?,
rmm_updater_handoff::Evidence::HealthVerified {
receipt: receipt.clone(),
},
)?;
journal
.as_ref()
.context("UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED")?
.prepare(
u64::try_from(context.clock.now()?.timestamp())?,
rmm_updater_handoff::Evidence::HealthVerified {
receipt: receipt.clone(),
},
)?;
}
NativeControlOperation::Finalize => ensure!(
context.generation == Generation::Replacement
&& journal.phase() == Phase::HealthVerified,
&& journal
.as_ref()
.is_some_and(|j| j.phase() == Phase::HealthVerified),
"UPDATE_BRIDGE_FINAL_PHASE"
),
}
@@ -270,8 +315,11 @@ impl<'a> FullBridge<'a> {
ensure!(
handoff.bytes()? == context.handoff.bytes()?
&& proof.delegation == *context.delegation
&& proof.events.len() >= self.prefix.events.len()
&& proof.events[..self.prefix.events.len()] == self.prefix.events,
&& self
.prefix
.as_ref()
.is_none_or(|prior| proof.events.len() >= prior.events.len()
&& proof.events[..prior.events.len()] == prior.events),
"UPDATE_BRIDGE_PROOF_ROLLBACK_OR_CHANGED"
);
match request.method {
@@ -315,7 +363,7 @@ impl<'a> FullBridge<'a> {
),
NativeControlOperation::Finalize => unreachable!(),
}
self.prefix = proof.clone();
self.prefix = Some(proof.clone());
}
context.budget.check()?;
if matches!(request.method, NativeControlOperation::Finalize) {
@@ -331,8 +379,11 @@ impl<'a> FullBridge<'a> {
original_outcome,
})
}
pub fn head_sha256(&self) -> &str {
&self.prefix.head_sha256
pub fn head_sha256(&self) -> Result<&str> {
self.prefix
.as_ref()
.map(|p| p.head_sha256.as_str())
.context("UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED")
}
pub fn observe_starts(
&mut self,
+605
View File
@@ -0,0 +1,605 @@
//! One live original-attempt pass. Activation queues only; the fixed listener
//! must finish its reply before this runtime can stop the calling Fullhelper.
//! No daemon entrypoint, admission/capability registration or restart recovery.
use crate::{
agent_startup::BoundAgentLock,
bridge::{BridgeContext, FullBridge, Generation},
bundle,
clock::NativeClock,
fence::LedgerFence,
ledger::{OwnedInputs, OwnedLedger},
original::Original,
participants::{StableParticipant, verify_original_helper},
retained::RetainedSet,
returned,
trust::TrustState,
};
use anyhow::{Context, Result, ensure};
use rmm_agent_core::{
auth::Binding,
reconcile::SyncClock,
update_handoff::{NativeControlOperation, NativeEffect, NativeEffectClaim, NativeService},
};
use rmm_domain::{
agent_update::{ParticipantIdentity, ParticipantRole, UpdateInflightProof},
agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy},
jobs::hash,
};
use rmm_updater_handoff::{Evidence, Phase, Process};
use rmm_updater_linux::{
Budget, DurableEffectFence, Effect,
files::{Directory, HeldFile, LedgerGuard, Role},
ipc::{self, Request, Response, State},
services::{Service, ServicePolicy, ServiceProof, Systemd},
};
use std::{ffi::OsStr, path::Path, time::Duration};
use uuid::Uuid;
struct Protected {
directory: Directory,
file: HeldFile,
name: String,
max: u64,
}
impl Protected {
fn read(path: &str, max: u64) -> Result<(Self, Vec<u8>)> {
let path = Path::new(path);
let directory = Directory::open(path.parent().context("UPDATE_ENGINE_PARENT")?, 0, false)?;
let name = path
.file_name()
.context("UPDATE_ENGINE_NAME")?
.to_str()
.context("UPDATE_ENGINE_NAME")?
.to_owned();
let mut file = directory.inspect(OsStr::new(&name), 0, max)?;
let raw = file.bytes(max)?;
Ok((
Self {
directory,
file,
name,
max,
},
raw,
))
}
fn verify(&self) -> Result<()> {
self.directory
.file(OsStr::new(&self.name), self.file.proof(), self.max)?;
Ok(())
}
}
/// Construct only in the separately provisioned stable service, with the
/// independently protected original job Binding. It offers no approval API.
pub struct Runtime {
binding: Binding,
policy: LocalUpdatePolicy,
policy_sha256: String,
installed: InstalledReleaseRecord,
installed_sha256: String,
health_key: [u8; 32],
health_pin_sha256: String,
protected: Vec<Protected>,
old_policies: Vec<ServicePolicy>,
updater: StableParticipant,
clock: NativeClock,
queued: Option<Queued>,
accepted: bool,
failed: bool,
terminal: bool,
head: Option<String>,
}
struct Queued {
agent_startup: BoundAgentLock,
original: Original,
witnesses: bundle::Loaded,
trust: TrustState,
budget: Budget,
proof: UpdateInflightProof,
}
impl Runtime {
pub fn new(binding: Binding) -> Result<Self> {
let clock = NativeClock::new()?;
let budget = observation_budget()?;
let (policy_file, raw) = Protected::read("/etc/rmm-agent-updater/policy.json", 65536)?;
let (policy, policy_sha256) =
LocalUpdatePolicy::from_bytes(&raw).map_err(anyhow::Error::msg)?;
ensure!(
policy.tenant_id == binding.tenant_id
&& policy.asset_id == binding.asset_id
&& policy.agent_id == binding.agent_id
&& policy.enrollment_generation == binding.enrollment_generation
&& policy.assignment_version == binding.assignment_version,
"UPDATE_ENGINE_LOCAL_IDENTITY"
);
let (record_file, raw) = Protected::read(&policy.installed_record_path, 32768)?;
let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?;
let installed_sha256 = hash(&raw);
let old_policies = service_policies(&policy, &installed, None)?;
let (health_file, raw) = Protected::read(&policy.health_pin_path, 4096)?;
let health: HealthKeyPin = serde_json::from_slice(&raw)?;
let health_key = health.public_key().map_err(anyhow::Error::msg)?;
let updater = StableParticipant::observe(
ServicePolicy {
service: Service::Updater,
image_sha256: policy.updater_binary_sha256.clone(),
unit_sha256: policy.updater_service.unit_sha256.clone(),
},
&budget,
)?;
Ok(Self {
binding,
policy,
policy_sha256,
installed,
installed_sha256,
health_key,
health_pin_sha256: hash(&raw),
protected: vec![policy_file, record_file, health_file],
old_policies,
updater,
clock,
queued: None,
accepted: false,
failed: false,
terminal: false,
head: None,
})
}
/// A lost activation reply disables this live runtime before any stop.
/// Drive is deliberately private: it cannot run inside Engine::handle.
pub fn serve_one(&mut self, listener: &ipc::Listener) -> Result<()> {
self.require_reader_registry_and_census()?;
ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED");
let services = Systemd::new(self.old_policies.clone())?;
let budget = observation_budget()?;
if let Err(error) = listener.serve_one(&services, &budget, self) {
if self.queued.take().is_some() {
self.failed = true;
}
return Err(error);
}
if let Some(queued) = self.queued.take() {
// serve_one has written/flushed the bounded reply and dropped its
// accepted stream. Only now may the original Full process stop.
match self.drive(queued) {
Ok(()) => self.terminal = true,
Err(error) => {
self.failed = true;
return Err(error);
}
}
}
Ok(())
}
fn require_reader_registry_and_census(&self) -> Result<()> {
// This is an explicit source-checkpoint barrier, not a caller boolean
// or a known-unit-list substitute. Replace only with the real protected
// bootstrap registry + complete live FD/maps census and both locks.
anyhow::bail!("UPDATE_READER_CENSUS_NOT_CONFIGURED")
}
fn enqueue(
&mut self,
peer: &ParticipantIdentity,
grant: Uuid,
nonce: Uuid,
handoff_sha: &str,
) -> Result<()> {
ensure!(
!self.accepted && self.queued.is_none() && !self.failed && !self.terminal,
"UPDATE_ENGINE_NO_RETRY_OR_RESUME"
);
// Fuse before any fallible original admission. Even an uncertain reply
// cannot dispatch this handoff for a second time in this process.
self.accepted = true;
for file in &self.protected {
file.verify()?;
}
let header = bundle::read_header(grant, nonce, handoff_sha)?;
ensure!(
peer.role == ParticipantRole::LinuxFullHelper
&& *peer == header.delegation.original_helper
&& header.handoff.updater_sha256 == self.policy.updater_binary_sha256
&& header.handoff.updater_policy_sha256 == self.policy_sha256
&& header.handoff.predecessor_record_sha256 == self.installed_sha256,
"UPDATE_ENGINE_ORIGINAL_PARTICIPANTS_OR_POLICY"
);
let finish =
chrono::DateTime::from_timestamp(i64::try_from(header.handoff.finish_before)?, 0)
.context("UPDATE_ENGINE_FINISH")?;
let budget = Budget::new(
header.handoff.boot_id,
(finish - self.clock.now()?).to_std()?,
)?;
let services = Systemd::new(self.old_policies.clone())?;
verify_original_helper(&services, &header.delegation, &budget)?;
self.updater
.verify_delegation(&header.delegation, &budget)?;
let mut bridge = FullBridge::original(BridgeContext {
handoff: &header.handoff,
delegation: &header.delegation,
services: &services,
updater: &self.updater,
clock: &self.clock,
budget: &budget,
health_public_key: self.health_key,
generation: Generation::Original,
})?;
let reply = bridge.call(NativeControlOperation::ReadOriginal)?;
let proof = reply.proof.context("UPDATE_ENGINE_ORIGINAL_PROOF")?;
let original = Original::verify(
&self.binding,
&reply
.original_start
.context("UPDATE_ENGINE_ORIGINAL_START")?,
&header.handoff.bytes()?,
header.delegation,
&self.clock,
&budget,
)?;
let (_, journal) = rmm_domain::agent_update::verify_inflight_proof(&proof, self.health_key)
.map_err(anyhow::Error::msg)?;
ensure!(
journal.phase() == Phase::StopIntent,
"UPDATE_ENGINE_NOT_A_FRESH_HANDOFF"
);
let trust = TrustState::load(&original, &self.binding, &self.clock)?;
ensure!(
trust.health_public_key() == self.health_key
&& original.update().updater.health_key_pin_sha256 == self.health_pin_sha256
&& serde_json::to_vec(trust.policy())? == serde_json::to_vec(&self.policy)?,
"UPDATE_ENGINE_TRUST_CHANGED"
);
let witnesses = bundle::read_for_handoff(original.handoff())?;
witnesses.files.reopen_stages(original.handoff(), &budget)?;
witnesses.retained.verify()?;
let agent_startup = BoundAgentLock::bind(&witnesses.retained)?;
self.head = Some(proof.head_sha256.clone());
self.queued = Some(Queued {
agent_startup,
original,
witnesses,
trust,
budget,
proof,
});
Ok(())
}
fn drive(&mut self, queued: Queued) -> Result<()> {
let Queued {
agent_startup,
original,
witnesses,
trust,
budget,
proof,
} = queued;
original.check_current(&self.binding, &self.clock, &budget)?;
trust.recheck(&original, &self.clock)?;
let services = Systemd::new(self.old_policies.clone())?;
let old = [Service::Agent, Service::General, Service::Full]
.into_iter()
.map(|s| services.observe(s, &budget).map(|h| h.proof().clone()))
.collect::<Result<Vec<_>>>()?;
let mut bridge = FullBridge::new(
BridgeContext {
handoff: original.handoff(),
delegation: original.delegation(),
services: &services,
updater: &self.updater,
clock: &self.clock,
budget: &budget,
health_public_key: self.health_key,
generation: Generation::Original,
},
proof,
)?;
let mut claims = Vec::new();
for service in [
NativeService::Agent,
NativeService::General,
NativeService::Full,
] {
let expected_head_sha256 = bridge.head_sha256()?.to_owned();
claims.push(
bridge
.call(NativeControlOperation::ClaimStop {
expected_head_sha256,
service,
})?
.claim
.context("UPDATE_ENGINE_STOP_CLAIM")?,
);
}
drop(bridge);
let mut stop_fence = StopFence {
original: &original,
binding: &self.binding,
clock: &self.clock,
budget: &budget,
updater: &self.updater,
trust: &trust,
retained: &witnesses.retained,
claims,
old,
next: 0,
pending: false,
poisoned: false,
};
let stopped = services.stop_all(&budget, &mut stop_fence)?;
let claims = stop_fence.finish()?;
let agent_startup = agent_startup.acquire(&stopped, &budget)?;
let os = LedgerGuard::acquire(&stopped, &witnesses.ledger, &budget)?;
let mut ledger = OwnedLedger::open(OwnedInputs {
os: &os,
original: &original,
binding: &self.binding,
clock: &self.clock,
budget: &budget,
updater: &self.updater,
retained: &witnesses.retained,
files: &witnesses.files,
stopped: &stopped,
trust: &trust,
})?;
for (claim, old) in claims.iter().zip(stopped.proofs()) {
ledger.observe_native(claim, &hash(&serde_json::to_vec(&old)?))?;
}
ledger.append_observed(Evidence::AllStopped {
observation_sha256: hash(&serde_json::to_vec(&stopped.proofs())?),
})?;
ledger.append_observed(Evidence::UpdaterOwnsLedger {
process: Process {
pid: self.updater.identity().pid,
birth: self.updater.identity().birth,
image_sha256: self.updater.identity().image_sha256.clone(),
},
ledger_identity_sha256: witnesses.ledger.sha256()?,
})?;
// Do not hold a second connection before all readers really stopped.
let swap = (|| -> Result<()> {
let stages = witnesses.files.reopen_stages(original.handoff(), &budget)?;
let mut fence = LedgerFence::new(&mut ledger)?;
for (stage, role) in
stages
.into_iter()
.zip([Role::Agent, Role::Helper, Role::FullConfig, Role::FullPin])
{
let directory = Directory::open(
Path::new(role.target())
.parent()
.context("UPDATE_ENGINE_TARGET_PARENT")?,
0,
false,
)?;
stage.install(&directory, &os, &budget, &mut fence)?;
}
fence.finish()?;
ledger.append_observed(Evidence::PairVerified {
pair: original.handoff().target.clone(),
retained_state_sha256: original.handoff().retained_state_sha256.clone(),
})
})();
if let Err(error) = swap {
// Exactly one best-effort ORIGINAL Unknown CAS while we still own
// the real guard. Failure is preserved; no restoration or retry.
let _ = ledger.mark_unknown(
u64::try_from(self.clock.now()?.timestamp())?,
rmm_updater_handoff::UnknownReason::ReplaceUncertain,
);
return Err(error);
}
let prepared = ledger.prepare_return_and_close()?;
let reservation = prepared.bind(returned::Inputs {
original: &original,
binding: &self.binding,
clock: &self.clock,
budget: &budget,
updater: &self.updater,
retained: &witnesses.retained,
files: &witnesses.files,
trust: &trust,
})?;
let target_policies = service_policies(&self.policy, &self.installed, Some(&original))?;
let target = Systemd::new(target_policies.clone())?;
let observer = Systemd::new(target_policies)?;
let mut bridge = FullBridge::new(
BridgeContext {
handoff: original.handoff(),
delegation: original.delegation(),
services: &observer,
updater: &self.updater,
clock: &self.clock,
budget: &budget,
health_public_key: self.health_key,
generation: Generation::Replacement,
},
reservation.proof().clone(),
)?;
let mut fence = reservation.start_fence(&observer, &mut bridge);
agent_startup.verify()?;
os.release(&budget, &mut fence)?;
agent_startup.return_after_root_release(&budget)?;
let started = stopped.start_once(target, &budget, &mut fence)?;
fence.finish()?;
bridge.observe_starts(&started)?;
loop {
original.check_current(&self.binding, &self.clock, &budget)?;
self.updater
.verify_delegation(original.delegation(), &budget)?;
witnesses.retained.verify()?;
for service in &started {
service.verify(&budget)?;
}
let reply = bridge.call(NativeControlOperation::ReadOriginal)?;
let proof = reply.proof.context("UPDATE_ENGINE_HEALTH_PROOF")?;
self.head = Some(proof.head_sha256.clone());
let (_, journal) =
rmm_domain::agent_update::verify_inflight_proof(&proof, self.health_key)
.map_err(anyhow::Error::msg)?;
match journal.phase() {
Phase::ServicesStarted => std::thread::sleep(Duration::from_millis(100)),
Phase::HealthVerified => {
bridge.call(NativeControlOperation::Finalize)?;
self.head = None;
return Ok(());
}
_ => anyhow::bail!("UPDATE_ENGINE_HEALTH_PREFIX_CHANGED"),
}
}
}
}
impl ipc::Engine for Runtime {
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response> {
ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED");
self.updater
.identity()
.validate()
.then_some(())
.context("UPDATE_ENGINE_IDENTITY")?;
let state = match request {
Request::Describe {} => State::Described,
Request::Activate {
grant_id,
owner_nonce,
handoff_sha256,
} => {
self.enqueue(peer, grant_id, owner_nonce, &handoff_sha256)?;
State::Inflight
}
// Health travels through the existing independently validating
// new Fullhelper path. This daemon accepts no duplicate authority.
_ => anyhow::bail!("UPDATE_ENGINE_UNSUPPORTED_CONTROL"),
};
Ok(Response {
schema_version: 1,
state,
ready: false,
updater: self.updater.identity().clone(),
head_sha256: self.head.clone(),
})
}
}
struct StopFence<'a> {
original: &'a Original,
binding: &'a Binding,
clock: &'a NativeClock,
budget: &'a Budget,
updater: &'a StableParticipant,
trust: &'a TrustState,
retained: &'a RetainedSet,
claims: Vec<NativeEffectClaim>,
old: Vec<ServiceProof>,
next: usize,
pending: bool,
poisoned: bool,
}
impl StopFence<'_> {
fn current(&self) -> Result<()> {
self.original
.check_current(self.binding, self.clock, self.budget)?;
self.updater
.verify_delegation(self.original.delegation(), self.budget)?;
self.trust.recheck(self.original, self.clock)?;
self.retained.verify()
}
fn finish(self) -> Result<Vec<NativeEffectClaim>> {
ensure!(
!self.poisoned && !self.pending && self.next == 3,
"UPDATE_ENGINE_STOP_INCOMPLETE"
);
self.current()?;
Ok(self.claims)
}
}
impl DurableEffectFence for StopFence<'_> {
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
ensure!(
!self.poisoned && !self.pending && self.next < 3,
"UPDATE_ENGINE_STOP_NO_RETRY"
);
self.poisoned = true;
self.current()?;
let service = [Service::Agent, Service::General, Service::Full][self.next];
let native = [
NativeService::Agent,
NativeService::General,
NativeService::Full,
][self.next];
let claim = &self.claims[self.next];
ensure!(
*effect == Effect::StopService { service }
&& claim.effect() == &NativeEffect::StopService { service: native }
&& claim.grant_id() == self.original.permit().grant_id
&& claim.owner_nonce() == self.original.handoff().owner_nonce,
"UPDATE_ENGINE_STOP_RESERVATION_CHANGED"
);
self.pending = true;
Ok(())
}
fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> {
ensure!(
self.poisoned
&& self.pending
&& self.next < 3
&& *effect
== Effect::StopService {
service: self.old[self.next].service
}
&& observation == hash(&serde_json::to_vec(&self.old[self.next])?),
"UPDATE_ENGINE_STOP_OBSERVATION_CHANGED"
);
self.current()?;
self.next += 1;
self.pending = false;
self.poisoned = false;
Ok(())
}
}
fn observation_budget() -> Result<Budget> {
Budget::new(
std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?
.trim()
.parse()?,
Duration::from_secs(5),
)
}
fn service_policies(
policy: &LocalUpdatePolicy,
installed: &InstalledReleaseRecord,
original: Option<&Original>,
) -> Result<Vec<ServicePolicy>> {
let release = installed
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
policy
.services
.iter()
.zip([
Service::Agent,
Service::General,
Service::Full,
Service::Apt,
])
.map(|(pin, service)| {
ensure!(pin.unit == service.unit(), "UPDATE_ENGINE_SERVICE_SET");
let image_sha256 = match (service, original) {
(Service::Agent, Some(o)) => o.handoff().target.agent_sha256.clone(),
(Service::General | Service::Full | Service::Apt, Some(o)) => {
o.handoff().target.helper_sha256.clone()
}
(Service::Agent, None) => release.manifest.artifacts[0].sha256.clone(),
(_, None) => release.manifest.artifacts[1].sha256.clone(),
_ => anyhow::bail!("UPDATE_ENGINE_SERVICE_ROLE"),
};
Ok(ServicePolicy {
service,
image_sha256,
unit_sha256: pin.unit_sha256.clone(),
})
})
.collect()
}
+88
View File
@@ -1316,6 +1316,94 @@ mod tests {
active,
}
}
#[test]
fn public_record_builder_binds_actual_original_key_and_exact_health_head() {
let f = fixture();
let (grant, record, start):(String,Vec<u8>,Vec<u8>)=f.db.query_row(
"SELECT h.grant_id,h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id)",
[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).unwrap();
let grant: Uuid = grant.parse().unwrap();
let delegation = update_handoff::read_delegation(&f.db, grant).unwrap();
let original =
crate::original::Original::verify_retained(&f.binding, &start, &record, delegation)
.unwrap();
let key: [u8; 32] = hex::decode(&original.update().updater.health_public_key_hex)
.unwrap()
.try_into()
.unwrap();
let mut journal = Journal::open(&record, key).unwrap();
let mut wrong_journal = Journal::open(
&record,
SigningKey::from_bytes(&[88; 32]).verifying_key().to_bytes(),
)
.unwrap();
let mut statement =
f.db.prepare("SELECT event FROM agent_update_handoff_events ORDER BY sequence")
.unwrap();
let events = statement
.query_map([], |r| r.get::<_, Vec<u8>>(0))
.unwrap()
.collect::<rusqlite::Result<Vec<_>>>()
.unwrap();
let mut health_raw = None;
let mut wrong_health_raw = None;
for raw in events {
let event: Event = serde_json::from_slice(&raw).unwrap();
if let Evidence::HealthVerified { receipt } = &event.evidence {
journal.replay(&raw).unwrap();
let mut wrong = receipt.clone();
let mut message = HEALTH_DOMAIN.to_vec();
message.extend_from_slice(&wrong.payload);
wrong.signature = SigningKey::from_bytes(&[88; 32])
.sign(&message)
.to_bytes()
.to_vec();
let forged = wrong_journal
.prepare(
event.observed_at,
Evidence::HealthVerified { receipt: wrong },
)
.unwrap();
wrong_journal.replay(&forged).unwrap();
wrong_health_raw = Some(forged);
health_raw = Some(raw);
break;
}
journal.replay(&raw).unwrap();
wrong_journal.replay(&raw).unwrap();
}
let health_raw = health_raw.unwrap();
let built = crate::record::BuiltRecord::build(&original, &f.initial, &journal, &health_raw)
.unwrap();
assert_eq!(built.raw(), f.active);
assert_eq!(built.sha256(), hash(&f.active));
// A complete kernel Journal can be constructed with the wrong external
// key. The public builder must independently enforce the ORIGINAL job.
assert!(
crate::record::BuiltRecord::build(
&original,
&f.initial,
&wrong_journal,
&wrong_health_raw.unwrap()
)
.is_err()
);
let mut changed: Event = serde_json::from_slice(&health_raw).unwrap();
changed.observed_at += 1;
assert!(
crate::record::BuiltRecord::build(
&original,
&f.initial,
&journal,
&serde_json::to_vec(&changed).unwrap()
)
.is_err()
);
assert!(
crate::record::BuiltRecord::build(&original, &f.active, &journal, &health_raw).is_err()
);
}
#[test]
fn completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes() {
let f = fixture();
+2
View File
@@ -1,9 +1,11 @@
//! Concrete, original-attempt-bound Linux worker. No approval or retry path.
#![cfg(target_os = "linux")]
pub mod agent_startup;
pub mod bridge;
pub mod bundle;
pub mod clock;
pub mod engine;
pub mod fence;
pub mod files;
pub mod full;
+1 -1
View File
@@ -480,7 +480,7 @@ def chrony_observation():
directory = os.open('/run/chrony', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
dir_identity = fd_metadata(directory)
require(stat.S_ISDIR(dir_identity['mode']) and dir_identity['uid'] == 989 and
dir_identity['gid'] == 989 and stat.S_IMODE(dir_identity['mode']) == 0o755,
dir_identity['gid'] == 989 and stat.S_IMODE(dir_identity['mode']) == 0o700,
'actual fixed protected Chrony socket directory')
pidfile = os.open('chronyd.pid', os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
pid_identity = fd_metadata(pidfile)
@@ -0,0 +1,309 @@
#!/usr/bin/env python3
"""Frozen four Linux source units only; no actual Chrony or kernel query; no updater service or Apply.
Prepare copies the independently reviewed snapshot locally. Execute is one
root-only Cloud-VM fixture run. After any lost reply read the original case;
never execute it again or substitute another binary/source generation.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import stat
import uuid
import windows_msi_runtime_acceptance as support
ROOT = Path(__file__).resolve().parents[1]
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
QUALIFICATION = ROOT / 'devstate/time-source-qualification/7a8cb5be-41b3-400a-bd9b-b4b6f505a6e9'
STATE = ROOT / 'devstate/time-source-socket-native-linux'
PROFILE = 'rmm.time-source.four-socket-permission-units.v1'
RECEIPT_SHA = '74759e286ba7c9762fe4c455da952a0e62de48f55ea643e0a8f435d2128497a5'
INPUTS_SHA = 'c0067889fa6e79e5b1dc2ad46685613fd0b379b30a4541670f635140405718d9'
BINARY_SHA = '9bd41ff166aeaae45fdf3dda2d72b04fc30e5ef87a181fe733c47e511a836d59'
BINARY_BYTES = 1169800
TESTS = sorted(['native::tests::clock_brackets_reject_suspend_step_backwards_and_total_timeout', 'native::tests::socket_cleanup_preserves_replaced_name_and_removes_only_exact_own_inode', 'tracking::tests::exact_packet_sequence_and_network_source', 'tracking::tests::signed_float_ceil_and_overflow_are_conservative'])
AGENT_SHA = '0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f'
HELPER_SHA = '79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf'
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def save_local(path, value):
support.save(path, value)
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def copy_exact(source, destination, digest, size):
metadata = source.lstat()
support.require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1
and metadata.st_uid in (0, os.getuid()) and not metadata.st_mode & 0o002
and metadata.st_size == size and size <= 2 * 1024 * 1024, 'bounded regular frozen input')
raw = source.read_bytes()
support.require(sha(raw) == digest, 'frozen snapshot input hash')
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
support.private(destination.parent, True)
fd = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'wb') as stream:
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
fd = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def verify_case(folder):
value = support.load(folder / 'manifest.json')
support.require(value['profile'] == PROFILE and value['tests'] == TESTS
and value['runner_sha256'] == sha(Path(__file__).read_bytes())
and value['receipt_sha256'] == RECEIPT_SHA and value['binary_sha256'] == BINARY_SHA
and value['binary_bytes'] == BINARY_BYTES, 'same original reviewed manifest')
support.require(sha((folder / 'receipt.json').read_bytes()) == RECEIPT_SHA
and sha((folder / 'inputs.json').read_bytes()) == INPUTS_SHA, 'original qualification provenance')
source = support.load(folder / 'inputs.json')
support.require(len(source) == 7 and source == value['source_files'], 'exact frozen seven provider inputs')
for item in source:
path = Path(item['path'])
support.require(not path.is_absolute() and '..' not in path.parts, 'fixed snapshot relative path')
file = folder / 'source' / path
support.private(file)
support.require(file.stat().st_size == item['bytes'] and sha(file.read_bytes()) == item['sha256'], 'retained source freeze')
binary = folder / 'time-contract-tests'; support.private(binary)
support.require(binary.stat().st_size == BINARY_BYTES and sha(binary.read_bytes()) == BINARY_SHA, 'original qualified test bytes')
for path, digest in value['transport_sources'].items():
support.require(sha((ROOT / path).read_bytes()) == digest, 'original strict transport source')
return value
def remote(p):
import base64
import hashlib
import json
import os
from pathlib import Path
import selectors
import signal
import stat
import subprocess
import time
import uuid
def require(ok, message):
if not ok:
raise RuntimeError(message)
def enc(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def create(path, raw, mode=0o600):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
with os.fdopen(fd, 'wb') as stream:
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def run(args, timeout=20):
# Keep the owned group leader unreaped until its entire group has been
# cleaned up. Its PID therefore cannot be recycled before killpg.
child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, start_new_session=True,
env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'})
selector = selectors.DefaultSelector()
buffers = {'stdout': bytearray(), 'stderr': bytearray()}
deadline = time.monotonic() + timeout
try:
for stream, name in ((child.stdout, 'stdout'), (child.stderr, 'stderr')):
os.set_blocking(stream.fileno(), False); selector.register(stream, selectors.EVENT_READ, name)
while True:
require(time.monotonic() < deadline, 'owned native command timeout; read original case only')
for key, _ in selector.select(0.02):
raw = os.read(key.fileobj.fileno(), 4096)
if raw:
buffers[key.data].extend(raw)
require(len(buffers[key.data]) <= 65536, 'bounded native output')
else:
selector.unregister(key.fileobj)
ended = os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
if ended is not None:
# Child remains a zombie until finally: no PID/group reuse.
os.killpg(child.pid, signal.SIGKILL)
for key in list(selector.get_map().values()):
while True:
try:
raw = os.read(key.fileobj.fileno(), 4096)
except BlockingIOError:
break
if not raw:
break
buffers[key.data].extend(raw)
require(len(buffers[key.data]) <= 65536, 'bounded native output')
code = ended.si_status if ended.si_code == os.CLD_EXITED else -ended.si_status
return code, bytes(buffers['stdout']), bytes(buffers['stderr'])
finally:
os.killpg(child.pid, signal.SIGKILL)
child.wait()
selector.close(); child.stdout.close(); child.stderr.close()
def metadata_identity(value):
return (value.st_dev, value.st_ino, value.st_uid, value.st_gid, value.st_mode,
value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
def hashed(path, maximum, process_image=False):
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | (0 if process_image else os.O_NOFOLLOW))
with os.fdopen(fd, 'rb') as stream:
before = os.fstat(stream.fileno()); require(stat.S_ISREG(before.st_mode) and before.st_size <= maximum, 'bounded witness file')
digest = hashlib.sha256(); total = 0
while True:
raw = stream.read(32768)
if not raw:
break
total += len(raw); require(total <= maximum, 'bounded witness hash'); digest.update(raw)
after = os.fstat(stream.fileno())
require(metadata_identity(before) == metadata_identity(after) and total == before.st_size, 'stable witness hash')
return before, digest.hexdigest()
def witness():
out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}}
release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line)
require(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'fixed native Ubuntu24.04')
out['os'] = {'id': 'ubuntu', 'version': '24.04', 'machine': os.uname().machine, 'kernel': os.uname().release}
for name, uid, binary in (
('rmm-agent-remote.service', 993, p['agent_sha256']),
('rmm-helper-cloud.service', 0, p['helper_sha256']),
('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])):
code, stdout, _ = run(['/usr/bin/systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState', '-p', 'InvocationID'])
require(code == 0, 'existing service read')
service = dict(line.split('=', 1) for line in stdout.decode().splitlines())
pid = int(service['MainPID']); require(service['ActiveState'] == 'active' and pid > 1, 'three existing services active')
proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19]
ids = {line.split(':')[0]: line.split()[1:] for line in (proc / 'status').read_text().splitlines() if line.startswith(('Uid:', 'Gid:'))}
metadata, image = hashed(proc / 'exe', 256 * 1024 * 1024, process_image=True)
current = (proc / 'exe').stat()
require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary
and (metadata.st_dev, metadata.st_ino) == (current.st_dev, current.st_ino)
and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'current generation/account/image')
out['services'][name] = dict(service, birth=birth, image=image, ids=ids)
code, stdout, _ = run(['/usr/bin/systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState'])
apt = dict(line.split('=', 1) for line in stdout.decode().splitlines())
require(code == 0 and apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed')
out['apt'] = apt
for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json',
'/etc/rmm-remote/full-maintenance-helper-proof.json', '/etc/systemd/system/rmm-full-maintenance-helper.service'):
path = Path(name); metadata = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_uid == 0
and not metadata.st_mode & 0o022 and metadata.st_nlink == 1, 'protected known control')
current, digest = hashed(path, 65536)
require(metadata_identity(current) == metadata_identity(metadata), 'same known control file')
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode,
metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns, digest]
for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock',
'/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite'):
path = Path(name); metadata = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1, 'existing state identity')
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode]
return out
require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root contract fixtures')
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case')
folder = Path('/var/tmp') / ('rmm-time-source-units-linux-' + ident)
if p['action'] == 'read':
metadata = folder.lstat()
require(stat.S_ISDIR(metadata.st_mode) and not folder.is_symlink() and metadata.st_uid == 0
and stat.S_IMODE(metadata.st_mode) == 0o700, 'own original case only')
result = folder / 'result.json'
return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(),
'result': json.loads(result.read_bytes()) if result.exists() else None, 'current_witness': witness()}
require(p['action'] == 'execute', 'one fixed time contract action')
os.umask(0o077); folder.mkdir(mode=0o700)
create(folder / 'intent.json', enc({key: value for key, value in p.items() if key != 'binary_b64'}))
require(len(p['binary_b64']) == 1559736, 'bounded binary transfer')
raw = base64.b64decode(p['binary_b64'], validate=True)
require(len(raw) == 1169800 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed four-unit binary')
binary = folder / 'time-contract-tests'; create(binary, raw, 0o700)
before = witness(); create(folder / 'before.json', enc(before))
command = ['/usr/bin/setpriv', '--reuid=0', '--regid=0', '--clear-groups', '--no-new-privs', str(binary)]
code, stdout, stderr = run(command + ['--list', '--format', 'terse'])
create(folder / 'list.stdout', stdout); create(folder / 'list.stderr', stderr)
require(code == 0 and stderr == b'', 'native list succeeded')
lines = stdout.decode().splitlines()
require(len(lines) == 4 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact four tests before any run')
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
code, stdout, stderr = run(command + ['--test-threads=1', '--nocapture'])
create(folder / 'run.stdout', stdout); create(folder / 'run.stderr', stderr)
after = witness(); create(folder / 'after.json', enc(after))
require(before == after and code == 0 and stderr == b''
and b'4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout
and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'four native units and retained target state')
receipt = dict(id=ident, profile=p['profile'], passed=4, ignored=0, filtered=0, execution_uid=0, tests=p['tests'],
before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'],
source_manifest_sha256=p['manifest_sha256'], stdout_sha256=hashlib.sha256(stdout).hexdigest(),
no_rmm_jobs=True, no_apply=True, no_service_control=True)
create(folder / 'result.json', enc(receipt)); return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('prepare', 'execute', 'read')); parser.add_argument('--case')
args = parser.parse_args(); os.umask(0o077)
STATE.mkdir(mode=0o700, parents=True, exist_ok=True); support.private(STATE, True)
if args.action == 'prepare':
support.require(args.case is None, 'prepare one new local case')
receipt_path = QUALIFICATION / 'receipt.json'; support.private(receipt_path)
support.require(sha(receipt_path.read_bytes()) == RECEIPT_SHA, 'independently reviewed source receipt')
receipt = support.load(receipt_path); original = support.load(QUALIFICATION / 'inputs.json')
support.require(sha((QUALIFICATION / 'inputs.json').read_bytes()) == INPUTS_SHA
and receipt['inputs_sha256'] == INPUTS_SHA and len(original) == 7
and receipt['result'] == 'LOCAL_RELEASE_PROVIDER4_SOCKET_PERMISSION_FIX_PASS' and receipt['tests'] == 4
and receipt['skips'] == 0 and receipt['filters'] == 0, 'reviewed four-test qualification')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
copy_exact(receipt_path, folder / 'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size)
copy_exact(QUALIFICATION / 'inputs.json', folder / 'inputs.json', INPUTS_SHA, (QUALIFICATION / 'inputs.json').stat().st_size)
paths = set()
for item in original:
path = Path(item['path'])
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique fixed frozen input')
paths.add(str(path)); copy_exact(QUALIFICATION / 'source' / path, folder / 'source' / path, item['sha256'], item['bytes'])
binary = QUALIFICATION / 'qualified-provider-tests'
support.require(receipt['artifacts'][0] == dict(path='qualified-provider-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA), 'fixed original linked artifact')
copy_exact(binary, folder / 'time-contract-tests', BINARY_SHA, BINARY_BYTES)
transports = {path: sha((ROOT / path).read_bytes()) for path in ('deploy/windows_msi_runtime_acceptance.py', 'deploy/vm_access_check.py')}
save_local(folder / 'manifest.json', dict(id=ident, profile=PROFILE, runner_sha256=sha(Path(__file__).read_bytes()),
receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_bytes=BINARY_BYTES,
source_files=original, tests=TESTS, transport_sources=transports))
verify_case(folder)
print(json.dumps({'id': ident, 'prepared_locally': True})); return
support.require(args.case is not None, 'original --case required')
ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same canonical original case')
folder = STATE / ident; support.private(folder, True); verify_case(folder)
payload = dict(id=ident, action=args.action, profile=PROFILE, tests=TESTS, binary_sha256=BINARY_SHA,
receipt_sha256=RECEIPT_SHA, manifest_sha256=sha((folder / 'manifest.json').read_bytes()),
agent_sha256=AGENT_SHA, helper_sha256=HELPER_SHA)
if args.action == 'execute':
save_local(folder / 'execute-entered.json', {'once': True, 'no_retry': True})
payload['binary_b64'] = base64.b64encode((folder / 'time-contract-tests').read_bytes()).decode()
code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n'
response = support.transport(support.access_settings(ACCESS_ROOT, 'linux'), 'python3 -', code.encode(), folder)
save_local(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response)
if args.action == 'read' and response['result'] is not None:
support.require(response['result']['source_manifest_sha256'] == sha((folder / 'manifest.json').read_bytes())
and response['current_witness'] == response['result']['after'], 'same-case retained native result')
print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'),
'complete': response.get('result') is not None if args.action == 'read' else True, 'read_only': args.action == 'read'}))
if __name__ == '__main__':
main()
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""One fixed original-case SYSTEM fixture repair; no RMM job or role start."""
import argparse
import json
from pathlib import Path
import subprocess
import uuid
import signed_clock_capture_acceptance as original
import signed_clock_capture_system_repair as repair
ROOT = Path(__file__).resolve().parents[2]
FOLDER = ROOT / 'devstate/windows-signed-clock-capture-system-repair/cff25311-d30b-495a-8b50-e0e28e2e5b48'
SCRIPT_SHA = 'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca'
GENERATOR_SHA = '9b44aa1491be2d154fb37fd0431370657f9623a2440649c29e910826beb44d2e'
NAME = 'SignedClockCaptureSystemRepair.ps1'
require, save, load = original.require, original.save, original.load
LAUNCH = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$p.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'-or$p.profile-cne'rmm.windows.raw-clock.original-system-create-repair.v1'-or$p.script_sha256-cne'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca'-or$p.action-notin@('repair','read')){throw 'Exact original fixture repair launch'}
$script='C:\ProgramData\RustDiscoveryBootstrap\ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca\SignedClockCaptureSystemRepair.ps1'
$i=Get-Item -LiteralPath $script -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-ne15551-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Exact original fixture repair bytes'}
$parent=$i.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No repair launch reparse ancestry'};$parent=$parent.Parent}
$a=Get-Acl -LiteralPath $script;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Repair controller owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private repair controller DACL'}}
$global:RmmCaptureSystemRepairPayload=$p
& $script
'''
def verify():
require(original.sha(ROOT / 'deploy/windows/signed_clock_capture_acceptance.py') == repair.RUNNER_SHA,
'unchanged original capture operator')
require(original.sha(ROOT / 'deploy/windows/signed_clock_capture_system_repair.py') == GENERATOR_SHA,
'reviewed original-case repair generator')
original.private(FOLDER, True)
manifest = load(FOLDER / 'manifest.json')
require(manifest['original_case'] == repair.CASE and manifest['generator_sha256'] == GENERATOR_SHA
and manifest['repair_script_sha256'] == SCRIPT_SHA and manifest['repair_script_bytes'] == 15551,
'original fixed repair artifact')
script = FOLDER / NAME
original.private(script)
require(script.stat().st_size == 15551 and original.sha(script) == SCRIPT_SHA,
'reviewed fixed repair controller')
require(original.sha(repair.ORIGINAL / 'manifest.json') == repair.MANIFEST_SHA,
'original partial setup provenance')
def stage(access):
# Separate literal allowlist; the original capture transport is unchanged.
prepare = original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', NAME)
observed = access.powershell(prepare, dict(sha256=SCRIPT_SHA))
if not observed['already_uploaded']:
credentials = original.pipe.cb.contract.protected_json(access.root / 'credentials/windows-dev-access.json')
prefix = credentials['ssh_prefix']
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + SCRIPT_SHA + '/' + NAME
result = subprocess.run(args, input=('put ' + json.dumps(str(FOLDER / NAME)) + ' '
+ json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
require(result.returncode == 0, 'one exact repair transfer; lost reply read only')
observed = access.powershell(prepare, dict(sha256=SCRIPT_SHA))
require(observed['already_uploaded'] is True and observed['sha256'] == SCRIPT_SHA,
'immutable staged original-case repair')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('stage', 'repair', 'read'))
args = parser.parse_args()
verify()
access = original.CaptureAccess(original.ACCESS_ROOT)
baseline = load(repair.ORIGINAL / 'baseline.json')
require(original.server_closed(access) == baseline['server'], 'original closed server counters and policy')
original.preserved(baseline['native'], original.native_witness(access))
action = args.action
if action != 'read':
save(FOLDER / (action + '-attempt.json'), dict(original_case=repair.CASE, once=True,
no_retry=True, script_sha256=SCRIPT_SHA, operator_sha256=original.sha(Path(__file__))))
if action == 'stage':
stage(access)
response = dict(staged=True, script_sha256=SCRIPT_SHA)
else:
if action == 'repair':
require((FOLDER / 'stage-reply.json').exists(), 'completed original stage; no restaging')
payload = dict(id=repair.CASE, profile=repair.PROFILE, action=action,
script_sha256=SCRIPT_SHA)
response = access.powershell(LAUNCH, payload, timeout=60)
identifier = str(uuid.uuid4()) if action == 'read' else action
save(FOLDER / (identifier + '-reply.json'), response)
after_server, after_native = original.server_closed(access), original.native_witness(access)
require(after_server == baseline['server'], 'closed server policy and counters unchanged')
original.preserved(baseline['native'], after_native)
save(FOLDER / (identifier + '-preservation.json'), dict(server=after_server, native=after_native,
original_case=repair.CASE, response_sha256=original.sha(FOLDER / (identifier + '-reply.json')),
no_rmm_jobs=True, no_role_start=True, setup_completed=False))
if action == 'repair':
require(response.get('system_created_stopped') is True and response.get('setup_completed') is False
and response.get('service_started') is False, 'only own SYSTEM fixture created stopped')
print(json.dumps(dict(action=action, original_case=repair.CASE, read_only=action == 'read',
preservation_sha256=original.sha(FOLDER / (identifier + '-preservation.json')),
response_sha256=original.sha(FOLDER / (identifier + '-reply.json')), preserved=True,
system_created_stopped=response.get('system_created_stopped'), setup_completed=False)))
if __name__ == '__main__':
main()
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Prepare one original-case-bound SYSTEM creation repair; no transport or execution.
Never replay the original setup. The generated controller can create only the
missing fixed SYSTEM fixture, or read its original repair records. It does not
finish setup, copy an executable, start/stop a service or remove anything.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import stat
import uuid
ROOT = Path(__file__).resolve().parents[2]
CASE = 'efd17b43-7e04-49a7-9bd4-862d13365eec'
ORIGINAL = ROOT / 'devstate/windows-signed-clock-capture-native' / CASE
RUNNER_SHA = 'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770'
MANIFEST_SHA = '806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'
CONTROLLER_SHA = '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'
EXE_SHA = '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'
EXE_BYTES = 8566784
MARKERS_SHA = 'ff8e2eef73139c8350aa0f86c6fed5125fce95f79d535f25224829ce4fa9c565'
PROFILE = 'rmm.windows.raw-clock.original-system-create-repair.v1'
def require(value, message):
if not value:
raise RuntimeError(message)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def private_read(path, limit=2 * 1024 * 1024):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as stream:
meta = os.fstat(stream.fileno())
require(stat.S_ISREG(meta.st_mode) and meta.st_nlink == 1 and meta.st_uid == os.getuid()
and stat.S_IMODE(meta.st_mode) == 0o600 and meta.st_size <= limit, 'private bounded original evidence')
raw = stream.read(limit + 1)
after = os.fstat(stream.fileno())
require(len(raw) <= limit and (meta.st_ino, meta.st_size, meta.st_mtime_ns, meta.st_ctime_ns)
== (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns), 'unchanged original evidence')
return raw
def write(path, raw):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def canonical(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
NATIVE = r'''
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class RmmCaptureSystemRepair {
const string LocalName="RmmSignedClockCaptureLocalService";
const string SystemName="RmmSignedClockCaptureSystem";
const string SystemCommand="\"C:\\ProgramData\\RustDiscoverySignedClockCapture\\efd17b43-7e04-49a7-9bd4-862d13365eec\\SignedClockCapture.exe\" --service efd17b43-7e04-49a7-9bd4-862d13365eec system";
[DllImport("advapi32.dll",EntryPoint="OpenSCManagerW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenManager(string machine,string database,uint access);
[DllImport("advapi32.dll",EntryPoint="CreateServiceW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr CreateService(IntPtr manager,string name,string display,uint access,uint type,uint start,uint error,string command,string group,IntPtr tag,string dependencies,string account,string password);
[DllImport("advapi32.dll",EntryPoint="OpenServiceW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenService(IntPtr manager,string name,uint access);
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool CloseServiceHandle(IntPtr handle);
[DllImport("advapi32.dll",EntryPoint="ChangeServiceConfig2W",ExactSpelling=true,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool ChangeServiceConfig2(Service handle,uint level,ref uint value);
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool QueryServiceStatusEx(Service handle,int level,out Status value,int size,out int needed);
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool SetServiceObjectSecurity(Service handle,uint info,IntPtr descriptor);
[DllImport("advapi32.dll",EntryPoint="ConvertStringSecurityDescriptorToSecurityDescriptorW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool ConvertSecurity(string text,uint revision,out IntPtr descriptor,out uint size);
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr value);
[StructLayout(LayoutKind.Sequential)] public struct Status {public uint Type,State,Controls,Win32Exit,SpecificExit,Checkpoint,WaitHint,Pid,Flags;}
static Exception Failed(string step){int code=Marshal.GetLastWin32Error();return new Win32Exception(code,"CAPTURE_SYSTEM_REPAIR_"+step);}
public sealed class Service:SafeHandleZeroOrMinusOneIsInvalid {
internal Service(IntPtr value):base(true){SetHandle(value);}
protected override bool ReleaseHandle(){return CloseServiceHandle(handle);}
public Status Read(){Status value;int needed;if(!QueryServiceStatusEx(this,0,out value,Marshal.SizeOf(typeof(Status)),out needed))throw Failed("QueryServiceStatusEx");return value;}
}
static IntPtr Manager(uint access){IntPtr value=OpenManager(null,null,access);if(value==IntPtr.Zero)throw Failed("OpenSCManagerW");return value;}
static Service OpenFixed(string name){IntPtr manager=Manager(1);try{IntPtr value=OpenService(manager,name,4);if(value==IntPtr.Zero)throw Failed("OpenServiceW");return new Service(value);}finally{CloseServiceHandle(manager);}}
public static Service OpenLocal(){return OpenFixed(LocalName);}
public static Service OpenSystem(){return OpenFixed(SystemName);}
public static Service CreateSystemOnce(){
IntPtr manager=Manager(3);try{
// Literal managed null is passed to the P/Invoke here. No PowerShell string
// binding or caller-selected service/account/path reaches CreateServiceW.
IntPtr value=CreateService(manager,SystemName,SystemName,0xf01ff,16,3,1,SystemCommand,null,IntPtr.Zero,null,null,null);
if(value==IntPtr.Zero)throw Failed("CreateServiceW");
Service service=new Service(value);try{
uint sid=1;if(!ChangeServiceConfig2(service,5,ref sid))throw Failed("ChangeServiceConfig2W");
IntPtr descriptor;uint bytes;if(!ConvertSecurity("D:P(A;;GA;;;SY)(A;;GA;;;BA)",1,out descriptor,out bytes))throw Failed("ConvertSecurityW");
try{if(!SetServiceObjectSecurity(service,4,descriptor))throw Failed("SetServiceObjectSecurity");}finally{LocalFree(descriptor);}
return service;
}catch{service.Dispose();throw;}
}finally{CloseServiceHandle(manager);}
}
}
'@
'''
HEADER = r'''
$ErrorActionPreference='Stop';$request=$global:RmmCaptureSystemRepairPayload
if(!$request-or(($request.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$request.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'-or$request.profile-cne'rmm.windows.raw-clock.original-system-create-repair.v1'-or$request.action-notin@('repair','read')-or$request.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed original system repair request'}
$p=@{id='efd17b43-7e04-49a7-9bd4-862d13365eec'};$base='C:\ProgramData\RustDiscoverySignedClockCapture';$case=Join-Path $base $p.id;$control=Join-Path $case 'control';$exe=Join-Path $case 'SignedClockCapture.exe';$boot='C:\ProgramData\RustDiscoveryBootstrap'
$names=@('RmmSignedClockCaptureLocalService','RmmSignedClockCaptureSystem');$tags=@('local-service','system');$accounts=@('NT AUTHORITY\LocalService','LocalSystem');$sys='S-1-5-18';$admin='S-1-5-32-544'
'''
BODY = r'''
if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'SignedClockCaptureSystemRepair.ps1')-or(HashFile $PSCommandPath)-cne$request.script_sha256){throw 'Actual exact repair controller'}
Check $PSCommandPath $false;foreach($dir in @($base,$case,$control)){Check $dir $true}
$oldController=Join-Path (Join-Path $boot '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4') 'SignedClockCaptureAcceptance.ps1';Check $oldController $false;if((HashFile $oldController)-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'){throw 'Original controller hash'}
$staged=Join-Path (Join-Path $boot '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb') 'SignedClockCapture.exe';Check $staged $false;if((Get-Item -LiteralPath $staged).Length-ne8566784-or(HashFile $staged)-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'){throw 'Original staged executable'}
$intent=ReadJson (Join-Path $control 'intent.json');if((($intent.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'-or$intent.action-cne'setup'-or$intent.id-cne$p.id-or$intent.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$intent.exe_bytes-ne8566784-or$intent.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$intent.script_sha256-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'-or$intent.manifest_sha256-cne'806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'){throw 'Exact original setup intent'}
$active=ReadJson (Join-Path $base 'active.json');if((($active.PSObject.Properties.Name|Sort-Object)-join',')-cne'id,manifest_sha256,no_retry,script_sha256'-or$active.id-cne$p.id-or$active.manifest_sha256-cne$intent.manifest_sha256-or$active.script_sha256-cne$intent.script_sha256-or$active.no_retry-ne$true){throw 'Same original active campaign'}
$allowed=@('intent.json','local-service-create-attempt.json','local-service-created.json','system-create-attempt.json','system-create-repair-attempt.json','system-create-repair-created.json','system-create-repair-failure.json');foreach($item in @(Get-ChildItem -LiteralPath $control -Force)){if($item.PSIsContainer-or$item.Name-notin$allowed){throw 'Unexpected campaign progress: no repair'}}
foreach($n in @(0,1)){$attempt=ReadJson (Join-Path $control ($tags[$n]+'-create-attempt.json'));if((($attempt.PSObject.Properties.Name|Sort-Object)-join',')-cne'command,create_once'-or$attempt.create_once-ne$true-or$attempt.command-cne(Command $n)){throw 'Original exact service attempt'}}
$made=ReadJson (Join-Path $control 'local-service-created.json');$local=Service 0;if((($made.PSObject.Properties.Name|Sort-Object)-join',')-cne'create_once,service'-or$made.create_once-ne$true-or!$local-or!(Equal $local $made.service)){throw 'Same original LocalService definition'}
$localHandle=[RmmCaptureSystemRepair]::OpenLocal();try{$localStatus=$localHandle.Read();if($localStatus.State-ne1){throw 'Original LocalService must remain stopped'}}finally{$localHandle.Dispose()}
foreach($path in @($exe,(Join-Path $case 'local-service'),(Join-Path $case 'system'))){if(Test-Path -LiteralPath $path){throw 'Unexpected setup completion or prior role entry'}}
$repairAttempt=Join-Path $control 'system-create-repair-attempt.json';$repairCreated=Join-Path $control 'system-create-repair-created.json';$repairFailure=Join-Path $control 'system-create-repair-failure.json'
$system=Get-CimInstance Win32_Service -Filter "Name='RmmSignedClockCaptureSystem'" -OperationTimeoutSec 5
if($request.action-ceq'read'){
$records=[ordered]@{};foreach($leaf in @('system-create-repair-attempt.json','system-create-repair-created.json','system-create-repair-failure.json')){$path=Join-Path $control $leaf;$records[$leaf]=$null;if(Test-Path -LiteralPath $path){$records[$leaf]=ReadJson $path}}
$systemMetadata=$null;if($system){$systemMetadata=@{command=$system.PathName;account=$system.StartName;start=$system.StartMode;type=$system.ServiceType;state=$system.State;definition_unverified=$true}}
@{id=$p.id;read_only=$true;local_service_verified_stopped=$true;system_present=[bool]$system;system=$systemMetadata;records=$records;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Depth 24 -Compress;exit 0
}
if($system-or(Test-Path -LiteralPath $repairAttempt)-or(Test-Path -LiteralPath $repairCreated)-or(Test-Path -LiteralPath $repairFailure)){throw 'Existing system or repair attempt: original read only'}
WriteNew $repairAttempt @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;original_manifest_sha256=$intent.manifest_sha256;original_controller_sha256=$intent.script_sha256;create_once=$true;system_account_null_inside_csharp=$true;command=(Command 1);no_retry=$true}
$handle=$null
try{
$handle=[RmmCaptureSystemRepair]::CreateSystemOnce();$status=$handle.Read();if($status.State-ne1){throw 'New SYSTEM fixture must remain stopped'}
$created=Service 1;if(!$created){throw 'New fixed SYSTEM definition absent'}
$still=Service 0;if(!(Equal $still $made.service)){throw 'Original LocalService definition changed'}
WriteNew $repairCreated @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;service=$created;stopped=$true;create_once=$true;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}
@{id=$p.id;system_created_stopped=$true;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Compress
}catch{
$inner=$_.Exception;while($null-ne$inner.InnerException){$inner=$inner.InnerException};$native=$null;$step='managed_postcondition';if($inner-is[ComponentModel.Win32Exception]){$native=$inner.NativeErrorCode;if($inner.Message-match'^CAPTURE_SYSTEM_REPAIR_[A-Za-z0-9]+$'){$step=$inner.Message}}
if(!(Test-Path -LiteralPath $repairFailure)){WriteNew $repairFailure @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;failed=$true;step=$step;native_error_code=$native;read_original_case_only=$true}}
throw 'SYSTEM repair failed; read the original case only; do not retry'
}finally{if($null-ne$handle){$handle.Dispose()}}
'''
def helpers(original):
# Reuse only the exact original pure ACL/metadata/record helpers. Never
# import/dot-source/execute the original controller or its setup branch.
def section(start, end):
require(original.count(start) == 1 and original.count(end) == 1, 'unique original helper boundaries')
return original[original.index(start):original.index(end)]
output = section('function HashBytes', 'function NewDir')
output += section('function WriteNew', 'function Original')
require('function NewDir' not in output and 'CreateOnce' not in output and 'function ReadAll' not in output,
'only bounded original helper subset')
return output
def prepare():
require(sha((ROOT / 'deploy/windows/signed_clock_capture_acceptance.py').read_bytes()) == RUNNER_SHA,
'original runner unchanged')
original_manifest = private_read(ORIGINAL / 'manifest.json')
original_script = private_read(ORIGINAL / 'SignedClockCaptureAcceptance.ps1')
markers = private_read(ORIGINAL / 'marker-query-result-5c07d236-a249-450e-83f8-e5c22c49bae3.json')
require(sha(original_manifest) == MANIFEST_SHA and sha(original_script) == CONTROLLER_SHA
and sha(markers) == MARKERS_SHA, 'exact original partial-case provenance')
marker_value = json.loads(markers)
require(marker_value == {'names': ['intent.json', 'local-service-create-attempt.json',
'local-service-created.json', 'system-create-attempt.json'], 'read_only': True},
'actual original four-marker partial state')
# Read the already-qualified public executable only; never credentials/pins/keys.
executable = private_read(ORIGINAL / 'SignedClockCapture.exe', EXE_BYTES)
require(len(executable) == EXE_BYTES and sha(executable) == EXE_SHA, 'original qualified executable unchanged')
script = (HEADER + helpers(original_script.decode()) + NATIVE + BODY).encode('ascii')
require(len(script) <= 32768, 'bounded single-purpose repair controller')
state = ROOT / 'devstate/windows-signed-clock-capture-system-repair'
state.mkdir(mode=0o700, parents=True, exist_ok=True)
require(state.stat().st_uid == os.getuid() and stat.S_IMODE(state.stat().st_mode) == 0o700,
'private local repair artifact root')
folder = state / str(uuid.uuid4())
folder.mkdir(mode=0o700)
write(folder / 'SignedClockCaptureSystemRepair.ps1', script)
for action in ('repair', 'read'):
write(folder / ('payload-' + action + '.json'), canonical(dict(id=CASE, profile=PROFILE,
action=action, script_sha256=sha(script))))
manifest = {'profile': PROFILE, 'original_case': CASE, 'original_manifest_sha256': MANIFEST_SHA,
'original_controller_sha256': CONTROLLER_SHA, 'original_runner_sha256': RUNNER_SHA,
'original_marker_receipt_sha256': MARKERS_SHA, 'exe_sha256': EXE_SHA,
'repair_script_sha256': sha(script), 'repair_script_bytes': len(script),
'generator_sha256': sha(Path(__file__).read_bytes()), 'target_executed': False,
'no_original_controller_replay': True, 'no_start_stop_delete_or_setup_completion': True}
write(folder / 'manifest.json', canonical(manifest))
print(json.dumps({'path': str(folder), **manifest}, sort_keys=True))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['prepare'])
parser.parse_args()
prepare()
if __name__ == '__main__':
main()
+28
View File
@@ -87,3 +87,31 @@ gegeben; dieser prüft eigene Control-/Inventar-/Prozesszeugen unabhängig.
Der zuerst qualifizierte Deliveryschnitt oben bleibt historisch. Änderungen
und tatsächliche lokale Folgeprüfungen sowie offene native Gates stehen in
[agent-updater-runtime-source.md](agent-updater-runtime-source.md).
## Exakte lokale Applyspanne statt Sekundenquantisierung
Nachtrag2026-11-15: Der unveränderte eingefrorene Healthreceipt enthält
`signed_sync_applied_at` weiterhin als `u64` und unverändert als
`floor(confirming.issued_at)`. Dieser Scalar erteilt keine Zeitfreigabe.
Der neue lesende Coregetter `update_health_sync::read_round` prüft bounded
die vorhandenen Originalrequest-Protobufs, SignedResponsebytes und tatsächlich
im selben HelperSync-Commit gespeicherten Appliedwitnesses. Die bestehende
Signatur-/Kontextprüfung läuft unabhängig erneut; es wird weder ein ACKboolean
noch eine Callerzeit akzeptiert und kein Journal/Ready/Lease neu geschrieben.
`verified_span` findet genau ein tatsächlich angewandtes bestätigendes D2 mit
beiden vorherigen Decision-IDs gleich D1, derselben Originalgeräte-/Boot-/
Verbindungsbindung und identischem ServicesStarted-Präfix. Dieser Präfix muss
auch unverändert im aktuellen Originalhandoff enthalten sein. Der Fullguard
prüft jetzt `D1.issued_at <= actual_local_applied_at <= D2.issued_at` mit
den exakten ursprünglichen DateTimes. Erst danach folgt die bestehende lokale
Inventar-/Dienst-/Originalhealthprüfung. Der u64-Wert wird ausschließlich auf
Gleichheit mit dem ursprünglichen D2-Sekundenfloor geprüft.
Der enge tatsächliche Grenzfall akzeptiert beide exakten Endpunkte und verweigert
eine um1ns zu frühe oder zu späte Anwendung trotz identischem Sekundenfloor.
Der vorhandene vollständige negative HelperSyncfall prüft zusätzlich den echten
Original-Roundgetter nach Signatur-/Applypersistierung. Lokaler Quell-/Testbeleg:
`devstate/updater-health-exact-span-6879f7cc-f284-4f50-b3e6-de321f3af6a2/`.
Kein nativer Health-/Applynachweis und keine Änderung an Frozenreceipt-/
Kernelbytes oder an der WebUI-Grenze.
+11
View File
@@ -130,3 +130,14 @@ und ursprüngliche Admissionstrecke, qualifizierte passive Kandidatenbeobachtung
geschlossene Readercensus, unklare Record-I/O-Namespace-Adjudikation und der vor
der ersten Baseline notwendige V2-Rückweg bleiben offen. Applyfähigkeit bleibt
unveröffentlicht; kein Cloud-VM-Apply, kein Produktfertig- oder Produktionsnachweis.
## Nachtrag2026-11-15: gesperrte Worker-Drivefolge
Nach dem gepushten gemeinsamen Checkpoint8e93c9e und dem erhaltenden Mainmerge
07d6118 ist die bisher offene Enginefolge als konkrete Workerquelle verbunden.
Ihr Eintritt bleibt explizit `UPDATE_READER_CENSUS_NOT_CONFIGURED`; weder
Daemonentrypoint noch Job-/Applycapability wird aktiviert. Die genaue
Queue-/Reply-/Stop-/Lock-/Swap-/Start-/Healthfolge und vorhandene separate
Agent-Singletonsperre stehen in [worker](agent-updater-worker.md). Der neu
geprüfte öffentliche Recordbuilder löst die zuvor dort genannte fehlende
positive authentisierte Eingangsprobe. Keine reale Applyabnahme folgt daraus.
+46
View File
@@ -158,3 +158,49 @@ keine echte UI-/Job-/Service-/Rootguardwirkung und umgehen ausdrücklich den
öffentlichen authentisierten BuiltRecordeingang. Aktueller Source-/Nachweisstand
und restliche Engine-/Admission-/Rollback-/Nativegates:
[Runtimefortschreibung](agent-updater-runtime-source.md).
## Einmalige Queue-/Drivefolge und vorhandene Agent-Singletonsperre
Am2026-11-15 liegt `worker::engine::Runtime` als noch gesperrter Quellschnitt
vor. Der vorhandene IPC-Activatehandler queuet ausschließlich den originalen
Handoff; die private Drivefolge ist erst nach vollständig geschriebenem Reply
und geschlossener Accepted-Verbindung erreichbar. Eine verlorene Antwort
verwirft die Queue und sperrt dieselbe Runtime. Die erste Fullbridge-Lesung
übernimmt den tatsächlich authentisierten Originalpräfix; vorher sind alle
mutierenden Methoden gesperrt und kein Event wird aus Headerdaten erfunden.
Die Folge verbindet Originalsignatur-/Policy-/Floor-/Dateibeobachtungen, alle
drei Full-Stopclaims vor irgendeinem Stop, die tatsächlichen Stopbeobachtungen
im Originalledger nach Guardübernahme, AllStopped/Owns, vier getrennte
Save-/Publishpaare, Pair, Return-/Startreservation, tatsächlichen DBclose und
flockdrop, General→Full→Agent und neue Full-Start-/Health-/Recordbestätigung.
Es gibt keinen Resume oder Restore. Ein Fehler bei den Fileübergängen versucht
unter dem noch gehaltenen Originalguard genau einen Unknown-CAS und startet
keinen Dienst neu. Native Dienst-/Fehlerfolgen sind damit noch nicht bewiesen.
Zusätzlich wird die vorhandene `/var/lib/rmm-agent-remote/agent.lock` aus dem
OriginalRetainedSet gebunden: unveränderter Inode, UID993/GID984/0600/nlink1,
0Bytes und privater Parent. Nach echtem StoppedServices-Beleg nimmt der Worker
diese vorhandene Sperre exklusiv ohne CREATE. Sie bleibt über Root-DB/Swap/
DBclose/Rootlockreturn gehalten und wird vor der festen Startfolge zurückgegeben.
Der Agent hält schon heute seine ursprüngliche Singletondatei vor beiden
Agent-SQLiteöffnungen; keine ACL, Agentdatei oder Sperrrolle wurde geändert.
**Explizite Sperre dieses Checkpoints:** `Runtime::serve_one` verweigert mit
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Geschützte kompatible Bootstrapregistry
plus vollständige aktuelle PID-/FD-/maps-Census und Nachstopbeobachtung unter
beiden tatsächlichen Sperren fehlen noch. Eine bekannte Unitliste ersetzt
keinen Census. Keine CLI oder RMM-Admission ruft diese Runtime auf; Applycaps
bleiben geschlossen. Ebenso offen: Staging-/Downloadproducer, passiver gültiger
Updatezustand, V2-Rollbackvertrag vor dem ersten Bootstrap, Unsicherheits-
Namespaces, qualifizierte Dienstkontexte und tatsächlicher Linux-Apply.
Lokaler Nachweis liegt unter
`devstate/updater-engine-source-6a8bb902-4db4-4d93-8843-450ba1dd5622/`.
Der7er-Workerlauf umfasst jetzt auch den **öffentlichen** BuiltRecordbuilder:
Originalsignierter Job und echte vollständig signierte History ergeben exakt
die erwarteten Rawrecordbytes. Ein für einen fremden externen Healthkey gültiger
Journal bleibt unter dem Originaljobkey unzulässig; geänderter Head/prior wird
verweigert. Ein separater echter Container-FS-Fall belegt die Agent-Singleton-
Aliasblockade und Ablehnung eines gleichbyteigen Inodeersatzes. Dies sind lokale
Krypto-/FS-Verträge; sie führen die Queue-/Drive-/Dienstfolge nicht aus.
+14
View File
@@ -1,5 +1,19 @@
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
**Provider-Socketfix Linux-first bestanden:** Originalfall8ee39b4f, native
Cloud-Linux4/4 ohne Skip/Filter, separater Originalread vollständig; bekannte
Runtimezeugen erhalten.0755 akzeptiert, Gruppen-/Fremdwrite verweigert,
Ancestry/Socket-/Daemon-/Credentialbindung erhalten. [Ergebnis](server-time-source.md).
Keine Chronyrechte geändert und noch keine echte Serverqualitätsprobe.
**Windows-Messfixture eng repariert:** Originalfallefd17b43, separate
SYSTEM-Erstellung mit C#-internem NULL erfolgreich, beide eigenen Messdienste
verifiziert gestoppt; separater Readback und sämtliche RMM-/Serverzeugen erhalten.
Originalsetup bleibt fehlgeschlagen, keine Rollenstarts/Calibration/Clockfreigabe.
[Reparatur und Grenzen](windows-raw-capture-system-repair.md).
**Finaler Windows-Kontextfence Linux-first bestanden:** Originalfall1e179c84,
volle15er-Liste, nur geänderten Fencetest1PASS/14filtered ausgeführt; separater
Readback vollständig, bekannte Runtimezeugen erhalten. Recheck und erkannter
+15 -2
View File
@@ -108,8 +108,8 @@ exakt drei tatsächlichen Prozesse seiner festen Cgroup
Chronyd-Kind. Keine zusätzliche oder untergeordnete Cgroup wird übergangen.
Beide Chronyd-Prozesse müssen UID/GID989 und dieselben geschützten
`/usr/sbin/chronyd`-Originalbytes besitzen. Der Root:Root0644-single-link-Pidfile
`/run/chrony/chronyd.pid` bestimmt den Daemon; weil das Verzeichnis UID/GID989
gehört, reicht diese Datei allein ausdrücklich nicht als Namensautorität.
`/run/chrony/chronyd.pid` bestimmt den Daemon; weil das Verzeichnis UID/GID989 und Modus0700
besitzt, reicht diese Datei allein ausdrücklich nicht als Namensautorität.
Zusätzlich muss unter diesen drei Prozessen ausschließlich genau der gewählte
Daemon den tatsächlichen Kernelinode des festen Unix-Datagramsockets
`/run/chrony/chronyd.sock` halten. Diese begrenzte Beobachtung behauptet keine
@@ -301,3 +301,16 @@ werden: der Dateiname `operator.py` darf keine gleichnamigen Python-Standardmodu
gespeichert; unerwartete Fehler liefern nur `unexpected_operator_exception`,
keinen Exceptiontext oder Traceback. Verlorene Antworten erlauben ausschließlich
Lesen des ursprünglichen Falls, keine Phasenwiederholung oder Pinheilung.
Der nachfolgende tatsächliche Preflightfall
`053cfe86` verweigerte allein die zuvor fälschlich erwartete
Chronyverzeichnisberechtigung0755. Der lesende Originalbeleg
`22fa2aabdfdbbd0fe55957358f7f651f317ee647b20a46ab1f2613a365095d7f`
zeigt UID/GID9890700 für `/run/chrony`, Root:Root0644 mit einem Link für die
Pidfile und UID/GID9890755 mit einem Link für den Socket. Der Operator verlangt
jetzt exakt das beobachtete Verzeichnis0700. Der Provider akzeptiert am Socket
Lese-/Ausführungsbits, verweigert weiterhin Gruppen-/Fremdschreibrechte und
behält alle Identitäts-, Ancestry- und Kernelcredentialprüfungen bei. Es wurden
keine Chronyberechtigungen geändert. Beide fehlgeschlagenen Originalfälle bleiben
erhalten; diese Quelle benötigt erneut einen neuen Paket-/Abnahmefall.
+41 -2
View File
@@ -50,8 +50,13 @@ würdigen Pin separat provisionieren und die Providerinstanz neu eröffnen.
Ziel ist ausschließlich `/run/chrony/chronyd.sock`. Seine Identität und
Verzeichniskette werden vor und nach der Abfrage geprüft. Nicht-root-eigene
Verzeichnisse müssen dem gepinnten Chrony-Konto gehören; kein Gruppen- oder
Fremdschreibrecht. Der Socket muss dem gepinnten Daemonkonto gehören und darf
keine Rechte für Fremde haben. Andere Images oder Layouts bleiben vorerst
Fremdschreibrecht. Der Socket muss ein einzelner Socketinode des gepinnten Daemonkontos sein
und darf weder Gruppen- noch Fremdschreibrecht haben. Lese-/Ausführungsbits
wie beim tatsächlich beobachteten Modus0755 verleihen auf Linux kein Recht,
ein Datagramm zu senden; dafür ist Schreibrecht am Pathnamesocket erforderlich
([Linux unix(7)](https://man7.org/linux/man-pages/man7/unix.7.html)). Der Server
verwendet tatsächlich das gehaltene Chronyverzeichnis UID/GID9890700; dessen
Identität sowie sämtliche übrigen Ancestry-/Credentialprüfungen bleiben Pflicht. Andere Images oder Layouts bleiben vorerst
nicht unterstützt, ohne permissiven Fallback.
Der vom Rootoperator separat anzulegende Clientbereich ist
@@ -210,3 +215,37 @@ Socket-Fixtures einschließlich tatsächlicher Namenersetzung/FD-Cleanup.
diesem Lauf.** Der neue native OS-/Validatornachweis ersetzt nicht die offene
reale ARM64-Serverprobe mit provisioniertem Pin und frischer gemeinsamer
Chrony-/Kernelqualität.
## Tatsächlich nativ: Socketberechtigungsfix auf Cloud-Linux
2026-11-15, Originalfall `8ee39b4f-daed-4953-b90f-c04a7b2857c1`:
alle vier vollständig gelisteten Provider-Vertragsprüfungen auf der
tatsächlichen Cloud-Linux-VM als UID0 bestanden,0 fehlgeschlagen,0 ignoriert,
0 gefiltert. Separater Originalfall-Readback vollständig; bekannte Runtimezeugen
vorher/nachher/aktuell unverändert. Der bestehende Sockettest enthält jetzt
ausdrücklich0755 positiv sowie0775/0757 negativ. Root-/Daemonidentitäten,
gehaltene Verzeichnis-/Socketinodes, Singlelink und SCM-Credentials werden
nicht durch eine Berechtigungsausnahme ersetzt. Auf dem Server wurde keine
Chrony-Datei oder -Berechtigung geändert.
Qualifizierte Nativequelle-SHA256
`f1fede6a260c4f91c4bf647f2dcadb63520cdadff22c0130327ecd7cae57921b`.
Lokale eingefrorene Releasequalification7a8cb5be-41b3-400a-bd9b-b4b6f505a6e9,
Receipt-SHA256
`74759e286ba7c9762fe4c455da952a0e62de48f55ea643e0a8f435d2128497a5`,
Sieben-Inputmanifest
`c0067889fa6e79e5b1dc2ad46685613fd0b379b30a4541670f635140405718d9`.
Diese Inputs enthalten auch die zum Freezezeitpunkt gesicherte Dokumentfassung;
nachfolgende Ergebnisdokumentation ist kein Compilerinput. ELF1169800Bytes,
SHA256 `9bd41ff166aeaae45fdf3dda2d72b04fc30e5ef87a181fe733c47e511a836d59`.
Neuer Operator `deploy/time_source_socket_linux_acceptance.py`, SHA256
`eef43096cac8a83751f844d810b97a3f68025786ca64ff34f82be59280ca1aa8`.
Der Lauf verwendet eigene Parser-/Clock-/Socketfixtures. Er öffnet keine
echte NativeTimeSource, fragt weder tatsächliches Chrony noch die Kernelzeit
ab und qualifiziert keinen signierten Zeitanker oder Windowsclock. Reale
Serverprobe und nachfolgender Broker-/mTLS-Roundtrip bleiben offene Schritte.
Ausführungsreceipt-SHA256 `0decb992bfbfa88389da1949fddb491f2ec02a30abc9f4cce886d1f645768e07`.
Separater Rückabruf-SHA256 `88728b6659d506ba96140dd1924a089969e63fcd6f6d308109c4603ec4043da8`.
+171
View File
@@ -0,0 +1,171 @@
# Eigener SYSTEM-Reparaturschritt des bestehenden Rohcapturefalls
Der einzige Zielfall bleibt `efd17b43-7e04-49a7-9bd4-862d13365eec`.
`deploy/windows/signed_clock_capture_system_repair.py prepare` erzeugt nur lokal
einen gesonderten festen Controller. Er enthält keine SSH-/Übertragungs- oder
Ausführungsfunktion. Originalrunner, Originalcontroller, Manifest und sämtliche
alten Marker werden weder verändert noch erneut ausgeführt.
## Tatsächlicher Befund
Das ursprüngliche Setup scheiterte auf der zusammengefassten PS-Zeile138.
Der lesende Markerbeleg
`ff8e2eef73139c8350aa0f86c6fed5125fce95f79d535f25224829ce4fa9c565`
enthält `intent.json`, `local-service-create-attempt.json`,
`local-service-created.json` und `system-create-attempt.json`. Der ebenfalls
lesende Servicebeleg findet den exakten LocalService gestoppt/Manual mit
UNRESTRICTED-SID und der eingerichteten Admin-/SYSTEM-DACL; SYSTEM fehlt.
Damit kam der erste `CreateOnce` vollständig zurück und der Fehler liegt sehr
nahe an der zweiten Dienstanlage. Der ursprüngliche NativeErrorCode wurde
nicht gesichert; beispielsweise1057 wird deshalb **nicht** als Messwert behauptet.
Der konkrete Quellfehlerkandidat ist die Übergabe von PS-`$null` an den
C#-Stringparameter `account`. Für einen echten .NET-null-String sieht PowerShell
den Typ [NullString](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.language.nullstring)
vor, auch in5.1. [CreateServiceW](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-createservicew)
dokumentiert NULL als LocalSystem-Default; ein leerer Accountstring ist kein
dokumentierter Ersatz. Der Restzustand passt zu diesem Binderfehler, beweist
die verlorene ursprüngliche Nativefehlernummer jedoch nicht.
Die ursprünglichen SafeHandle-/Disposepfade schließen Handles, löschen aber
keinen Dienst; ihr `ReleaseHandle` gibt nur ein Boolean zurück. Eine solche
Schließung erklärt hier nicht den expliziten `Win32Exception`-Pfad. Separat
wurde eine tatsächliche falsche Erfolgsprüfung gefunden: `Service.Read` verlangt
`pcbBytesNeeded==sizeof(Status)` auch nach erfolgreichem
[QueryServiceStatusEx](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-queryservicestatusex).
Dieser Ausgabewert ist für den Fall `ERROR_INSUFFICIENT_BUFFER` beschrieben;
die Größe darf kein zusätzlicher Erfolgsindikator sein. Die Reparaturklasse
prüft daher nur den tatsächlichen BOOL-Erfolg und sichert einen Fehler sofort.
Der unveränderte Rohcaptureprozess verwendet Token, Service-SID-Lookup und
gehaltene Dateien. Er ruft nicht `PeerProof::for_service`/`OpenServiceW` auf.
Ein zusätzlicher LocalService-SCM-ACE ist für diesen konkreten Rohcapturepfad
deshalb nicht erforderlich; die gegenwärtige Dienst-DACL wird nicht erweitert.
Spätere installierte Adapterpfade sind gesondert zu beurteilen.
## Implementierter, noch nicht am Ziel ausgeführter Reparaturumfang
Lokaler Paketfall
`devstate/windows-signed-clock-capture-system-repair/cff25311-d30b-495a-8b50-e0e28e2e5b48`:
Controller15551Bytes, SHA256
`ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca`.
Generator-SHA256
`9b44aa1491be2d154fb37fd0431370657f9623a2440649c29e910826beb44d2e`.
Die lokalen Manifest-/Payloaddateien nennen weiterhin ausschließlich den
ursprünglichen Zielfall. Eine neue lokale Artefakt-ID ist kein neuer Zielversuch.
Vor der einzigen neuen SystemCreate-Operation prüft der Controller:
- Eigenen tatsächlich ausgeführten Hashpfad sowie Originalcontroller89c19138…,
Originalmanifest806c062b… über den ursprünglichen Setupintent/active-Bezug
und die unveränderte gestagte EXE601c27a4… mit8566784Bytes.
- Geschützte Originalverzeichnisse und exakt erlaubten Markerfortschritt,
beide ursprünglichen Createattempts samt fester CLI und den bereits erzeugten
LocalService anhand seines originalen Createdbelegs, der Service-SIDart,
ACLhash, Startart, Konto, Typ und Abhängigkeiten. Ein gehaltener SCM-Queryhandle
muss ihn als gestoppt melden.
- Noch fehlenden SYSTEM-Dienst und fehlende Repairattempt-/Created-/Failuremarker.
Noch keine Rollenverzeichnisse, installierte Case-EXE oder weitere Start-/
Setupmarker. Fremde oder weiter fortgeschrittene Zustände verweigern.
Er schreibt dann ausschließlich einen neuen create-only
`system-create-repair-attempt.json`, legt SYSTEM genau einmal an, setzt SIDart1
und dieselbe enge Dienst-DACL und prüft den weiterhin gestoppten Zustand.
Name und CLI sind feste C#-Konstanten; **NULL entsteht innerhalb C#**, kein
Accountstring kommt aus PowerShell oder Payload. Nativeaufrufe erhalten feste
Schrittnamen und sofort gesicherte NativeErrorCodes. SafeHandleparameter
halten den SCM-Handle während des nativen Reads gültig. Erfolg und Fehler
erhalten eigene neue Marker, die alten Systemattempts bleiben unangetastet.
Es gibt nur `repair` und `read`. Nach fehlender Antwort/Fehler ausschließlich
`read` des Originalfalls, niemals erneut `repair` oder Original-`setup`.
Ein nach CreateService fehlgeschlagener SID-/ACLschritt bleibt offen sichtbar;
kein automatisches Delete oder vermeintlicher Erfolg. `read` zeigt die feste
SYSTEM-Definition in einem solchen Restzustand ausdrücklich als unverifiziert.
Keine Starts/Stops/Deletes, Zeitsetter, W32Time-/RMM-Änderung, EXE-Kopie oder
Setupcompletion. Ein erfolgreicher SystemCreate allein bedeutet **keine
Capturebereitschaft**.
Tatsächlich lokal: Python-AST, Pakethashes, ursprüngliche Fallbindung und
begrenzter Mutationsumfang geprüft. Kein PowerShell-/C#-Compiler ist hier
verfügbar; native Parser-/Add-Type-Prüfung und sämtliche Zielaktionen wurden
durch diesen Worker nicht ausgeführt. Diese Grenzen stehen im lokalen Beleg.
## Getrennte nächste Finalisierung und Controllerkorrektur: Vorschlag
Der Originalsetupfehler lag vor Service-SID-Auflösung, Reader-ACLs, beiden
Rollenverzeichnissen, EXE-Kopie und Setupcompletion. Ein weiterer eigener
Originalfallcontroller muss diesen fehlenden Rest explizit abschließen:
1. Neue create-only Finalisierungsabsicht nach ursprünglicher Fall-/Hashbindung,
originalem LS-Createdbeleg und erfolgreichem neuen SYSTEM-Repaircreatedbeleg.
Beide festen Dienste müssen exakt passende, weiterhin gestoppte Definitionen
haben; beide tatsächlichen `NT SERVICE`-SIDs unabhängig auflösen und prüfen.
Keine Rawrollen-Startattempts/-Intents/-Ergebnisse zulassen.
2. Die bisher rootgeschützten Base-/Case-ACLs auf genau die zwei eigenen
Reader-SIDs ergänzen. Ausschließlich die zwei noch fehlenden eigenen
Rollenverzeichnisse create-only mit dem jeweils eigenen Writer-SID anlegen;
die unveränderte EXE ausschließlich create-only aus dem gesicherten Staging
übernehmen, Hash/Größe und finales ACLprofil erneut prüfen. Kein breites
ACL-Repair, fremdes Objekt oder Überschreiben.
3. Einen **neuen** `setup-repair-complete.json` schreiben. Originales Setup und
dessen fehlender `setup-complete.json` werden nicht rückwirkend erfolgreich
erklärt. Eine partielle neue Finalisierung bleibt als eigener Intent ohne
Erfolg; keine automatische Wiederholung/Resume-Engine.
4. Einen weiteren getrennt gehashten Controller aus den Originalbytes erzeugen:
Original-`setup` dauerhaft verweigern; für nachfolgende Start-/Read-/Cleanup-
Aktionen den neuen Completionbeleg sowie originalen LS- und reparierten
SYSTEM-Createdbezug verlangen. Originalcontroller/Manifesthash zusätzlich
prüfen, eigene Scriptpfad-/Hashprüfung auf den neuen Controller binden.
Die einzige Änderung am nativen Statusread ist das Entfernen der falschen
`pcbBytesNeeded`-Erfolgsgleichheit. Kein Clock-/Capturealgorithmuswechsel.
Erst ein eindeutiger eigener Rollenstartintent erlaubt anschließend eine einzige
Rohcaptureausführung. LS zuerst, SYSTEM erst nach eindeutig erfolgreichem LS-
Originalergebnis; Prozessgeneration-/Watchdog- und Ausgabebelege bleiben wie im
Originalprofil erforderlich. Cleanup ist separat: nur verifizierte eigene
gestoppte Dienste über gehaltene SCM-Handles und passende originale/reparierte
Createdbelege löschen, niemals ein freier Name, unbekannter Prozess oder blindes
Stoppen. Bei unklarem Start-/Exit-/Deletezustand ausschließlich Originalfall
lesen. Die hier gelieferte SystemCreate-Reparatur implementiert diese spätere
Finalisierung und Cleanupkorrektur noch nicht.
## Tatsächliche native Reparatur, 2026-11-15
Root führte nach unabhängigem Review den unveränderten Reparaturcontroller
`ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca`
im Originalfall efd17b43 aus. Zuvor bestätigte die Windows-VM
PowerShell5.1.26100.9818:0 ASTfehler, isolierte C#-Kompilierung bestanden,
Controller dabei nicht ausgeführt. Syntaxreceipt
`f0586ef81853cc942b8043088b9c46336808c41cb89aa6d1afaff0e0b1483b30`.
Der dünne native Operator `signed_clock_capture_repair_acceptance.py`
(SHA256 `85fa12492c303beec4539fe38fc3fa81455594a4a62722aa8950b1497f4016f8`)
verwendet ausschließlich den bestehenden gepinnten Transport und seinen einen
festen zusätzlichen Stagenamen. Ein unabhängiger Review fand vor Ausführung
die fehlende Bindung lokaler Nutzlastdateien an die ausgewählte CLI-Aktion;
diese wurde durch vollständig im Code festgelegte Nutzlasten behoben. Ein
`read` kann deshalb keine `repair`-Nutzlast aus einer Datei übernehmen.
Staging erfolgreich, anschließend genau ein Reparaturaufruf erfolgreich:
SYSTEM-Messdienst neu angelegt und tatsächlich gestoppt, LocalService weiterhin
verifiziert gestoppt. `setup_completed=false`, `service_started=false`.
Repairreply-SHA256
`b87746dc066fc255d2cbf1871698811203d38410e27c8d6d51d2d38ea7752c96`,
zugehöriger Erhaltungsbeleg
`a1bb8a42e22f2d0263dc381bd675134effe6555867b57b7f4fae28eb6f319ad6`.
Die sechs vollständigen nativen RMM-Witnessfelder einschließlich Helpermetadata
und stabiler Journalidentität sowie aktuelle Serverpolicy/Zähler sind vorher
und nachher unverändert. Linux31/31/27/0, Windows0/0/0/0; kein RMM-Job.
Das ursprüngliche Setup bleibt fehlgeschlagen. Seine Bytes und Marker bleiben
erhalten; ein `setup-complete` oder Rohmessbericht wurde nicht nachträglich
erfunden. Es gab weder Rollenstart noch Clockpin-/RMM-Konfigurationsänderung,
Kalibrierung, W32Time-Anweisung oder Jobfreigabe. Die noch fehlende endgültige
Messfixtureeinrichtung und anschließenden beiden Rollenprüfungen bleiben offen.
Separater tatsächlicher Original-Readback bestanden: Antwort-SHA256
`fad16846247eb6d84f352802aeb0dbc368f32cbee1512ca4c4d63b22aedb62b8`,
Erhaltungsreceipt
`336b4ff6cbf718658dd3c459ac716bbaee2e2e82c60bac79ac6a9631ce3e66e7`.
Er liest die ursprünglichen neuen Reparaturmarker, startet und repariert nichts.