This commit is contained in:
@@ -80,10 +80,13 @@ impl Continuity {
|
||||
"TIME_NATIVE_CONFIGURATION_GENERATION"
|
||||
);
|
||||
if let Some((current, hash)) = &self.configuration {
|
||||
ensure!(
|
||||
generation >= *current && (generation != *current || hash == sha256),
|
||||
"TIME_NATIVE_CONFIGURATION_ROLLBACK_OR_FORK"
|
||||
);
|
||||
if generation < *current || (generation == *current && hash != sha256) {
|
||||
// A constructor has positively observed a protected rollback
|
||||
// or fork. Reject it without adopting its head, and retain the
|
||||
// process-wide failure even if the original bytes are restored.
|
||||
self.invalidate();
|
||||
anyhow::bail!("TIME_NATIVE_CONFIGURATION_ROLLBACK_OR_FORK");
|
||||
}
|
||||
if generation > *current {
|
||||
self.invalidate();
|
||||
}
|
||||
@@ -131,6 +134,13 @@ impl Continuity {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn require_epoch(&self, epoch: u64) -> Result<()> {
|
||||
ensure!(
|
||||
!self.exhausted && self.epoch == epoch,
|
||||
"TIME_NATIVE_EVIDENCE_INVALIDATED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// All three native clocks are read in one bracket. The qualified base error
|
||||
@@ -396,7 +406,8 @@ mod installed {
|
||||
use rmm_agent_core::auth::Binding;
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_time_attestation::{
|
||||
Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, Verifier,
|
||||
Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, VerifiedEvidence,
|
||||
Verifier,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
@@ -467,6 +478,10 @@ mod installed {
|
||||
epoch: u64,
|
||||
challenge: Challenge,
|
||||
}
|
||||
struct HeldEvidence {
|
||||
evidence: VerifiedEvidence,
|
||||
epoch: u64,
|
||||
}
|
||||
/// Own-process role proof, protected held configuration, private challenge
|
||||
/// and native timers. No constructor accepts agent-reported helper times.
|
||||
pub struct SignedClock {
|
||||
@@ -478,6 +493,7 @@ mod installed {
|
||||
connection_generation: u64,
|
||||
base_error_ns: u64,
|
||||
pending: Option<Pending>,
|
||||
latest: Option<HeldEvidence>,
|
||||
}
|
||||
impl SignedClock {
|
||||
/// Connection generation is later confirmed by the independently
|
||||
@@ -602,6 +618,7 @@ mod installed {
|
||||
connection_generation,
|
||||
base_error_ns,
|
||||
pending: None,
|
||||
latest: None,
|
||||
};
|
||||
value.recheck()?;
|
||||
process()
|
||||
@@ -612,16 +629,34 @@ mod installed {
|
||||
Ok(value)
|
||||
}
|
||||
fn recheck(&mut self) -> Result<()> {
|
||||
self.own_process.check()?;
|
||||
for file in &mut self.files {
|
||||
file.check()?;
|
||||
let result = (|| {
|
||||
self.own_process.check()?;
|
||||
for file in &mut self.files {
|
||||
file.check()?;
|
||||
}
|
||||
let config = self.files.last_mut().context("TIME_NATIVE_CONFIG_HELD")?;
|
||||
ensure!(
|
||||
config.sha256()? == self.config_sha256,
|
||||
"TIME_NATIVE_CONFIG_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.invalidate_observed_context();
|
||||
}
|
||||
result
|
||||
}
|
||||
fn invalidate_observed_context(&mut self) {
|
||||
self.latest = None;
|
||||
self.pending = None;
|
||||
self.verifier.invalidate();
|
||||
// A positively observed protected-context failure is shared by
|
||||
// every object in this process, even if this object owns no nonce.
|
||||
// Restoring old bytes must not revive any older same-generation
|
||||
// evidence. Poisoned state already refuses all future access.
|
||||
if let Ok(mut state) = process().lock() {
|
||||
state.invalidate();
|
||||
}
|
||||
let config = self.files.last_mut().context("TIME_NATIVE_CONFIG_HELD")?;
|
||||
ensure!(
|
||||
config.sha256()? == self.config_sha256,
|
||||
"TIME_NATIVE_CONFIG_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn begin(&mut self, connection_generation: u64) -> Result<Request> {
|
||||
if connection_generation != self.connection_generation {
|
||||
@@ -675,9 +710,9 @@ mod installed {
|
||||
let signed: SignedAttestation = serde_json::from_slice(bytes)?;
|
||||
self.recheck()?;
|
||||
let mut checked = None;
|
||||
let interval =
|
||||
let (evidence, interval) =
|
||||
self.verifier
|
||||
.finish(pending.challenge, &signed, received, || {
|
||||
.finish_evidence(pending.challenge, &signed, received, || {
|
||||
let (sample, epoch) = observed(self.boot_id, self.base_error_ns)?;
|
||||
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
|
||||
checked = Some(sample);
|
||||
@@ -688,6 +723,10 @@ mod installed {
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
|
||||
state.require_owner(pending.owner, pending.epoch)?;
|
||||
state.active = None;
|
||||
self.latest = Some(HeldEvidence {
|
||||
evidence,
|
||||
epoch: pending.epoch,
|
||||
});
|
||||
let comparison = Comparison {
|
||||
interval,
|
||||
wall_utc_ns: checked.context("TIME_NATIVE_FINAL_SAMPLE")?.wall_utc_ns,
|
||||
@@ -696,6 +735,7 @@ mod installed {
|
||||
consume(&comparison)
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.latest = None;
|
||||
self.verifier.invalidate();
|
||||
if let Ok(mut state) = process().lock()
|
||||
&& state.active == Some(pending.owner)
|
||||
@@ -705,13 +745,64 @@ mod installed {
|
||||
}
|
||||
result
|
||||
}
|
||||
/// No IO/IPC callback, reply, caller timestamp or ready flag is needed
|
||||
/// for reads. Only a freshly recaptured own wall observation, bounded
|
||||
/// by the original finite evidence, is exposed inside this callback.
|
||||
pub fn with_current_comparison<T>(
|
||||
&mut self,
|
||||
consume: impl FnOnce(&Comparison) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
// A first/next refresh may be pending. Absence/ordinary expiry of
|
||||
// the old evidence must not consume that independent new nonce.
|
||||
let epoch = self
|
||||
.latest
|
||||
.as_ref()
|
||||
.context("TIME_NATIVE_NO_EVIDENCE")?
|
||||
.epoch;
|
||||
let checked = (|| {
|
||||
self.recheck()?;
|
||||
let (sample, current_epoch) = observed(self.boot_id, self.base_error_ns)?;
|
||||
ensure!(epoch == current_epoch, "TIME_NATIVE_EVIDENCE_INVALIDATED");
|
||||
let state = process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
|
||||
state.require_epoch(epoch)?;
|
||||
state.require_connection(self.connection_generation)?;
|
||||
Ok(sample)
|
||||
})();
|
||||
let checked = match checked {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
self.close();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let evidence = &self
|
||||
.latest
|
||||
.as_ref()
|
||||
.context("TIME_NATIVE_NO_EVIDENCE")?
|
||||
.evidence;
|
||||
let interval = match self.verifier.check_evidence(evidence, checked) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
self.latest = None;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
consume(&Comparison {
|
||||
interval,
|
||||
wall_utc_ns: checked.wall_utc_ns,
|
||||
})
|
||||
}
|
||||
pub fn close(&mut self) {
|
||||
self.verifier.invalidate();
|
||||
if let Some(pending) = self.pending.take()
|
||||
&& let Ok(mut state) = process().lock()
|
||||
&& state.active == Some(pending.owner)
|
||||
{
|
||||
state.invalidate();
|
||||
let evidence_epoch = self.latest.take().map(|value| value.epoch);
|
||||
let pending = self.pending.take();
|
||||
if let Ok(mut state) = process().lock() {
|
||||
let owns_pending = pending.is_some_and(|value| state.active == Some(value.owner));
|
||||
if owns_pending || evidence_epoch == Some(state.epoch) {
|
||||
state.invalidate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -721,7 +812,7 @@ mod installed {
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed only inside the completion callback, never returned as a
|
||||
/// Borrowed only inside a completion/current-comparison callback, never returned as a
|
||||
/// storable clock/lease/permit. Runtime callers must retain all job gates.
|
||||
pub struct Comparison {
|
||||
interval: Interval,
|
||||
@@ -836,25 +927,49 @@ mod tests {
|
||||
let mut state = Continuity::default();
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
state.accept_connection(3).unwrap();
|
||||
let before_rollback = state.epoch;
|
||||
assert!(state.accept_configuration(3, "old-config").is_err());
|
||||
assert!(state.accept_configuration(4, "different-config").is_err());
|
||||
assert!(state.require_epoch(before_rollback).is_err());
|
||||
assert_eq!(state.configuration, Some((4, "one-config".into())));
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
let before_fork = state.epoch;
|
||||
assert!(state.accept_configuration(4, "different-config").is_err());
|
||||
assert!(state.require_epoch(before_fork).is_err());
|
||||
assert_eq!(state.configuration, Some((4, "one-config".into())));
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
assert!(state.require_epoch(before_rollback).is_err());
|
||||
assert!(state.require_epoch(before_fork).is_err());
|
||||
|
||||
state.observe(boot, sample(0)).unwrap();
|
||||
let first_clock_evidence = state.epoch;
|
||||
let other_clock_evidence = state.epoch;
|
||||
// recheck's observed-context failure fences the entire process even
|
||||
// when no object currently owns a pending nonce. Same-generation
|
||||
// restoration does not erase the observed failure or heal old proof.
|
||||
state.invalidate();
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
assert!(state.require_epoch(first_clock_evidence).is_err());
|
||||
assert!(state.require_epoch(other_clock_evidence).is_err());
|
||||
let original_epoch = state.reserve(owner).unwrap();
|
||||
assert!(original_epoch > first_clock_evidence);
|
||||
// An outstanding refresh owns a nonce, not the older finite evidence.
|
||||
state.require_epoch(original_epoch).unwrap();
|
||||
assert!(state.reserve(Uuid::new_v4()).is_err());
|
||||
let mut resumed = sample(2_000_000_000);
|
||||
resumed.unbiased_ns = 9_000_000_000;
|
||||
assert!(state.observe(boot, resumed).is_err());
|
||||
assert!(state.require_owner(owner, original_epoch).is_err());
|
||||
assert!(state.require_epoch(original_epoch).is_err());
|
||||
// A caller reconstructing its verifier still sees this retained state.
|
||||
state.observe(boot, resumed).unwrap();
|
||||
let next = Uuid::new_v4();
|
||||
let epoch = state.reserve(next).unwrap();
|
||||
assert!(epoch > original_epoch);
|
||||
state.require_owner(next, epoch).unwrap();
|
||||
state.require_epoch(epoch).unwrap();
|
||||
state.accept_connection(4).unwrap();
|
||||
assert!(state.require_owner(next, epoch).is_err());
|
||||
assert!(state.require_epoch(epoch).is_err());
|
||||
assert!(state.require_connection(3).is_err());
|
||||
assert!(state.accept_connection(3).is_err());
|
||||
state.require_connection(4).unwrap();
|
||||
@@ -863,6 +978,7 @@ mod tests {
|
||||
state.epoch = u64::MAX;
|
||||
state.invalidate();
|
||||
assert!(state.exhausted);
|
||||
assert!(state.require_epoch(state.epoch).is_err());
|
||||
state.invalidate();
|
||||
assert!(state.exhausted);
|
||||
assert!(state.reserve(Uuid::new_v4()).is_err());
|
||||
|
||||
@@ -218,6 +218,17 @@ impl Challenge {
|
||||
&self.request
|
||||
}
|
||||
}
|
||||
/// One verified response held only by its original verifier. Neither a lease
|
||||
/// nor a transferable clock/permit: every use needs a fresh own observation.
|
||||
/// There is no public constructor, Clone, serialization, or timestamp getter.
|
||||
pub struct VerifiedEvidence {
|
||||
payload: Payload,
|
||||
begin: Sample,
|
||||
received: Sample,
|
||||
epoch: u64,
|
||||
verifier_id: Uuid,
|
||||
context: Context,
|
||||
}
|
||||
/// Lives with the verifier process; callers must not reconstruct it to clear a
|
||||
/// discontinuity. Native adapters additionally preserve the process-wide fence.
|
||||
pub struct Verifier {
|
||||
@@ -301,6 +312,18 @@ impl Verifier {
|
||||
received: Sample,
|
||||
capture_checked: impl FnOnce() -> Result<Sample>,
|
||||
) -> Result<Interval> {
|
||||
// Preserve the original completion API and its exact final native
|
||||
// capture; no second signature verification or invented current time.
|
||||
let (_, interval) = self.finish_evidence(challenge, signed, received, capture_checked)?;
|
||||
Ok(interval)
|
||||
}
|
||||
pub fn finish_evidence(
|
||||
&mut self,
|
||||
challenge: Challenge,
|
||||
signed: &SignedAttestation,
|
||||
received: Sample,
|
||||
capture_checked: impl FnOnce() -> Result<Sample>,
|
||||
) -> Result<(VerifiedEvidence, Interval)> {
|
||||
let owned = challenge.verifier_id == self.verifier_id
|
||||
&& self.pending_nonce.as_deref() == Some(challenge.request.nonce.as_str())
|
||||
&& challenge.epoch == self.epoch
|
||||
@@ -333,23 +356,54 @@ impl Verifier {
|
||||
key.verify_strict(&message, &signature)?;
|
||||
let checked = capture_checked()?;
|
||||
self.observe(checked)?;
|
||||
let evidence = VerifiedEvidence {
|
||||
payload: p,
|
||||
begin: challenge.begin,
|
||||
received,
|
||||
epoch: challenge.epoch,
|
||||
verifier_id: challenge.verifier_id,
|
||||
context: challenge.request.context,
|
||||
};
|
||||
let interval = self.evidence_interval(&evidence, checked)?;
|
||||
Ok((evidence, interval))
|
||||
}
|
||||
/// Re-evaluate the original finite evidence with a fresh observation from
|
||||
/// this verifier's native adapter. Pending refresh challenges do not alter
|
||||
/// evidence authority; invalidation/expiry never renews its original time.
|
||||
pub fn check_evidence(
|
||||
&mut self,
|
||||
evidence: &VerifiedEvidence,
|
||||
current: Sample,
|
||||
) -> Result<Interval> {
|
||||
ensure!(
|
||||
self.epoch > 0
|
||||
&& evidence.verifier_id == self.verifier_id
|
||||
&& evidence.epoch == self.epoch
|
||||
&& evidence.context == self.context,
|
||||
"TIME_EVIDENCE_NOT_OWNED"
|
||||
);
|
||||
self.observe(current)?;
|
||||
self.evidence_interval(evidence, current)
|
||||
}
|
||||
fn evidence_interval(&self, evidence: &VerifiedEvidence, checked: Sample) -> Result<Interval> {
|
||||
let p = &evidence.payload;
|
||||
let elapsed = checked
|
||||
.interrupt_ns
|
||||
.checked_sub(challenge.begin.interrupt_ns)
|
||||
.checked_sub(evidence.begin.interrupt_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?;
|
||||
let age = checked
|
||||
.interrupt_ns
|
||||
.checked_sub(received.interrupt_ns)
|
||||
.checked_sub(evidence.received.interrupt_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?;
|
||||
ensure!(
|
||||
elapsed <= MAX_RTT_NS && age <= MAX_RECEIVED_AGE_NS,
|
||||
"TIME_STALE_RESPONSE"
|
||||
);
|
||||
// Include every local capture budget conservatively, never RTT/2.
|
||||
let delta = challenge
|
||||
let delta = evidence
|
||||
.begin
|
||||
.capture_error_ns
|
||||
.checked_add(received.capture_error_ns)
|
||||
.checked_add(evidence.received.capture_error_ns)
|
||||
.and_then(|d| d.checked_add(checked.capture_error_ns))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_ERROR_OVERFLOW"))?;
|
||||
ensure!(delta <= MAX_CAPTURE_ERROR_NS, "TIME_CAPTURE_BUDGET");
|
||||
@@ -552,4 +606,71 @@ mod tests {
|
||||
let signed = sign(&p, &key).unwrap();
|
||||
assert!(v.finish(c, &signed, resumed, || Ok(resumed)).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn held_evidence_expires_without_renewal_and_preserves_pending_refresh() {
|
||||
let (mut v, key, server) = fixture(context(Role::SystemHelper));
|
||||
let c = v.begin(sample(0)).unwrap();
|
||||
let mut signed = reply(&c, &key, server);
|
||||
let (evidence, initial) = v
|
||||
.finish_evidence(c, &signed, sample(70_000_000), || Ok(sample(80_000_000)))
|
||||
.unwrap();
|
||||
// Evidence owns verified facts, not an aliased response or a stored
|
||||
// signature to parse/verify again at each subsequent clock read.
|
||||
signed.payload.clear();
|
||||
signed.signature_hex.clear();
|
||||
let next = v.begin(sample(100_000_000)).unwrap();
|
||||
let next_reply = reply(&next, &key, server);
|
||||
let later = v.check_evidence(&evidence, sample(110_000_000)).unwrap();
|
||||
assert!(later.upper_utc_ns() > initial.upper_utc_ns());
|
||||
assert!(v.check_evidence(&evidence, sample(170_000_000)).is_ok());
|
||||
assert!(v.check_evidence(&evidence, sample(171_000_000)).is_err());
|
||||
assert_eq!(
|
||||
v.pending_nonce.as_deref(),
|
||||
Some(next.request().nonce.as_str())
|
||||
);
|
||||
let (fresh, _) = v
|
||||
.finish_evidence(next, &next_reply, sample(180_000_000), || {
|
||||
Ok(sample(190_000_000))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(v.check_evidence(&fresh, sample(200_000_000)).is_ok());
|
||||
assert!(v.check_evidence(&evidence, sample(201_000_000)).is_err());
|
||||
|
||||
// The one-second bound starts at the original challenge, even when
|
||||
// the complete response itself was received less than100ms ago.
|
||||
let c = v.begin(sample(300_000_000)).unwrap();
|
||||
let signed = reply(&c, &key, server);
|
||||
let (evidence, _) = v
|
||||
.finish_evidence(c, &signed, sample(1_240_000_000), || {
|
||||
Ok(sample(1_250_000_000))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(v.check_evidence(&evidence, sample(1_300_000_000)).is_ok());
|
||||
assert!(v.check_evidence(&evidence, sample(1_300_000_001)).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn held_evidence_cannot_cross_verifier_epoch_or_discontinuity() {
|
||||
let ctx = context(Role::Agent);
|
||||
let (mut a, key, server) = fixture(ctx.clone());
|
||||
let c = a.begin(sample(0)).unwrap();
|
||||
let signed = reply(&c, &key, server);
|
||||
let (evidence, _) = a
|
||||
.finish_evidence(c, &signed, sample(70_000_000), || Ok(sample(80_000_000)))
|
||||
.unwrap();
|
||||
let (mut other, _, _) = fixture(ctx);
|
||||
assert!(other.check_evidence(&evidence, sample(90_000_000)).is_err());
|
||||
assert!(a.check_evidence(&evidence, sample(90_000_000)).is_ok());
|
||||
a.invalidate();
|
||||
assert!(a.check_evidence(&evidence, sample(100_000_000)).is_err());
|
||||
|
||||
let c = a.begin(sample(110_000_000)).unwrap();
|
||||
let signed = reply(&c, &key, server);
|
||||
let (evidence, _) = a
|
||||
.finish_evidence(c, &signed, sample(120_000_000), || Ok(sample(130_000_000)))
|
||||
.unwrap();
|
||||
let mut backwards = sample(140_000_000);
|
||||
backwards.unbiased_ns = 1;
|
||||
assert!(a.check_evidence(&evidence, backwards).is_err());
|
||||
assert!(a.check_evidence(&evidence, sample(150_000_000)).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,9 +53,13 @@ fn main() {
|
||||
'''
|
||||
|
||||
|
||||
class OperatorDenied(RuntimeError):
|
||||
"""Only explicit operator guards may produce a public failure reason."""
|
||||
|
||||
|
||||
def require(ok, reason):
|
||||
if not ok:
|
||||
raise RuntimeError(reason)
|
||||
raise OperatorDenied(reason)
|
||||
|
||||
|
||||
def digest(raw):
|
||||
@@ -103,7 +107,7 @@ def run(args, timeout=15, limit=1024 * 1024):
|
||||
result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=timeout, check=False)
|
||||
require(len(result.stdout) <= limit and len(result.stderr) <= limit, 'bounded command output')
|
||||
require(result.returncode == 0, 'fixed command failed: ' + args[0])
|
||||
require(result.returncode == 0, 'fixed command failed')
|
||||
return result.stdout
|
||||
|
||||
|
||||
@@ -341,50 +345,218 @@ def runtime_witness():
|
||||
return result
|
||||
|
||||
|
||||
def fd_metadata(fd):
|
||||
item = os.fstat(fd)
|
||||
return {key: getattr(item, 'st_' + key) for key in
|
||||
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns')}
|
||||
|
||||
|
||||
def held_bytes(fd, limit):
|
||||
before = fd_metadata(fd)
|
||||
require(stat.S_ISREG(before['mode']) and before['size'] <= limit, 'bounded held regular input')
|
||||
raw = os.pread(fd, limit + 1, 0)
|
||||
require(len(raw) <= limit and fd_metadata(fd) == before, 'stable held input')
|
||||
return raw
|
||||
|
||||
|
||||
def chrony_unit():
|
||||
fields = ('MainPID', 'ControlPID', 'ActiveState', 'SubState', 'Type', 'ControlGroup', 'InvocationID', 'Job')
|
||||
raw = run(['systemctl', 'show', '--all', '--property=' + ','.join(fields), '--', 'chrony.service'], limit=4096)
|
||||
values = {}
|
||||
for line in raw.decode('ascii').splitlines():
|
||||
key, separator, value = line.partition('=')
|
||||
require(separator and key in fields and key not in values, 'complete fixed Chrony unit properties')
|
||||
values[key] = value
|
||||
require(set(values) == set(fields) and values['MainPID'].isdigit() and int(values['MainPID']) > 1 and
|
||||
values['ControlPID'] == '0' and values['ActiveState'] == 'active' and values['SubState'] == 'running' and
|
||||
values['Type'] == 'notify' and values['ControlGroup'] == '/system.slice/chrony.service' and
|
||||
re.fullmatch('[0-9a-f]{32}', values['InvocationID']) and int(values['InvocationID'], 16) > 0 and
|
||||
not values['Job'], 'actual fixed active notify Chrony service')
|
||||
return values
|
||||
|
||||
|
||||
def named_matches(path, held):
|
||||
named = metadata(path)
|
||||
return all(held.get(key) == value for key, value in named.items())
|
||||
|
||||
|
||||
def cgroup_members(path):
|
||||
raw = regular(path / 'cgroup.procs', 256)
|
||||
require(re.fullmatch(rb'(?:[1-9][0-9]*\n){3}', raw) is not None, 'exact three Chrony cgroup processes')
|
||||
members = sorted(int(value) for value in raw.splitlines())
|
||||
require(len(set(members)) == 3 and all(value > 1 for value in members), 'unique Chrony cgroup processes')
|
||||
# No silently ignored descendant cgroup can hide additional service members.
|
||||
with os.scandir(path) as entries:
|
||||
require(not any(entry.is_dir(follow_symlinks=False) for entry in entries),
|
||||
'no descendant Chrony cgroup')
|
||||
return members
|
||||
|
||||
|
||||
class ChronyProcess:
|
||||
def __init__(self, pid):
|
||||
self.pid, self.fds = pid, []
|
||||
try:
|
||||
self.pidfd = os.pidfd_open(pid)
|
||||
self.fds.append(self.pidfd)
|
||||
self.proc = Path('/proc') / str(pid)
|
||||
self.procfd = os.open(self.proc, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
self.fds.append(self.procfd)
|
||||
# The fixed proc exe magic link is followed once, then held and
|
||||
# compared with the current executable before and after hashing.
|
||||
self.image = os.open('exe', os.O_RDONLY | os.O_CLOEXEC, dir_fd=self.procfd)
|
||||
self.fds.append(self.image)
|
||||
self.original = self.observe()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
for fd in reversed(self.fds):
|
||||
os.close(fd)
|
||||
self.fds = []
|
||||
|
||||
def observe(self):
|
||||
poll = __import__('select').poll()
|
||||
poll.register(self.pidfd, __import__('select').POLLIN)
|
||||
require(not poll.poll(0), 'held Chrony process alive')
|
||||
status = regular(self.proc / 'status', 65536).decode('ascii')
|
||||
ids = {}
|
||||
for label in ('Uid', 'Gid'):
|
||||
match = re.search('^' + label + r':\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$', status, re.MULTILINE)
|
||||
require(match and len(set(match.groups())) == 1, 'fixed real effective process IDs')
|
||||
ids[label.lower()] = int(match[1])
|
||||
first = regular(self.proc / 'stat', 8192).decode('ascii').rsplit(')', 1)[1].split()
|
||||
require(len(first) >= 20 and first[19].isdigit() and first[1].isdigit(), 'process birth and parent')
|
||||
require(regular(self.proc / 'cgroup', 4096) == b'0::/system.slice/chrony.service\n',
|
||||
'actual unified Chrony cgroup membership')
|
||||
image = fd_metadata(self.image)
|
||||
current = os.stat('exe', dir_fd=self.procfd)
|
||||
require(stat.S_ISREG(image['mode']) and image['uid'] == 0 and image['mode'] & 0o022 == 0 and
|
||||
(current.st_dev, current.st_ino) == (image['dev'], image['ino']), 'held protected actual process image')
|
||||
image_hash = digest(held_bytes(self.image, 16 * 1024 * 1024))
|
||||
after = os.stat('exe', dir_fd=self.procfd)
|
||||
require((after.st_dev, after.st_ino) == (image['dev'], image['ino']) and
|
||||
fd_metadata(self.image) == image and regular(self.proc / 'stat', 8192).decode('ascii').rsplit(')', 1)[1].split()[19] == first[19]
|
||||
and not poll.poll(0), 'actual process image and birth unchanged')
|
||||
return {'pid': self.pid, 'birth_ticks': int(first[19]), 'parent_pid': int(first[1]),
|
||||
'uid': ids['uid'], 'gid': ids['gid'], 'image': image, 'image_sha256': image_hash}
|
||||
|
||||
def socket_fds(self, inode):
|
||||
fd = os.open('fd', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=self.procfd)
|
||||
try:
|
||||
names = os.listdir(fd)
|
||||
require(len(names) <= 128 and all(value.isdigit() for value in names), 'bounded process descriptor set')
|
||||
return sorted(int(value) for value in names if os.readlink(value, dir_fd=fd) == 'socket:[' + str(inode) + ']')
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def command_socket_inode():
|
||||
raw = regular(Path('/proc/net/unix'), 1024 * 1024)
|
||||
rows = [line.split() for line in raw.decode('ascii').splitlines()[1:]]
|
||||
matches = [row for row in rows if len(row) == 8 and row[7] == '/run/chrony/chronyd.sock']
|
||||
require(len(matches) == 1 and matches[0][4] == '0002' and matches[0][6].isdigit(),
|
||||
'unique fixed Unix datagram command socket')
|
||||
return int(matches[0][6])
|
||||
|
||||
|
||||
def chrony_observation():
|
||||
unit = chrony_unit()
|
||||
cgroup = Path('/sys/fs/cgroup/system.slice/chrony.service')
|
||||
protected_dir(cgroup)
|
||||
group_identity = metadata(cgroup)
|
||||
members = cgroup_members(cgroup)
|
||||
processes = []
|
||||
pidfile = directory = -1
|
||||
try:
|
||||
for pid in members:
|
||||
processes.append(ChronyProcess(pid))
|
||||
main = int(unit['MainPID'])
|
||||
by_pid = {process.pid: process for process in processes}
|
||||
require(main in by_pid, 'unit wrapper belongs to actual service cgroup')
|
||||
# /run/chrony is daemon-owned: a root-owned pidfile alone is NOT
|
||||
# sufficient namespace authority. Bind the actual command-socket FD too.
|
||||
protected_dir(Path('/run'))
|
||||
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,
|
||||
'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)
|
||||
require(pid_identity['uid'] == 0 and pid_identity['gid'] == 0 and pid_identity['nlink'] == 1 and
|
||||
stat.S_IMODE(pid_identity['mode']) == 0o644, 'root single link fixed Chrony pidfile')
|
||||
pid_raw = held_bytes(pidfile, 32)
|
||||
require(re.fullmatch(rb'[1-9][0-9]*\n', pid_raw) is not None, 'canonical actual Chrony pidfile PID')
|
||||
daemon = int(pid_raw.strip())
|
||||
require(daemon in by_pid and daemon != main, 'pidfile daemon belongs to service cgroup')
|
||||
child = next(pid for pid in members if pid not in (main, daemon))
|
||||
wrapper, actual, helper = (by_pid[pid].original for pid in (main, daemon, child))
|
||||
require(wrapper['uid'] == wrapper['gid'] == 0 and actual['uid'] == actual['gid'] == 989 and
|
||||
helper['uid'] == helper['gid'] == 989 and actual['parent_pid'] == main and helper['parent_pid'] == daemon,
|
||||
'actual fixed wrapper daemon child identity chain')
|
||||
fixed_images = {}
|
||||
for role, path, observed in (('wrapper', '/usr/bin/dash', wrapper), ('daemon', '/usr/sbin/chronyd', actual)):
|
||||
protected_dir(Path(path).parent)
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
fixed = fd_metadata(fd)
|
||||
require(fixed == observed['image'] and digest(held_bytes(fd, 16 * 1024 * 1024)) == observed['image_sha256']
|
||||
and named_matches(Path(path), fixed),
|
||||
'actual process equals protected fixed executable')
|
||||
fixed_images[role] = fixed
|
||||
finally:
|
||||
os.close(fd)
|
||||
require(helper['image'] == actual['image'] and helper['image_sha256'] == actual['image_sha256'],
|
||||
'actual Chrony child shares protected daemon image')
|
||||
socket_path = Path('/run/chrony/chronyd.sock')
|
||||
socket_identity = metadata(socket_path)
|
||||
require(stat.S_ISSOCK(socket_identity['mode']) and socket_identity['uid'] == socket_identity['gid'] == 989 and
|
||||
stat.S_IMODE(socket_identity['mode']) == 0o755, 'actual fixed Chrony filesystem socket')
|
||||
inode = command_socket_inode()
|
||||
holders = {process.pid: process.socket_fds(inode) for process in processes}
|
||||
require(bool(holders[daemon]) and all(not fds for pid, fds in holders.items() if pid != daemon),
|
||||
'unique actual service command socket holder')
|
||||
for process in processes:
|
||||
require(process.observe() == process.original, 'service process tuple unchanged')
|
||||
require(chrony_unit() == unit and cgroup_members(cgroup) == members and metadata(cgroup) == group_identity and
|
||||
fd_metadata(directory) == dir_identity and named_matches(Path('/run/chrony'), dir_identity) and
|
||||
held_bytes(pidfile, 32) == pid_raw and fd_metadata(pidfile) == pid_identity and
|
||||
named_matches(Path('/run/chrony/chronyd.pid'), pid_identity) and
|
||||
metadata(socket_path) == socket_identity and command_socket_inode() == inode and
|
||||
named_matches(Path('/usr/bin/dash'), fixed_images['wrapper']) and
|
||||
named_matches(Path('/usr/sbin/chronyd'), fixed_images['daemon']) and
|
||||
{process.pid: process.socket_fds(inode) for process in processes} == holders,
|
||||
'Chrony unit namespace process pidfile and socket unchanged')
|
||||
return {'pin': {'schema_version': 1, 'daemon_pid': daemon, 'daemon_birth_ticks': actual['birth_ticks'],
|
||||
'daemon_uid': actual['uid'], 'daemon_gid': actual['gid'], 'daemon_image_sha256': actual['image_sha256']},
|
||||
'unit': unit, 'processes': [process.original for process in processes],
|
||||
'cgroup_metadata': group_identity, 'pidfile_metadata': pid_identity, 'pidfile_sha256': digest(pid_raw),
|
||||
'directory_metadata': dir_identity, 'socket_metadata': socket_identity,
|
||||
'socket_kernel_inode': inode, 'service_socket_fds': holders, 'fixed_images': fixed_images}
|
||||
finally:
|
||||
if pidfile >= 0:
|
||||
os.close(pidfile)
|
||||
if directory >= 0:
|
||||
os.close(directory)
|
||||
for process in processes:
|
||||
process.close()
|
||||
|
||||
|
||||
def preflight():
|
||||
engine = run(['docker', 'version', '--format', '{{json .Server.Version}}']).decode().strip()
|
||||
image_values = json.loads(run(['docker', 'image', 'inspect', '--format',
|
||||
'[{{json .Id}},{{json .Architecture}},{{json .Os}}]', BUILDER]))
|
||||
image = dict(zip(('Id', 'Architecture', 'Os'), image_values, strict=True))
|
||||
# Inspect only public immutable image metadata, never Config/Env.
|
||||
require(image['Architecture'] == 'arm64' and image['Os'] == 'linux', 'cached ARM64 builder required')
|
||||
pid = int(run(['systemctl', 'show', 'chrony.service', '--property=MainPID', '--value']).strip())
|
||||
require(pid > 1, 'existing Chrony service PID')
|
||||
proc = Path('/proc') / str(pid)
|
||||
pidfd = os.pidfd_open(pid)
|
||||
try:
|
||||
status = regular(proc / 'status', 65536).decode()
|
||||
ids = {}
|
||||
for label in ('Uid', 'Gid'):
|
||||
match = re.search('^' + label + r':\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$', status, re.MULTILINE)
|
||||
require(match and len(set(match.groups())) == 1, 'fixed real/effective daemon IDs')
|
||||
ids[label.lower()] = int(match[1])
|
||||
birth = regular(proc / 'stat', 8192).decode().rsplit(')', 1)[1].split()[19]
|
||||
image_path = Path('/usr/sbin/chronyd')
|
||||
fixed = metadata(image_path)
|
||||
require(stat.S_ISREG(fixed['mode']) and fixed['uid'] == 0 and fixed['mode'] & 0o022 == 0,
|
||||
'protected Chrony executable')
|
||||
require(os.stat(proc / 'exe').st_ino == fixed['ino'] and os.stat(proc / 'exe').st_dev == fixed['dev'],
|
||||
'actual daemon fixed executable inode')
|
||||
image_hash = digest(regular(image_path))
|
||||
require(metadata(image_path) == fixed and
|
||||
regular(proc / 'stat', 8192).decode().rsplit(')', 1)[1].split()[19] == birth and
|
||||
int(run(['systemctl', 'show', 'chrony.service', '--property=MainPID', '--value']).strip()) == pid,
|
||||
'Chrony identity unchanged during probe')
|
||||
poll = __import__('select').poll()
|
||||
poll.register(pidfd, __import__('select').POLLIN)
|
||||
require(not poll.poll(0), 'Chrony process still alive')
|
||||
finally:
|
||||
os.close(pidfd)
|
||||
observed = chrony_observation()
|
||||
boot = regular(Path('/proc/sys/kernel/random/boot_id'), 128).decode().strip()
|
||||
require(str(uuid.UUID(boot)) == boot, 'kernel boot identity')
|
||||
return {'docker_engine_version': json.loads(engine),
|
||||
'builder': {key: image[key] for key in ('Id', 'Architecture', 'Os')},
|
||||
'runtime': runtime_witness(), 'boot_id': boot,
|
||||
'chrony_observation': {'schema_version': 1, 'daemon_pid': pid,
|
||||
'daemon_birth_ticks': int(birth), 'daemon_uid': ids['uid'], 'daemon_gid': ids['gid'],
|
||||
'daemon_image_sha256': image_hash},
|
||||
'chrony_image_metadata': fixed, 'pins_provisioned': False,
|
||||
'chrony_observation': observed['pin'], 'chrony_binding': observed,
|
||||
'chrony_image_metadata': observed['fixed_images']['daemon'], 'pins_provisioned': False,
|
||||
'quality_sampled': False, 'registry_cache_verified': False}
|
||||
|
||||
|
||||
@@ -637,8 +809,12 @@ def host(args):
|
||||
except Exception as error:
|
||||
# Fixed controlled messages only; never write exception repr, paths from secrets, nested errors or env.
|
||||
exclusive(phase / 'failure.json', encoded({'failed': True, 'exception_type': type(error).__name__,
|
||||
'failure_reason': str(error) if isinstance(error, OperatorDenied) else 'unexpected_operator_exception',
|
||||
'read_original_case_only': True}))
|
||||
raise
|
||||
print(json.dumps({'case': case.name, 'phase': name, 'failed': True,
|
||||
'failure_reason': str(error) if isinstance(error, OperatorDenied) else 'unexpected_operator_exception',
|
||||
'read_original_case_only': True}, sort_keys=True))
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -662,4 +838,10 @@ def main():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
# A failure writing the private receipt must not print nested exceptions.
|
||||
print(json.dumps({'failed': True, 'failure_reason': 'unexpected_operator_exception',
|
||||
'read_original_case_only': True}, sort_keys=True))
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Frozen six held-time-evidence contract units only; 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/windows-signed-clock/evidence-qualification-b245fc45-1f03-417d-9275-31f26a22451e'
|
||||
STATE = ROOT / 'devstate/time-attestation-evidence-linux'
|
||||
PROFILE = 'rmm.time-attestation.six-held-evidence-units.v1'
|
||||
RECEIPT_SHA = '4a3aad94ccf26e1b40fb08ef77d92bfd6cbe30d70827ce3af42b535c9744dd85'
|
||||
INPUTS_SHA = '60bab3aeaa3ff65f6046af73645c2bc6736ff946bb88d579622c24aa9ca4c6a5'
|
||||
BINARY_SHA = '0eb40face421325822887b2104fe82bd4050621e9c792e1b1d5751547e77208b'
|
||||
BINARY_BYTES = 1543576
|
||||
TESTS = sorted(['tests::discontinuity_invalidates_outstanding_and_requires_new_challenge', 'tests::foreign_reply_cannot_reenable_an_older_own_challenge', 'tests::held_evidence_cannot_cross_verifier_epoch_or_discontinuity', 'tests::held_evidence_expires_without_renewal_and_preserves_pending_refresh', 'tests::signed_roundtrip_uses_entire_rtt_and_strict_deadline_interval', 'tests::tampering_wrong_role_nonce_key_and_delays_never_open'])
|
||||
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) == 190 and source == value['source_files'], 'exact frozen 190 qualification 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-attestation-uri-tests-' + 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']) == 2058104, 'bounded binary transfer')
|
||||
raw = base64.b64decode(p['binary_b64'], validate=True)
|
||||
require(len(raw) == 1543576 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed six-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) == 6 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact six 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'6 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']), 'six native units and retained target state')
|
||||
receipt = dict(id=ident, profile=p['profile'], passed=6, 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) == 190
|
||||
and receipt['current_source_equals_frozen'] is True
|
||||
and receipt['local_checks']['codec_tests'] == '6PASS/0filtered'
|
||||
and receipt['legacy_job_gate_activation'] is False, 'reviewed six-codec-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 / 'time-evidence-tests'
|
||||
support.require(receipt['artifacts']['time-evidence-tests'] == dict(bytes=BINARY_BYTES, sha256=BINARY_SHA, complete_test_list=TESTS), '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,311 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Frozen one changed Windows context fence on Linux only; fourteen other cases filtered; 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/windows-signed-clock/config-fence-qualification-304d0520-9882-4ed4-b9e0-634996c07dc6'
|
||||
STATE = ROOT / 'devstate/windows-context-fence-native-linux'
|
||||
PROFILE = 'rmm.windows-clock.context-fence-linux-guard.v1'
|
||||
RECEIPT_SHA = 'f25dae5d8f9fea185a298014a087424c8b2207dfe15cfe86de38d0773fae9ef4'
|
||||
INPUTS_SHA = 'b0f317cb59aed20e2faa9cfeef38cc55fceb4bc00faac723bc9ab5bd8d60b87f'
|
||||
BINARY_SHA = 'b390ee90332671a68ab401e713691e3b4072db1ec83b2cff9a6e4dbbe524ec42'
|
||||
BINARY_BYTES = 4046032
|
||||
TESTS = sorted(['signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution'])
|
||||
ALL_TESTS = sorted(['event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits', 'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable', 'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata', 'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes', 'journal::tests::durable_reopen_ack_identity_and_single_process', 'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes', 'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data', 'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority', 'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry', 'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload', 'signed_clock::tests::bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters', 'signed_clock::tests::complete_raw_report_is_bounded_non_authoritative_and_keeps_actual_brackets', 'signed_clock::tests::job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case', 'signed_clock::tests::raw_capture_denies_backward_wall_counters_and_incomplete_or_expired_series', 'signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution'])
|
||||
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 <= 4 * 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['all_listed_tests'] == ALL_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) == 190 and source == value['source_files'], 'exact frozen 190 compiler 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 / 'windows-clock-guard-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-windows-raw-clock-guards-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']) == 5394712, 'bounded binary transfer')
|
||||
raw = base64.b64decode(p['binary_b64'], validate=True)
|
||||
require(len(raw) == 4046032 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed three-guard library binary')
|
||||
binary = folder / 'windows-clock-guard-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) == 15 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['all_listed_tests'], 'exact full fifteen-test list before one targeted fence')
|
||||
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
|
||||
code, stdout, stderr = run(command + ['signed_clock::tests::retained_process_fence_rejects_old_challenge_and_boot_substitution', '--exact', '--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'1 passed; 0 failed; 0 ignored; 0 measured; 14 filtered out' in stdout
|
||||
and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'one native context fence with fourteen filtered and retained target state')
|
||||
receipt = dict(id=ident, profile=p['profile'], passed=1, ignored=0, filtered=14, listed=15, 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) == 190
|
||||
and receipt['module_sha256'] == '9cc43960531a7fbd9899f88eeda4400c04a87a756a188c062bc1865fafd5bc50'
|
||||
and receipt['tests'] == 'local1PASS/14filtered; full15list verified'
|
||||
and receipt['runtime_gate_or_target_changes'] is False, 'reviewed changed context-fence 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 / 'windows-config-fence-tests'
|
||||
support.require(receipt['binary'] == dict(path='windows-config-fence-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA, complete_test_list=ALL_TESTS), 'fixed original linked artifact')
|
||||
copy_exact(binary, folder / 'windows-clock-guard-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, all_listed_tests=ALL_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, all_listed_tests=ALL_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 / 'windows-clock-guard-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()
|
||||
@@ -1,5 +1,18 @@
|
||||
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
|
||||
|
||||
**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
|
||||
Konstruktor-Fork/Rollback invalidieren prozessweit. [Belege](windows-signed-clock-evidence.md).
|
||||
Keine Windows-Kernel-/Zeitbereitschaft oder Jobfreigabe.
|
||||
|
||||
|
||||
**Kurzlebige Zeitevidenz Linux-first bestanden:** Originalfall44514778,
|
||||
sechs native Cloud-Linux-Vertragsprüfungen ohne Skip/Filter, separater Readback
|
||||
vollständig und bekannte Runtimezeugen erhalten. [Ergebnis](signed-time-contract-results.md).
|
||||
Keine Windows-Kernel-/Serverproviderqualifikation oder Jobgateaktivierung.
|
||||
|
||||
|
||||
**Native Zeitbootstrapversuche2026-11-15:** Windowsoriginalfall efd17b43
|
||||
baseline und AST/C# compile-only bestanden; Setup bei zweiter Messdienstanlage
|
||||
gescheitert. Eigener LocalService gestoppt, SYSTEM fehlt; Originalread samt
|
||||
|
||||
@@ -44,7 +44,7 @@ Archivhash separat. Ein neuer kanonischer UUIDv4-Fall liegt ausschließlich unte
|
||||
`/var/lib/rmm-time-source-bootstrap/<UUID>` mit Root0700; jede Phase erzeugt ein
|
||||
eigenes Verzeichnis, einen create-only Intent und anschließend ein Ergebnis.
|
||||
Vorhandene Verzeichnisse/Intents werden nie wiederverwendet. Nach verlorener
|
||||
Antwort ausschließlich `host-read --case <UUID>` benutzen, keine Wiederholung.
|
||||
Antwort ausschließlich `python3 -I operator.py host-read --case <UUID>` benutzen, keine Wiederholung.
|
||||
|
||||
1. Lokal: `python3 deploy/server_time_source_bootstrap.py prepare --commit
|
||||
2dfd791aa5703f42f0258d17bc9b5f6c9d71337f`. Das Ergebnis nennt den privaten
|
||||
@@ -101,10 +101,23 @@ und `10001:10001` verwenden. PostgreSQL darf keine publizierten Ports haben;
|
||||
sonstige publizierte Dockerports müssen ausschließlich IPv4-Loopback sein.
|
||||
Umgebungsvariablen, private Mountinhalte und Healthausgaben werden nicht gelesen.
|
||||
|
||||
Chrony wird über den vorhandenen `chrony.service`-MainPID identifiziert.
|
||||
PIDFD, Prozessgeburtszeit, reale/effective UID/GID, tatsächlicher Executableinode,
|
||||
geschütztes `/usr/sbin/chronyd` samt SHA256 und Boot-ID werden beobachtet und
|
||||
erneut verglichen. Dies ist eine begrenzte frische Beobachtung für spätere
|
||||
Der vorhandene `chrony.service` läuft hier als aktiver `Type=notify`-Dienst
|
||||
mit einem Root-`/usr/bin/dash`-Wrapper als MainPID. Der Preflight bindet die
|
||||
exakt drei tatsächlichen Prozesse seiner festen Cgroup
|
||||
`/system.slice/chrony.service`: Wrapper, dessen Chronyd-Kind und dessen weiteres
|
||||
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.
|
||||
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
|
||||
globale Abwesenheit fremder FD-Kopien. Gehaltene pidfds, Proc-/Image-FDs,
|
||||
Geburtszeiten, Elternbeziehungen, alle vier UID-/GID-Werte, Cgroupmitglieder,
|
||||
Unitgeneration, Originaldateimetadaten und Socket-/Pidfileidentitäten werden
|
||||
vorher/nachher verglichen. Unbekannte Topologien verweigern; kein Dienst wird
|
||||
neugestartet oder automatisch neu übernommen. Boot-ID wird ebenfalls beobachtet. Dies ist eine begrenzte frische Beobachtung für spätere
|
||||
Root-Pinprovisionierung, **keine** Sourcequalitätsabnahme. Der Provider prüft
|
||||
später seine vollständigen gehaltenen Identitäten selbst. Das historische
|
||||
Kernelresultat aus früheren Fällen ist kein frischer Qualitätsbeleg.
|
||||
@@ -267,3 +280,24 @@ Dieser Metadatenbefund ersetzt keinen erfolgreichen vollständigen Preflight
|
||||
oder ARM64-Build. Kein Chrony-/RMM-Neustart, kein Zeitsetter, Pin, Schlüssel,
|
||||
Broker oder Serverdeploy wurde vorgenommen. Der fehlgeschlagene Fall bleibt
|
||||
erhalten und wird nicht erneut ausgeführt.
|
||||
|
||||
|
||||
## Enger Preflightkorrekturstand, 2026-11-15
|
||||
|
||||
Der tatsächliche erste Server-Preflight des Falls
|
||||
`d3be954b-518b-4232-bac4-5bf0a8f934cd` verweigerte korrekt bei
|
||||
`actual daemon fixed executable inode`: Systemds MainPID war der legitime
|
||||
Dash-Wrapper, nicht Chronyd. Anschließende ausschließlich lesende Rootbefunde
|
||||
belegten die oben beschriebene Drei-Prozess-Topologie und den alleinigen
|
||||
Command-Sockethalter innerhalb dieser Dienst-Cgroup. Der alte Fehlerfall bleibt
|
||||
unverändert und darf nicht wiederholt werden. Die korrigierte Operatorquelle
|
||||
benötigt ein neues geprüftes Paket und einen neuen Fall; daraus folgt noch
|
||||
keine erfolgreiche ARM64-Ausführung oder Sourcequalitätsabnahme.
|
||||
|
||||
Hostbefehle müssen mit `python3 -I /absoluter/pfad/operator.py ...` gestartet
|
||||
werden: der Dateiname `operator.py` darf keine gleichnamigen Python-Standardmodule
|
||||
über den Skriptpfad überschatten. Kontrollierte Guardfehler werden als feste
|
||||
`failure_reason` in create-only `failure.json` und einer begrenzten JSON-Antwort
|
||||
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.
|
||||
|
||||
@@ -114,3 +114,36 @@ Keine reale Zeitqualifikation oder Windowsfähigkeit daraus ableiten. Die
|
||||
parallel hinzugefügte Linux-Providercrate ist separat lokal4/4 geprüft,
|
||||
noch nicht nativ abgefragt; ihr Code wird durch diesen Codecbeleg nicht
|
||||
mitqualifiziert. [Providerstand](server-time-source.md).
|
||||
|
||||
## Kurz gehaltene Evidenz: tatsächlich sechs Linux-VM-Prüfungen
|
||||
|
||||
2026-11-15: Originalfall `44514778-8617-4e60-a5da-46750f15ce51`
|
||||
führte auf der tatsächlichen Cloud-Linux-VM als UID0 alle sechs gelisteten
|
||||
Codecprüfungen aus:6 bestanden,0 fehlgeschlagen,0 ignoriert,0 gefiltert.
|
||||
Der separate Originalfall-Readback war vollständig und bestätigte die
|
||||
unveränderten bekannten Prozess-/Datei-/Dienstzeugen. Keine Dienststeuerung,
|
||||
Uhrstellung, RMM-Jobs, Grants oder Runtimeaktivierung.
|
||||
|
||||
Geprüfter Codec-SHA256
|
||||
`38009d0393c64d3c9b8db6154210e02cbf349d1a67b25ef2cc58c05f926b2346`;
|
||||
Operator `deploy/time_evidence_linux_acceptance.py`, SHA256
|
||||
`4234214fa72cccb47c41db856b2218708e9f23a9cfe3880ec6d87129705ef398`.
|
||||
Gefrorene Quellenqualification-Receipt
|
||||
`4a3aad94ccf26e1b40fb08ef77d92bfd6cbe30d70827ce3af42b535c9744dd85`,
|
||||
190-Inputmanifest
|
||||
`60bab3aeaa3ff65f6046af73645c2bc6736ff946bb88d579622c24aa9ca4c6a5`.
|
||||
Tatsächlich ausgeführtes ELF1543576Bytes, SHA256
|
||||
`0eb40face421325822887b2104fe82bd4050621e9c792e1b1d5751547e77208b`.
|
||||
|
||||
Die zwei hinzugekommenen Vertragsprüfungen belegen: gehaltene Evidenz
|
||||
verlängert ihre ursprünglichen Zeitgrenzen nicht, ihr Ablauf verbraucht nicht
|
||||
die bereits ausstehende neue Refreshnonce; Evidenz ist an Verifier, Epoche
|
||||
und beobachtete Kontinuität gebunden. Die vier bisherigen Signatur-/Nonce-/
|
||||
Intervallfehlerprüfungen liefen ebenfalls. Es handelt sich um native
|
||||
Vertragsfixtures, nicht um echte Windows-Kernelcaptures oder einen realen
|
||||
Chrony-/Broker-/mTLS-Roundtrip. Der getrennte Windowsadapter befindet sich
|
||||
noch in Quellenqualifikation; Windows-Jobs bleiben gesperrt.
|
||||
|
||||
Native Ausführungsreceipt-SHA256 `3df70a8451fdbde8e355d353fe1f0318e7707006830322d0caf400550fcaa72e`.
|
||||
|
||||
Separater Readback-SHA256 `7b95f6dff1b2aeb20c63e3c61b9594ee5eba88266dc118d7628eca4496d6cdc3`.
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# Kurze prozessgebundene Evidenz für native Clockleser
|
||||
|
||||
Dieser Schnitt erweitert ausschließlich den gemeinsamen Zeitcodec und den
|
||||
noch nicht angebundenen Windowsadapter. Er aktiviert keinen Legacyclock,
|
||||
Capability, Runtime-/Helper-IPC-Pfad oder Jobgate. Request, Payload, kanonische
|
||||
Wirebytes und Signaturdomäne bleiben unverändert; das eingefrorene Serverpaket
|
||||
des Quellencheckpoints `2dfd791` bleibt auf dem Draht kompatibel.
|
||||
|
||||
`Verifier::finish_evidence` konsumiert genau die eigene Challenge und prüft
|
||||
Nonce-/Kontext-/Keybindung und Signatur einmal. Erst danach erfolgt wie bisher
|
||||
das eigene finale Capture. Zurück kommen ein opakes `VerifiedEvidence` und
|
||||
das ursprüngliche sofortige `Interval`. Das bestehende `finish` delegiert
|
||||
dorthin und liefert unverändert nur dieses Intervall. Evidence besitzt keine
|
||||
öffentlichen Felder, keinen Konstruktor, Clone, Serialize/Deserialize oder
|
||||
Timestampgetter. Sie hält private verifizierte Payloadfakten, ursprüngliche
|
||||
Begin-/Receive-Samples sowie Verifier-ID, Epoche und Kontext; keine Signatur
|
||||
oder Antwortbytes für spätere erneute Signaturprüfung.
|
||||
|
||||
Jeder spätere `check_evidence` verlangt eine neue eigene native Beobachtung.
|
||||
Ownership/Epoche/Kontext und Kontinuität werden erneut geprüft. Die gesamte
|
||||
Zeit seit dem ursprünglichen Challengebeginn bleibt höchstens1s, seit dem
|
||||
ursprünglichen eigenen Empfang höchstens100ms. Begin-/Receive-/aktuelles
|
||||
Capturebudget zusammen höchstens50ms. Fehlerintervalle enthalten den gesamten
|
||||
vergangenen Zeitraum und Capturebudgets, niemals RTT/2. Quellalter samt diesen
|
||||
Zeiten bleibt höchstens1h; das gesamte neu errechnete UTC-Intervall muss
|
||||
innerhalb2s der tatsächlich selbst beobachteten Wallclock liegen. Ein Read
|
||||
erneuert keine Frist und ersetzt die Wallclock nicht durch einen Mittelpunkt.
|
||||
|
||||
Eine neue offene Challenge verändert diese Evidenzepoche nicht. Deshalb kann
|
||||
die vorherige Evidence während eines Refreshes bis zu ihren ursprünglichen
|
||||
Fristen weiter verwendet werden. Ihr gewöhnlicher Ablauf darf die nächste
|
||||
offene Nonce nicht konsumieren. Ein unabhängiger neuer erfolgreicher Vergleich
|
||||
ersetzt sie; eine verspätete alte Antwort wird dadurch nicht erneut gültig.
|
||||
Explizite Invalidierung, fremder Verifier, Diskontinuität oder wechselnder
|
||||
geschützter Kontext sperren die alte Evidence.
|
||||
|
||||
`SignedClock` hält die jüngste Evidence samt Prozess-Globalepoche ausschließlich
|
||||
privat. `complete` bewahrt seinen ursprünglichen Callback und dessen eigenes
|
||||
finales Sample/Initialintervall, versiegelt gleichzeitig die Evidence und
|
||||
erteilt keine zweite Wirkung bei doppelter Antwort. Der neue
|
||||
`with_current_comparison` liest nur den eigenen Prozess: Rolle/geschützte
|
||||
gehaltene Dateien und Konfigurationshash, echte Clockgetter, Boot-/Globalepoche
|
||||
und Connectionhead werden geprüft. Anschließend rechnet der eigene Verifier
|
||||
das Intervall erneut aus. Nur im Callback sind tatsächlich selbst beobachtetes
|
||||
UTC-W und frisches Intervall verfügbar. Kein Netzwerk-/Pipe-Rückruf aus diesem
|
||||
Getter, kein Agentbericht als Helperzeit, kein exportierter Clockready-Boolean.
|
||||
Fehlende Evidence oder normaler Ablauf sind kein Grund, einen laufenden neuen
|
||||
Refresh abzubrechen; ein nativer Identitäts-/Kontextfehler schließt den Kontext.
|
||||
|
||||
Die zwei neuen Codec-Guardsequenzen betreffen Originalfristen einschließlich
|
||||
101ms nach Empfang und mehr als1s seit Beginn, alte Evidence bei gleichzeitig
|
||||
offener nächster Challenge, erfolgreiche neue Evidence nach Ablauf der alten,
|
||||
getrennte Evidence-/Antwortdaten sowie falschen Verifier, neue Epoche und
|
||||
Diskontinuität. Der vorhandene Windows-Prozessfencetest prüft zusätzlich die
|
||||
Evidenceepoche während einer offenen Challenge und nach Invalidierung.
|
||||
|
||||
Lokale Build-/Testbelege dieses neuen Quellenstandes werden separat erfasst.
|
||||
Die alten nativen Codec-/Windows-Guard-/Rohcapturebelege qualifizieren diesen
|
||||
Deltaquellstand nicht nachträglich. Kein nativer Windowsvergleich, keine echte
|
||||
Rollen-/Timerkalibrierung oder neue Serverqualität wird aus lokalen Tests
|
||||
abgeleitet. Linux-first-Nachweis der neuen Guards, echte unabhängige Windows-
|
||||
Rollenproofs und spätere Runtime-/Deadlineintegration bleiben eigene offene
|
||||
MVP-Schritte. Geschützte Pins oder Baseerror werden hier nicht provisioniert.
|
||||
|
||||
## Tatsächlicher lokaler Nachweis, 2026-11-15
|
||||
|
||||
Privater neuer Fall
|
||||
`evidence-qualification-b245fc45-1f03-417d-9275-31f26a22451e`,190 eingefrorene
|
||||
Inputs, Manifest-SHA256
|
||||
`60bab3aeaa3ff65f6046af73645c2bc6736ff946bb88d579622c24aa9ca4c6a5`.
|
||||
Codecquelle SHA256
|
||||
`38009d0393c64d3c9b8db6154210e02cbf349d1a67b25ef2cc58c05f926b2346`,
|
||||
Windowsmodul SHA256
|
||||
`3a0b5985884f74b9ef910af5586fc62ba4d4194ef82483e23d7c220501f478ee`.
|
||||
|
||||
Tatsächlich ausschließlich lokal bestanden:
|
||||
|
||||
- Linux-Release-Link beider Libtestexes; Codec vollständig6 Tests,6PASS,
|
||||
einschließlich der4 bestehenden Completionregressionen und2 neuen Guards.
|
||||
- Windows-Linuxlib vollständig15 Namen geprüft; ausschließlich geänderten
|
||||
Prozessfencetest ausgeführt:1PASS,14 andere ausdrücklich gefiltert.
|
||||
- Codec-Alltargets-Clippy und Windows-GNU-Alltargets-Clippy mit
|
||||
`system-helper`, jeweils `-D warnings`, sowie Formatcheck beider Ownerdateien.
|
||||
|
||||
Die Linuxcodec-Testexe hat1543576Bytes/SHA256
|
||||
`0eb40face421325822887b2104fe82bd4050621e9c792e1b1d5751547e77208b`;
|
||||
die Windows-Linuxlib-Testexe4043056Bytes/SHA256
|
||||
`f5ee6564fff8abbc0e13eb043060e24bdaa474c6dbbddaffe5b2c3b911783cf4`.
|
||||
Dies sind vorbereitete Linux-first-Artefakte. Keine native Cloud-Linux-
|
||||
Ausführung, Windowsausführung oder Rollenqualifikation wurde durch diesen
|
||||
Worker in diesem Schritt durchgeführt. Die zuvor eingefrorenen Runner und
|
||||
der Serverquellenpack des Checkpoints2dfd791 bleiben bytegleich erhalten;
|
||||
sie werden nicht nachträglich auf diesen neuen Quellenstand umgedeutet.
|
||||
|
||||
## Nachtrag: beobachtete Kontextfehler fencen alle Objekte
|
||||
|
||||
Der unabhängige Review fand einen konkreten Wiederherstellungsfall: Ein Fehler
|
||||
von `begin` beim Nachprüfen geschützter Dateien gab zuvor lediglich `Err`
|
||||
zurück. Nach kurzfristiger Wiederherstellung des alten Kontexts konnte alte
|
||||
Evidence innerhalb ihrer Restfrist erneut verwendbar werden. Der zentrale
|
||||
private `recheck` fencet jetzt bei jedem tatsächlich beobachteten Rollen-/Image-/
|
||||
Datei-/Konfigurationsfehler die eigene Evidence, Pendingnonce und den eigenen
|
||||
Verifier sowie **unbedingt** die gemeinsame Prozess-Globalepoche. Dies gilt
|
||||
auch ohne eigenen Pendingowner und somit für alte Evidence anderer Objekte.
|
||||
`open`, `begin`, `complete` und `with_current_comparison` benutzen dieselbe
|
||||
Prüfung. Gleichgenerationige Wiederherstellung löscht diesen Befund nicht;
|
||||
erst ein frischer erfolgreicher Vergleich kann wieder neue Evidence liefern.
|
||||
|
||||
Gewöhnlicher Evidenzablauf löscht weiterhin ausschließlich die alte Evidence
|
||||
und bewahrt die nächste offene Refreshnonce. Normales `close`/Drop behält die
|
||||
bisherige konditionale Besitzer-/Epochprüfung und fencet nicht blind eine
|
||||
neuere andere Connection. Kein neuer Provisionszwang, kein Wire-/Codecwechsel.
|
||||
|
||||
Neuer eigener190-Input-Fall
|
||||
`context-fence-qualification-4d884851-d24b-42e6-82b2-956da3c6a980`,
|
||||
Inputmanifest SHA256
|
||||
`4363d357c01803f381939de28d287eaf323f2701f5e7064bb479833ccc0c0475`,
|
||||
Modul SHA256
|
||||
`7132b914de701a3ed5c35f265dbf7aa8bb4e0621dbc597eb3225165aa7231683`.
|
||||
Der gemeinsame Codec bleibt bytegleich bei SHA38009d0393c64d3c9b8db6154210e02cbf349d1a67b25ef2cc58c05f926b2346;
|
||||
die frühere6er-Codecprüfung wurde deshalb nicht unnötig wiederholt.
|
||||
|
||||
Tatsächlich lokal: Release-Testbinary gelinkt, vollständige15er-Liste geprüft,
|
||||
nur den geänderten Prozessfencetest ausgeführt:1PASS/14filtered. Die Statefolge
|
||||
prüft jetzt ausdrücklich zwei alte Objekt-Epochen nach einem beobachteten
|
||||
Kontextfehler ohne offene Nonce, deren Ablehnung nach SameGen-Restore sowie
|
||||
eine neue zulässige Challenge. Windows-GNU-Alltargets-Clippy mit system-helper/
|
||||
`-D warnings` und Modulformatcheck PASS. Testexe4043200Bytes/SHA256
|
||||
`89f17cc6ae861f12adb251676b6b5deec664b41979e655dbab79ef1dac19e69d`.
|
||||
Dies ist ein enger lokaler Delta-/Statemodellnachweis, kein nativer Windows-
|
||||
Dateirestore- oder Rollenversuch. Alte Receipts/Artefakte bleiben unverändert;
|
||||
ihre Dokumentfassung wurde als eigener historischer Beleg erhalten. Keine
|
||||
Zielaktion, neue Clockbereitschaft oder Jobwirkung wurde aktiviert.
|
||||
|
||||
## Nachtrag: Konstruktor erkennt Fork/Rollback ebenfalls prozessweit
|
||||
|
||||
Der weitere unabhängige Review fand denselben Restorefall vor dem abschließenden
|
||||
`recheck` eines neuen Objekts: `accept_configuration` verweigerte einen positiven
|
||||
Rollback-/SameGenfork-Befund, ließ dabei aber alte Objekt-Epochen bestehen.
|
||||
Jetzt invalidiert dieser konkrete Fehlerzweig die gemeinsame Epoche vor dem
|
||||
Fehlerreturn und übernimmt ausdrücklich keinen neuen Konfigurationshead.
|
||||
Wiederherstellung des bisherigen Heads heilt keine alte Evidence; eine frische
|
||||
postErrorChallenge ist weiterhin möglich. Die vorherige zentrale Recheck-
|
||||
Korrektur allein wurde deshalb nicht als vollständige Invariante übernommen.
|
||||
|
||||
Neuer190-Input-Fall
|
||||
`config-fence-qualification-304d0520-9882-4ed4-b9e0-634996c07dc6`, Manifest
|
||||
`b0f317cb59aed20e2faa9cfeef38cc55fceb4bc00faac723bc9ab5bd8d60b87f`,
|
||||
Modul SHA256
|
||||
`9cc43960531a7fbd9899f88eeda4400c04a87a756a188c062bc1865fafd5bc50`.
|
||||
Einzige geänderte Compilerquelle gegenüber dem vorigen190er-Fall ist das
|
||||
Windowsmodul; Codec/Wire bleiben bytegleich. Der bestehende Fencetest prüft
|
||||
Rollback und Fork, Ablehnung alter Epochen auch nach Restore sowie den
|
||||
unverändert gehaltenen echten Konfigurationshead. Lokal nach Release-Link und
|
||||
vollständiger15er-Liste:1PASS/14filtered; GNU-Alltargets-Clippy mit system-helper/
|
||||
`-D warnings` und Formatcheck PASS. Testexe4046032Bytes/SHA256
|
||||
`b390ee90332671a68ab401e713691e3b4072db1ec83b2cff9a6e4dbbe524ec42`.
|
||||
Der unabhängige enge Source-Re-review meldete für diesen Fehlerzweig PASS.
|
||||
Keine native Windows-Restore-Abnahme, kein Gate-/Runtimeanschluss und keine
|
||||
Zielaktion durch diesen Deltaquellstand. Alle bisherigen Fälle bleiben historisch.
|
||||
|
||||
## Tatsächlicher Linux-first-Nachweis des finalen Kontextfences
|
||||
|
||||
2026-11-15: Originalfall `1e179c84-041c-4c49-b730-3a688a495aec` auf
|
||||
der Cloud-Linux-VM. Vollständige15er-Testliste geprüft; ausschließlich der
|
||||
geänderte Prozessfencetest lief:1 bestanden,14 ausdrücklich gefiltert,
|
||||
0 ignoriert. Separater Originalfall-Rückabruf vollständig; bekannte
|
||||
RMM-Datei-/Prozess-/Dienstzeugen unverändert. Der Test prüft das native
|
||||
Statemodell, keine Windows-Dateiwiederherstellung oder Windows-Kerneluhr.
|
||||
|
||||
Operator `deploy/windows_context_fence_linux_acceptance.py`, SHA256
|
||||
`ec469733415f3cfe5804b507c4cb50911e6f2afdd93bc5bb19c6cbed1cedec4d`.
|
||||
Originale lokale Qualificationreceipt
|
||||
`f25dae5d8f9fea185a298014a087424c8b2207dfe15cfe86de38d0773fae9ef4`,
|
||||
190-Inputmanifest
|
||||
`b0f317cb59aed20e2faa9cfeef38cc55fceb4bc00faac723bc9ab5bd8d60b87f`.
|
||||
Genau deren Testartefakt4046032Bytes wurde ausgeführt, SHA256
|
||||
`b390ee90332671a68ab401e713691e3b4072db1ec83b2cff9a6e4dbbe524ec42`.
|
||||
Der Quellenreview bestätigte beide tatsächlichen Kontextfehlerpfade: zentralen
|
||||
Recheck und Konstruktor-Fork/Rollback, jeweils prozessweite Invalidierung.
|
||||
Die Codecquelle38009d bleibt bytegleich; ihre sechs Prüfungen liefen separat
|
||||
im [nativen Codecfall44514778](signed-time-contract-results.md).
|
||||
|
||||
Keine Windowszeitqualität, Calibration, Runtimeintegration oder Jobfreigabe
|
||||
wird daraus abgeleitet. Eigene gestoppte Windows-Messfixture aus dem partiellen
|
||||
Setup bleibt separat dokumentiert und wird nicht durch diesen Linuxlauf geheilt.
|
||||
|
||||
Ausführungsreceipt-SHA256 `683935f353110da72178b0da703a33dcd87e48fa3f7a9bec2340a90ce9bcba3c`.
|
||||
|
||||
Separater Rückabruf-SHA256 `0cb31b157ef4c0c55774280529bb27a634ffb945c875508d29896090ec144930`.
|
||||
Reference in New Issue
Block a user