Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6c4037d07 |
Generated
-2
@@ -2191,7 +2191,6 @@ dependencies = [
|
||||
"rmm-domain",
|
||||
"rmm-privileged-helper",
|
||||
"rmm-protocol",
|
||||
"rmm-updater",
|
||||
"rmm-updater-handoff",
|
||||
"rusqlite",
|
||||
"rustls",
|
||||
@@ -2264,7 +2263,6 @@ dependencies = [
|
||||
"tokio-tungstenite 0.28.0",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# Rust Discovery / RMM
|
||||
|
||||
**Stand 15. November 2026, Spezifikation 1.23.** Linux M0–M5 ist auf der
|
||||
Ubuntu-Cloud-VM im dev/test-Betrieb abgenommen. Der zusätzliche Auftrag umfasst
|
||||
die Windows-11-VM, die genehmigte Skriptkonsole und den Agent-Selbstupdater.
|
||||
Beide aktiven Geräte melden sich an `discovery.ease-technologies.de` und sind
|
||||
über MCP mit gespeicherten Inventardaten abrufbar. Das Notebook dient der
|
||||
Entwicklung. [Abgleich der Geräte nach dem Gatewaywechsel](docs/server-time-gateway-deploy.md)
|
||||
Aktueller Entwicklungsstand: **Linux-MVP M0–M5 im begrenzten dev/test-Umfang abgeschlossen**,
|
||||
Spezifikation 1.15, 2026-11-13. Der endgültige Server ist
|
||||
`discovery.ease-technologies.de`. Der Linux-Client läuft ausschließlich auf der
|
||||
Ubuntu-Cloud-VM; das Notebook dient ausschließlich der Entwicklung. Die
|
||||
Windows-11-Test-VM ist ein eigener Gast und darf parallel entwickelt werden.
|
||||
|
||||
## Tatsächlich nachgewiesen
|
||||
|
||||
@@ -87,17 +86,14 @@ Kontrolle vor und nach den Ablehnungen. Das sind keine LocalService-
|
||||
TLS-Negativnachweise. Der permanente Dienst und seine Geräteidentität blieben
|
||||
erhalten; private Schlüssel verließen die VM nicht.
|
||||
|
||||
Auf Windows laufen der passive Agent und der getrennte SYSTEM-Helper. Die
|
||||
beiderseitige Identitätsprüfung zwischen den Diensten ist nativ belegt. Der
|
||||
PowerShell-Executor und die Bindung an den genehmigten Plan sind implementiert.
|
||||
Für die erste durchgängige Abnahme fehlen der unabhängige signierte Zeitabgleich
|
||||
der beiden laufenden Rollen sowie ein WebUI-genehmigter Auftrag mit überprüfter
|
||||
Ausgabe. Selbstupdates benötigen noch eine native Aktualisierung des installierten
|
||||
Agent-/Helper-Paars unter Erhalt der Geräteidentität. APT- und MSI-Paketfälle
|
||||
prüfen die Verwaltung anderer Software. [Windows-Abnahmen](docs/windows-gates.md)
|
||||
und [Agent-Selbstupdate](docs/agent-updater-runtime-source.md).
|
||||
|
||||
Weitere Agentplattformen, PVE/PBS/Cluster/Backups und Betriebsreife
|
||||
Windows meldet weiterhin keine Jobcapability und hat keinen Jobexecutor.
|
||||
Vertrauenswürdige Uhr, gemeinsamer signierter Sync-/Journal-/Einmalverbrauchskern
|
||||
sowie plattformgebundene Interpreterpläne in Domain, Server und WebUI sind vor
|
||||
dem ersten Windowsjob offen. Entwicklungsbuilds sind unsigniert;
|
||||
Rotation, Widerruf, privilegierter Helper, Paketaktionen und Windows-Reboot
|
||||
sind noch nicht abgenommen. Die [Windows-Gates](docs/windows-gates.md) und
|
||||
[Grenze vor dem ersten Job](docs/windows-job-boundary.md) führen den nächsten
|
||||
Umfang. Weitere Agentplattformen, PVE/PBS/Cluster/Backups und Betriebsreife
|
||||
folgen außerhalb des Linux-MVP. RustDesk ist ausdrücklich ausgelassen.
|
||||
|
||||
## Projektunterlagen
|
||||
|
||||
@@ -34,7 +34,6 @@ rmm-protocol = { path = "../protocol" }
|
||||
rmm-time-attestation = { path = "../time-attestation" }
|
||||
rusqlite = { version = "0.32.1", features = ["bundled"] }
|
||||
fs2 = "0.4.3"
|
||||
x509-parser = { version = "=0.18.1", features = ["verify"] }
|
||||
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -1,496 +0,0 @@
|
||||
//! Fixed passive development route fixture, never an installed-role or clock proof.
|
||||
//! Existing device mTLS material stays on this VM and is never hashed or exported.
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
#[path = "../../agent/src/https_channel.rs"]
|
||||
pub mod https_channel;
|
||||
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod probe {
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
auth::Binding,
|
||||
crypto::{DalekVerifier, Ed25519Verifier},
|
||||
};
|
||||
use rmm_agent_windows::{
|
||||
helper_ipc::{self as ipc, PinnedFile},
|
||||
native,
|
||||
};
|
||||
use rmm_time_attestation::{Context, Payload, Request, Role, SignedAttestation};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::windows::{
|
||||
fs::{MetadataExt, OpenOptionsExt},
|
||||
io::{FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_NO_TOKEN, GetLastError},
|
||||
Security::{
|
||||
CheckTokenMembership, CreateWellKnownSid, TOKEN_QUERY, WinBuiltinAdministratorsSid,
|
||||
},
|
||||
Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
|
||||
},
|
||||
System::Threading::{GetCurrentThread, OpenThreadToken},
|
||||
};
|
||||
|
||||
const ROOT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\time-route";
|
||||
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
|
||||
const STATE: &str = r"C:\ProgramData\RustDiscovery\state";
|
||||
const CA: &str = r"C:\ProgramData\RustDiscovery\server-ca.pem";
|
||||
const PEER_PIN: &str = r"C:\ProgramData\RustDiscoverySystem\agent-pin.json";
|
||||
const CONFIG_SHA: &str = "7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851";
|
||||
const PEER_PIN_SHA: &str = "af518db88a6d4a856c32ca9d89d88405689aa2d89163ab0cb638c1abdd8fa118";
|
||||
const TIME_PIN_SHA: &str = "c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2";
|
||||
const AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3";
|
||||
const ASSET: &str = "a176520e-8a91-4e93-a78b-8e7620f430e0";
|
||||
const SERVER: &str = "discovery.ease-technologies.de";
|
||||
const DOMAIN: &[u8] = b"RMM-TIME-ATTESTATION/v1\0";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FixtureContext {
|
||||
schema_version: u32,
|
||||
case_id: Uuid,
|
||||
connection_generation: u64,
|
||||
windows_boot_id: Uuid,
|
||||
server_boot_id: Uuid,
|
||||
server_context_evidence_sha256: String,
|
||||
binding_sha256: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PublicTimePin {
|
||||
schema_version: u32,
|
||||
algorithm: String,
|
||||
server_instance: Uuid,
|
||||
key_id: String,
|
||||
key_generation: u64,
|
||||
public_key_hex: String,
|
||||
}
|
||||
fn hash(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v))
|
||||
}
|
||||
fn hex<const N: usize>(value: &str) -> Result<[u8; N]> {
|
||||
ensure!(
|
||||
value.len() == 2 * N && value.bytes().all(|v| v.is_ascii_hexdigit()),
|
||||
"FIXTURE_HEX"
|
||||
);
|
||||
let mut out = [0; N];
|
||||
for (i, b) in out.iter_mut().enumerate() {
|
||||
*b = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn administrator() -> Result<()> {
|
||||
let mut thread = ptr::null_mut();
|
||||
if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 {
|
||||
let _held = unsafe { OwnedHandle::from_raw_handle(thread) };
|
||||
anyhow::bail!("FIXTURE_IMPERSONATION_FORBIDDEN");
|
||||
}
|
||||
ensure!(
|
||||
unsafe { GetLastError() } == ERROR_NO_TOKEN,
|
||||
"FIXTURE_THREAD_TOKEN"
|
||||
);
|
||||
let mut sid = [0usize; 16];
|
||||
let mut bytes = std::mem::size_of_val(&sid) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
ptr::null_mut(),
|
||||
sid.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
} != 0,
|
||||
"FIXTURE_ADMIN_SID"
|
||||
);
|
||||
let mut enabled = 0;
|
||||
ensure!(
|
||||
unsafe { CheckTokenMembership(ptr::null_mut(), sid.as_mut_ptr().cast(), &mut enabled) }
|
||||
!= 0
|
||||
&& enabled != 0,
|
||||
"FIXTURE_ADMIN_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn public_read(
|
||||
path: &Path,
|
||||
maximum: usize,
|
||||
readers: &[String],
|
||||
) -> Result<(PinnedFile, Vec<u8>)> {
|
||||
let mut held = PinnedFile::open(path, false, readers, &[], false)?;
|
||||
ensure!(
|
||||
held.file.metadata()?.len() <= maximum as u64,
|
||||
"FIXTURE_INPUT_LIMIT"
|
||||
);
|
||||
let mut raw = Vec::new();
|
||||
(&mut held.file)
|
||||
.take(maximum as u64 + 1)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= maximum, "FIXTURE_INPUT_LIMIT");
|
||||
held.check()?;
|
||||
Ok((held, raw))
|
||||
}
|
||||
// Do not call sha256() on these credential handles, including on error.
|
||||
// Share-read only prevents content replacement/write during the held read.
|
||||
fn credential_read(path: &Path, maximum: usize) -> Result<(File, Vec<u8>)> {
|
||||
native::private_path(path, false)?;
|
||||
let mut held = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
let before = held.metadata()?;
|
||||
ensure!(
|
||||
before.is_file()
|
||||
&& before.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& before.len() <= maximum as u64,
|
||||
"FIXTURE_CREDENTIAL_TYPE"
|
||||
);
|
||||
let identity = ipc::file_identity(&held)?;
|
||||
let mut raw = Vec::new();
|
||||
(&mut held).take(maximum as u64 + 1).read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= maximum, "FIXTURE_CREDENTIAL_LIMIT");
|
||||
native::private_path(path, false)?;
|
||||
let current = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
ensure!(
|
||||
ipc::file_identity(¤t)? == identity && held.metadata()?.len() == before.len(),
|
||||
"FIXTURE_CREDENTIAL_REPLACED"
|
||||
);
|
||||
Ok((held, raw))
|
||||
}
|
||||
fn create(root: &Path, name: &str, raw: &[u8]) -> Result<()> {
|
||||
ensure!(raw.len() <= 32768, "FIXTURE_REPORT_LIMIT");
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(root.join(name))?;
|
||||
file.write_all(raw)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn verify_signed(
|
||||
raw: &[u8],
|
||||
request: &Request,
|
||||
pin: &PublicTimePin,
|
||||
context: &FixtureContext,
|
||||
) -> Result<Payload> {
|
||||
let signed: SignedAttestation = serde_json::from_slice(raw)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(&signed)? == raw && signed.payload.len() <= 8192,
|
||||
"FIXTURE_CANONICAL_RESPONSE"
|
||||
);
|
||||
ensure!(
|
||||
signed.signature_hex.len() == 128
|
||||
&& signed
|
||||
.signature_hex
|
||||
.bytes()
|
||||
.all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v)),
|
||||
"FIXTURE_SIGNATURE_FORMAT"
|
||||
);
|
||||
let payload: Payload = serde_json::from_str(&signed.payload)?;
|
||||
ensure!(
|
||||
serde_json::to_string(&payload)? == signed.payload,
|
||||
"FIXTURE_CANONICAL_PAYLOAD"
|
||||
);
|
||||
ensure!(
|
||||
payload.version == 1
|
||||
&& payload.server_instance == pin.server_instance
|
||||
&& payload.server_boot_id == context.server_boot_id
|
||||
&& payload.key_id == pin.key_id
|
||||
&& payload.key_generation == pin.key_generation
|
||||
&& payload.request_sha256 == request.sha256()?
|
||||
&& payload.captured_utc_ns > 0
|
||||
&& payload.server_error_ns <= rmm_time_attestation::MAX_SERVER_ERROR_NS
|
||||
&& payload.source_sync_age_ns <= rmm_time_attestation::MAX_SYNC_AGE_NS,
|
||||
"FIXTURE_RESPONSE_BINDING"
|
||||
);
|
||||
let key = hex::<32>(&pin.public_key_hex)?;
|
||||
let signature = hex::<64>(&signed.signature_hex)?;
|
||||
let mut message = DOMAIN.to_vec();
|
||||
message.extend_from_slice(signed.payload.as_bytes());
|
||||
ensure!(
|
||||
DalekVerifier.validate_key(&key)?
|
||||
&& DalekVerifier.verify(&key, &message, &signature)?,
|
||||
"FIXTURE_SIGNATURE"
|
||||
);
|
||||
Ok(payload)
|
||||
}
|
||||
async fn bounded_response(mut response: reqwest::Response) -> Result<(u16, Vec<u8>)> {
|
||||
let status = response.status().as_u16();
|
||||
if status == 200 {
|
||||
ensure!(
|
||||
response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
== Some("application/json"),
|
||||
"FIXTURE_RESPONSE_MEDIA"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
response.content_length().is_none_or(|n| n <= 16384),
|
||||
"FIXTURE_RESPONSE_LENGTH"
|
||||
);
|
||||
let mut raw = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
ensure!(
|
||||
raw.len()
|
||||
.checked_add(chunk.len())
|
||||
.is_some_and(|n| n <= 16384),
|
||||
"FIXTURE_RESPONSE_LIMIT"
|
||||
);
|
||||
raw.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok((status, raw))
|
||||
}
|
||||
async fn execute(root: &Path, id: Uuid) -> Result<Value> {
|
||||
let mut directory = PinnedFile::open(root, true, &[], &[], false)?;
|
||||
let mut root_directory = PinnedFile::open(Path::new(ROOT), true, &[], &[], false)?;
|
||||
ensure!(
|
||||
std::env::current_exe()?
|
||||
.to_string_lossy()
|
||||
.eq_ignore_ascii_case(&root.join("TimeRouteProbe.exe").to_string_lossy()),
|
||||
"FIXTURE_OWN_EXECUTABLE_PATH"
|
||||
);
|
||||
let mut leaves = fs::read_dir(root)?
|
||||
.map(|v| v.map(|v| v.file_name().to_string_lossy().into_owned()))
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
leaves.sort();
|
||||
ensure!(
|
||||
leaves == ["TimeRouteProbe.exe", "context.json", "time-public-key.json"],
|
||||
"FIXTURE_CREATE_ONCE_CASE"
|
||||
);
|
||||
let (mut context_file, context_raw) = public_read(&root.join("context.json"), 4096, &[])?;
|
||||
let context: FixtureContext = serde_json::from_slice(&context_raw)?;
|
||||
ensure!(
|
||||
context.schema_version == 1
|
||||
&& context.case_id == id
|
||||
&& context.connection_generation > 1
|
||||
&& !context.windows_boot_id.is_nil()
|
||||
&& !context.server_boot_id.is_nil()
|
||||
&& digest(&context.server_context_evidence_sha256)
|
||||
&& digest(&context.binding_sha256),
|
||||
"FIXTURE_ROOT_CONTEXT"
|
||||
);
|
||||
let (mut time_file, time_raw) = public_read(&root.join("time-public-key.json"), 4096, &[])?;
|
||||
ensure!(
|
||||
hash(&time_raw) == TIME_PIN_SHA,
|
||||
"FIXTURE_REAL_PUBLIC_TIME_PIN"
|
||||
);
|
||||
let pin: PublicTimePin = serde_json::from_slice(&time_raw)?;
|
||||
ensure!(
|
||||
pin.schema_version == 1
|
||||
&& pin.algorithm == "Ed25519"
|
||||
&& !pin.server_instance.is_nil()
|
||||
&& pin.key_generation > 0
|
||||
&& !pin.key_id.is_empty()
|
||||
&& pin.key_id.len() <= 64
|
||||
&& pin
|
||||
.key_id
|
||||
.bytes()
|
||||
.all(|v| v.is_ascii_alphanumeric() || v == b'-' || v == b'_')
|
||||
&& digest(&pin.public_key_hex),
|
||||
"FIXTURE_PUBLIC_TIME_PROFILE"
|
||||
);
|
||||
let agent_sid = native::service_sid()?;
|
||||
// The protected peer-pin has read ACEs for both fixed installed services.
|
||||
let helper_sid = ipc::service_sid("RmmDiscoverySystemHelper")?;
|
||||
let (mut peer_file, peer_raw) =
|
||||
public_read(Path::new(PEER_PIN), 16384, &[agent_sid, helper_sid])?;
|
||||
ensure!(hash(&peer_raw) == PEER_PIN_SHA, "FIXTURE_ORIGINAL_PEER_PIN");
|
||||
let peer: ipc::Pin = serde_json::from_slice(&peer_raw)?;
|
||||
peer.validate()?;
|
||||
let binding: Binding = peer.binding;
|
||||
ensure!(
|
||||
binding.agent_id.to_string() == AGENT
|
||||
&& binding.asset_id.to_string() == ASSET
|
||||
&& hash(&serde_json::to_vec(&binding)?) == context.binding_sha256,
|
||||
"FIXTURE_EXISTING_DEVICE_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
hex::<32>(&pin.public_key_hex)? != hex::<32>(&binding.public_key_hex)?,
|
||||
"FIXTURE_TIME_JOB_KEY_REUSE"
|
||||
);
|
||||
let (config_handle, config_raw) = credential_read(Path::new(CONFIG), 4096)?;
|
||||
ensure!(
|
||||
hash(&config_raw) == CONFIG_SHA,
|
||||
"FIXTURE_ORIGINAL_PASSIVE_CONFIG"
|
||||
);
|
||||
let config: Value = serde_json::from_slice(&config_raw)?;
|
||||
ensure!(
|
||||
config["server_name"] == SERVER
|
||||
&& config["connect_address"] == "88.99.80.202:443"
|
||||
&& config["state_directory"] == STATE
|
||||
&& config["ca_file"] == CA
|
||||
&& config["transport"] == "auto",
|
||||
"FIXTURE_CONFIG_ENDPOINT"
|
||||
);
|
||||
create(
|
||||
root,
|
||||
"intent.json",
|
||||
&serde_json::to_vec(&json!({"case_id":id,"run_once":true,
|
||||
"context_sha256":hash(&context_raw),"public_time_pin_sha256":TIME_PIN_SHA,
|
||||
"route":rmm_time_attestation::ENDPOINT,"no_jobs":true,"clock_proof":false}))?,
|
||||
)?;
|
||||
let (ca_handle, ca) = credential_read(Path::new(CA), 32768)?;
|
||||
let state = Path::new(STATE);
|
||||
let (certificate_handle, certificate) = credential_read(&state.join("device.pem"), 32768)?;
|
||||
let (private_handle, mut private_key) = credential_read(&state.join("device.key"), 16384)?;
|
||||
let client = crate::https_channel::mtls_client(
|
||||
"88.99.80.202:443".parse()?,
|
||||
&ca,
|
||||
&certificate,
|
||||
&private_key,
|
||||
)?;
|
||||
private_key.fill(0);
|
||||
drop(private_key); // Private bytes never enter any JSON, digest or report.
|
||||
let incarnation = Uuid::new_v4();
|
||||
let mut reports = Vec::new();
|
||||
for kind in ["positive-agent", "tenant-mismatch", "stale-connection"] {
|
||||
let mut request = Request {
|
||||
version: 1,
|
||||
endpoint: rmm_time_attestation::ENDPOINT.into(),
|
||||
nonce: rand::random::<[u8; 32]>()
|
||||
.iter()
|
||||
.map(|v| format!("{v:02x}"))
|
||||
.collect(),
|
||||
context: Context {
|
||||
tenant_id: binding.tenant_id,
|
||||
asset_id: binding.asset_id,
|
||||
agent_id: binding.agent_id,
|
||||
enrollment_generation: binding.enrollment_generation,
|
||||
assignment_generation: binding.assignment_version,
|
||||
connection_generation: context.connection_generation,
|
||||
windows_boot_id: context.windows_boot_id,
|
||||
verifier_incarnation: incarnation,
|
||||
role: Role::Agent,
|
||||
helper_image_sha256: None,
|
||||
binding_schema: 1,
|
||||
},
|
||||
};
|
||||
if kind == "tenant-mismatch" {
|
||||
request.context.tenant_id =
|
||||
Uuid::parse_str("22222222-2222-4222-8222-222222222222")?;
|
||||
ensure!(
|
||||
request.context.tenant_id != binding.tenant_id,
|
||||
"FIXTURE_FOREIGN_TENANT"
|
||||
);
|
||||
}
|
||||
if kind == "stale-connection" {
|
||||
request.context.connection_generation -= 1;
|
||||
}
|
||||
request.validate()?;
|
||||
if kind == "positive-agent" {
|
||||
create(
|
||||
root,
|
||||
"positive-request.json",
|
||||
&serde_json::to_vec(&request)?,
|
||||
)?;
|
||||
}
|
||||
let (status, raw) = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
let response = client
|
||||
.post("https://discovery.ease-technologies.de:443/agent/v1/time-attestation")
|
||||
.timeout(Duration::from_secs(3))
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
bounded_response(response).await
|
||||
})
|
||||
.await??;
|
||||
let mut report = json!({"kind":kind,"http_status":status,"response_bytes":raw.len(),"response_sha256":hash(&raw),"request_sha256":request.sha256()?});
|
||||
if kind == "positive-agent" {
|
||||
create(root, "positive-response.json", &raw)?;
|
||||
ensure!(status == 200, "FIXTURE_POSITIVE_STATUS");
|
||||
let payload = verify_signed(&raw, &request, &pin, &context)?;
|
||||
report["signature_verified"] = true.into();
|
||||
report["whole_request_context_bound"] = true.into();
|
||||
report["server_boot_id"] = payload.server_boot_id.to_string().into();
|
||||
} else {
|
||||
ensure!(
|
||||
status == if kind == "tenant-mismatch" { 403 } else { 409 },
|
||||
"FIXTURE_NEGATIVE_STATUS"
|
||||
);
|
||||
}
|
||||
create(
|
||||
root,
|
||||
&format!("{kind}-result.json"),
|
||||
&serde_json::to_vec(&report)?,
|
||||
)?;
|
||||
reports.push(report);
|
||||
}
|
||||
context_file.check()?;
|
||||
time_file.check()?;
|
||||
peer_file.check()?;
|
||||
directory.check()?;
|
||||
root_directory.check()?;
|
||||
drop((config_handle, ca_handle, certificate_handle, private_handle));
|
||||
let report = json!({"schema_version":1,"case_id":id,"verified":true,"execution_context":"bootstrap_administrator_protocol_probe",
|
||||
"endpoint":rmm_time_attestation::ENDPOINT,"reports":reports,"shared_existing_device_mtls":true,
|
||||
"private_key_exported":false,"private_key_hashed":false,"private_key_copied_to_evidence":false,
|
||||
"certificate_verification_disabled":false,"service_role_proven":false,"trusted_clock_proven":false,
|
||||
"clock_freshness_qualified":false,"sync_ready":false,"jobs_created":false,"grants_created":false,
|
||||
"context_sha256":hash(&context_raw),"server_context_evidence_sha256":context.server_context_evidence_sha256,
|
||||
"public_time_pin_sha256":TIME_PIN_SHA});
|
||||
create(root, "report.json", &serde_json::to_vec(&report)?)?;
|
||||
Ok(report)
|
||||
}
|
||||
pub fn run() -> Result<Value> {
|
||||
administrator()?;
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
ensure!(
|
||||
args.len() == 2 && args[0] == "probe",
|
||||
"FIXTURE_FIXED_ARGUMENTS"
|
||||
);
|
||||
let id = Uuid::parse_str(&args[1])?;
|
||||
ensure!(
|
||||
!id.is_nil() && id.to_string() == args[1],
|
||||
"FIXTURE_CANONICAL_CASE"
|
||||
);
|
||||
// Before any async runtime/threads, force the one verified DNS identity.
|
||||
unsafe {
|
||||
std::env::set_var("RMM_SERVER_NAME", SERVER);
|
||||
}
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(execute(&PathBuf::from(ROOT).join(id.to_string()), id))
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
fn main() {
|
||||
match probe::run() {
|
||||
Ok(value) => println!("{value}"),
|
||||
Err(_) => {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"verified":false,"code":"WINDOWS_TIME_ROUTE_FIXTURE_INCOMPLETE","service_role_proven":false,"trusted_clock_proven":false})
|
||||
);
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(all(windows, feature = "system-helper")))]
|
||||
fn main() {
|
||||
eprintln!("Fixed time route fixture requires native Windows and system-helper build");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -1,832 +0,0 @@
|
||||
//! Passive TLS renewal. SQLite commits only public CSR/certificate/version data;
|
||||
//! private keys stay in immutable, protected files outside the telemetry WAL.
|
||||
//! The caller must retain the existing exclusive agent-state journal lock.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rcgen::{CertificateParams, DnType, KeyPair};
|
||||
use rusqlite::{Connection, params};
|
||||
use rustls::{RootCertStore, pki_types::UnixTime, sign::CertifiedKey};
|
||||
use serde::Deserialize;
|
||||
use std::{io::Cursor, sync::Arc, time::Duration};
|
||||
use uuid::Uuid;
|
||||
use x509_parser::prelude::*;
|
||||
|
||||
pub struct DeviceIdentity {
|
||||
pub certificate_pem: Vec<u8>,
|
||||
pub private_key_pem: Vec<u8>,
|
||||
}
|
||||
/// Never supplies private bytes to the SQLite writer.
|
||||
pub trait KeyFiles {
|
||||
fn read(&self, version: Uuid) -> Result<Vec<u8>>;
|
||||
/// CreateNew, protected before writing, and durable before returning.
|
||||
fn create(&self, version: Uuid, key: &[u8]) -> Result<()>;
|
||||
}
|
||||
pub struct RotationStore {
|
||||
agent: Uuid,
|
||||
enrollment: u64,
|
||||
ca: Vec<u8>,
|
||||
}
|
||||
pub struct PendingRequest {
|
||||
pub identity: DeviceIdentity,
|
||||
pub csr_pem: String,
|
||||
base: Uuid,
|
||||
version: Uuid,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RenewalResponse {
|
||||
agent_id: Uuid,
|
||||
certificate_pem: String,
|
||||
overlap_seconds: u32,
|
||||
}
|
||||
impl RotationStore {
|
||||
pub fn new(agent: Uuid, enrollment: u64, ca: Vec<u8>) -> Result<Self> {
|
||||
ensure!(
|
||||
!agent.is_nil() && enrollment > 0,
|
||||
"ROTATION_IDENTITY_INVALID"
|
||||
);
|
||||
Ok(Self {
|
||||
agent,
|
||||
enrollment,
|
||||
ca,
|
||||
})
|
||||
}
|
||||
/// Called under the journal lock. Legacy files are eligible exactly once,
|
||||
/// before any selector exists. There is no recovery fallback or reenrollment.
|
||||
pub fn initialize(
|
||||
&self,
|
||||
db: &mut Connection,
|
||||
keys: &impl KeyFiles,
|
||||
cert: &[u8],
|
||||
now: i64,
|
||||
) -> Result<()> {
|
||||
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
tx.execute_batch("CREATE TABLE IF NOT EXISTS tls_versions(version TEXT PRIMARY KEY,certificate BLOB,csr TEXT);
|
||||
CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version));")?;
|
||||
let present: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM tls_rotation)", [], |r| {
|
||||
r.get(0)
|
||||
})?;
|
||||
if !present {
|
||||
let count: u64 = tx.query_row("SELECT count(*) FROM tls_versions", [], |r| r.get(0))?;
|
||||
ensure!(count == 0, "ROTATION_SELECTOR_MISSING");
|
||||
self.verify(cert, &keys.read(Uuid::nil())?, now)?;
|
||||
tx.execute(
|
||||
"INSERT INTO tls_versions VALUES(?1,?2,NULL)",
|
||||
params![Uuid::nil().to_string(), cert],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO tls_rotation VALUES(1,1,?1,?2,?3,NULL)",
|
||||
params![
|
||||
self.agent.to_string(),
|
||||
self.enrollment,
|
||||
Uuid::nil().to_string()
|
||||
],
|
||||
)?;
|
||||
}
|
||||
self.current(&tx, keys, now)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
fn selector(&self, db: &Connection) -> Result<(Uuid, Option<Uuid>)> {
|
||||
let (schema, agent, enrollment, current, pending): (u32,String,u64,String,Option<String>) = db.query_row("SELECT schema_version,agent,enrollment,current_version,pending_version FROM tls_rotation WHERE id=1",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
||||
ensure!(
|
||||
schema == 1 && agent == self.agent.to_string() && enrollment == self.enrollment,
|
||||
"ROTATION_IDENTITY_CHANGED"
|
||||
);
|
||||
Ok((
|
||||
Uuid::parse_str(¤t)?,
|
||||
pending.map(|s| Uuid::parse_str(&s)).transpose()?,
|
||||
))
|
||||
}
|
||||
pub fn current(
|
||||
&self,
|
||||
db: &Connection,
|
||||
keys: &impl KeyFiles,
|
||||
now: i64,
|
||||
) -> Result<DeviceIdentity> {
|
||||
let (version, _) = self.selector(db)?;
|
||||
let cert: Vec<u8> = db.query_row(
|
||||
"SELECT certificate FROM tls_versions WHERE version=?1",
|
||||
[version.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let key = keys.read(version)?;
|
||||
self.verify(&cert, &key, now)?;
|
||||
Ok(DeviceIdentity {
|
||||
certificate_pem: cert,
|
||||
private_key_pem: key,
|
||||
})
|
||||
}
|
||||
fn verify(&self, pem: &[u8], key: &[u8], now: i64) -> Result<(i64, i64)> {
|
||||
ensure!(
|
||||
pem.len() <= 32768 && key.len() <= 16384,
|
||||
"ROTATION_IDENTITY_LIMIT"
|
||||
);
|
||||
let chain =
|
||||
rustls_pemfile::certs(&mut Cursor::new(pem)).collect::<std::io::Result<Vec<_>>>()?;
|
||||
let leaf = chain.first().context("ROTATION_CERTIFICATE_MISSING")?;
|
||||
let (rest, cert) = X509Certificate::from_der(leaf.as_ref())
|
||||
.map_err(|_| anyhow::anyhow!("ROTATION_CERTIFICATE_PARSE"))?;
|
||||
let names = cert.subject().iter_common_name().collect::<Vec<_>>();
|
||||
ensure!(
|
||||
rest.is_empty()
|
||||
&& names.len() == 1
|
||||
&& names[0].as_str()? == self.agent.to_string()
|
||||
&& !cert.is_ca(),
|
||||
"ROTATION_AGENT_MISMATCH"
|
||||
);
|
||||
let mut roots = RootCertStore::empty();
|
||||
for ca in rustls_pemfile::certs(&mut Cursor::new(&self.ca)) {
|
||||
roots.add(ca?)?;
|
||||
}
|
||||
ensure!(!roots.is_empty(), "ROTATION_CA_MISSING");
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
|
||||
Arc::new(roots),
|
||||
provider.clone(),
|
||||
)
|
||||
.build()?;
|
||||
verifier.verify_client_cert(
|
||||
leaf,
|
||||
&chain[1..],
|
||||
UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(now)?)),
|
||||
)?;
|
||||
let key =
|
||||
rustls_pemfile::private_key(&mut Cursor::new(key))?.context("ROTATION_KEY_MISSING")?;
|
||||
// from_der allows unknown key consistency; require an actual match.
|
||||
CertifiedKey::from_der(chain.clone(), key, &provider)?.keys_match()?;
|
||||
let begin = cert.validity().not_before.timestamp();
|
||||
let end = cert.validity().not_after.timestamp();
|
||||
ensure!(
|
||||
begin <= now && now < end,
|
||||
"ROTATION_EXPIRED_RECOVERY_REQUIRED"
|
||||
);
|
||||
Ok((begin, end))
|
||||
}
|
||||
pub fn due(&self, db: &Connection, keys: &impl KeyFiles, now: i64) -> Result<bool> {
|
||||
let identity = self.current(db, keys, now)?;
|
||||
let (begin, end) =
|
||||
self.verify(&identity.certificate_pem, &identity.private_key_pem, now)?;
|
||||
Ok(self.selector(db)?.1.is_some()
|
||||
|| now.saturating_sub(begin) >= 20 * 86400
|
||||
|| end.saturating_sub(now) <= 10 * 86400)
|
||||
}
|
||||
pub fn has_pending(&self, db: &Connection) -> Result<bool> {
|
||||
Ok(self.selector(db)?.1.is_some())
|
||||
}
|
||||
/// A crash before the transaction leaves only an unselected key file. A
|
||||
/// response loss reuses the committed CSR/key and still-valid old mTLS leaf.
|
||||
pub fn prepare(
|
||||
&self,
|
||||
db: &mut Connection,
|
||||
keys: &impl KeyFiles,
|
||||
now: i64,
|
||||
) -> Result<PendingRequest> {
|
||||
let identity = self.current(db, keys, now)?;
|
||||
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
let (base, pending) = self.selector(&tx)?;
|
||||
let (version, csr_pem) = if let Some(version) = pending {
|
||||
ensure!(
|
||||
!version.is_nil() && version != base,
|
||||
"ROTATION_PENDING_CONFLICT"
|
||||
);
|
||||
let csr: String = tx.query_row(
|
||||
"SELECT csr FROM tls_versions WHERE version=?1 AND certificate IS NULL",
|
||||
[version.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let key = KeyPair::from_pem(std::str::from_utf8(&keys.read(version)?)?)?;
|
||||
let (rest, pem) = x509_parser::pem::parse_x509_pem(csr.as_bytes())
|
||||
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_CSR"))?;
|
||||
ensure!(
|
||||
rest.is_empty() && pem.label == "CERTIFICATE REQUEST",
|
||||
"ROTATION_PENDING_CSR"
|
||||
);
|
||||
let (rest, request) = X509CertificationRequest::from_der(&pem.contents)
|
||||
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_CSR"))?;
|
||||
ensure!(
|
||||
rest.is_empty()
|
||||
&& request
|
||||
.certification_request_info
|
||||
.subject_pki
|
||||
.subject_public_key
|
||||
.data
|
||||
.as_ref()
|
||||
== key.public_key_raw(),
|
||||
"ROTATION_PENDING_KEY_MISMATCH"
|
||||
);
|
||||
request
|
||||
.verify_signature()
|
||||
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_SIGNATURE"))?;
|
||||
(version, csr)
|
||||
} else {
|
||||
let key = KeyPair::generate()?;
|
||||
let csr = self.csr(&key)?;
|
||||
let version = Uuid::new_v4();
|
||||
keys.create(version, key.serialize_pem().as_bytes())?;
|
||||
tx.execute(
|
||||
"INSERT INTO tls_versions VALUES(?1,NULL,?2)",
|
||||
params![version.to_string(), csr],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE tls_rotation SET pending_version=?1 WHERE id=1",
|
||||
[version.to_string()],
|
||||
)?;
|
||||
(version, csr)
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(PendingRequest {
|
||||
identity,
|
||||
csr_pem,
|
||||
base,
|
||||
version,
|
||||
})
|
||||
}
|
||||
fn csr(&self, key: &KeyPair) -> Result<String> {
|
||||
let mut parameters = CertificateParams::default();
|
||||
parameters
|
||||
.distinguished_name
|
||||
.push(DnType::CommonName, self.agent.to_string());
|
||||
Ok(parameters.serialize_request(key)?.pem()?)
|
||||
}
|
||||
/// Commit only the exact pending version, with fresh certificate validation.
|
||||
/// Prior certs and key files are retained; failed installs change no selector.
|
||||
pub fn install(
|
||||
&self,
|
||||
db: &mut Connection,
|
||||
keys: &impl KeyFiles,
|
||||
request: &PendingRequest,
|
||||
bytes: &[u8],
|
||||
now: i64,
|
||||
) -> Result<()> {
|
||||
ensure!(bytes.len() <= 65536, "ROTATION_RESPONSE_LIMIT");
|
||||
let response: RenewalResponse = serde_json::from_slice(bytes)?;
|
||||
ensure!(
|
||||
response.agent_id == self.agent && response.overlap_seconds == 300,
|
||||
"ROTATION_RESPONSE_BINDING_INVALID"
|
||||
);
|
||||
self.verify(
|
||||
response.certificate_pem.as_bytes(),
|
||||
&keys.read(request.version)?,
|
||||
now,
|
||||
)?;
|
||||
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
ensure!(
|
||||
self.selector(&tx)? == (request.base, Some(request.version)),
|
||||
"ROTATION_SELECTOR_CHANGED"
|
||||
);
|
||||
let csr: String = tx.query_row(
|
||||
"SELECT csr FROM tls_versions WHERE version=?1 AND certificate IS NULL",
|
||||
[request.version.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(csr == request.csr_pem, "ROTATION_PENDING_CHANGED");
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE tls_versions SET certificate=?1 WHERE version=?2 AND certificate IS NULL",
|
||||
params![
|
||||
response.certificate_pem.as_bytes(),
|
||||
request.version.to_string()
|
||||
]
|
||||
)? == 1,
|
||||
"ROTATION_PENDING_MISSING"
|
||||
);
|
||||
tx.execute(
|
||||
"UPDATE tls_rotation SET current_version=?1,pending_version=NULL WHERE id=1",
|
||||
[request.version.to_string()],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub struct ProtectedKeyFiles {
|
||||
root: std::path::PathBuf,
|
||||
// Denying FILE_SHARE_DELETE holds the actual parent against rename/removal.
|
||||
_directory: std::fs::File,
|
||||
}
|
||||
#[cfg(windows)]
|
||||
impl ProtectedKeyFiles {
|
||||
pub fn open(root: &std::path::Path) -> Result<Self> {
|
||||
use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::*;
|
||||
ensure!(root.is_absolute(), "ROTATION_ABSOLUTE_STATE_REQUIRED");
|
||||
let directory = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(root)?;
|
||||
crate::native::private_path(root, true)?;
|
||||
Self::information(&directory, true)?;
|
||||
Ok(Self {
|
||||
root: root.into(),
|
||||
_directory: directory,
|
||||
})
|
||||
}
|
||||
fn path(&self, version: Uuid) -> std::path::PathBuf {
|
||||
self.root.join(if version.is_nil() {
|
||||
"device.key".into()
|
||||
} else {
|
||||
format!("device-{version}.key")
|
||||
})
|
||||
}
|
||||
fn information(file: &std::fs::File, directory: bool) -> Result<()> {
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::*;
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
ensure!(
|
||||
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0,
|
||||
"ROTATION_FILE_INFORMATION"
|
||||
);
|
||||
ensure!(
|
||||
info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
|
||||
&& (directory || info.nNumberOfLinks == 1),
|
||||
"ROTATION_FILE_TYPE_OR_LINKS"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
impl KeyFiles for ProtectedKeyFiles {
|
||||
fn read(&self, version: Uuid) -> Result<Vec<u8>> {
|
||||
use std::{fs::OpenOptions, io::Read, os::windows::fs::OpenOptionsExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
let path = self.path(version);
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(0)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(&path)?;
|
||||
Self::information(&file, false)?;
|
||||
crate::native::private_path(&path, false)?;
|
||||
let mut bytes = Vec::new();
|
||||
Read::by_ref(&mut file)
|
||||
.take(16385)
|
||||
.read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() <= 16384, "ROTATION_KEY_LIMIT");
|
||||
Ok(bytes)
|
||||
}
|
||||
fn create(&self, version: Uuid, key: &[u8]) -> Result<()> {
|
||||
use std::{fs::OpenOptions, io::Write, os::windows::fs::OpenOptionsExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_WRITE_THROUGH,
|
||||
};
|
||||
ensure!(
|
||||
!version.is_nil() && key.len() <= 16384,
|
||||
"ROTATION_NEW_KEY_REQUIRED"
|
||||
);
|
||||
let path = self.path(version);
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(0)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
|
||||
.open(&path)?;
|
||||
Self::information(&file, false)?;
|
||||
// Inherited ACL must already be private: no secret byte precedes this.
|
||||
crate::native::private_path(&path, false)?;
|
||||
file.write_all(key)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rcgen::{BasicConstraints, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose};
|
||||
use std::{cell::RefCell, collections::BTreeMap};
|
||||
#[derive(Default)]
|
||||
struct Keys(RefCell<BTreeMap<Uuid, Vec<u8>>>);
|
||||
impl KeyFiles for Keys {
|
||||
fn read(&self, id: Uuid) -> Result<Vec<u8>> {
|
||||
self.0
|
||||
.borrow()
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.context("MISSING_TEST_KEY")
|
||||
}
|
||||
fn create(&self, id: Uuid, key: &[u8]) -> Result<()> {
|
||||
ensure!(!self.0.borrow().contains_key(&id), "TEST_CREATE_NEW");
|
||||
self.0.borrow_mut().insert(id, key.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn now() -> i64 {
|
||||
chrono::DateTime::parse_from_rfc3339("2026-11-21T00:00:00Z")
|
||||
.unwrap()
|
||||
.timestamp()
|
||||
}
|
||||
fn ca() -> (String, Issuer<'static, KeyPair>) {
|
||||
let mut p = CertificateParams::default();
|
||||
p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
||||
p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let cert = p.self_signed(&key).unwrap().pem();
|
||||
(cert, Issuer::new(p, key))
|
||||
}
|
||||
fn certificate(agent: Uuid, key: &[u8], issuer: &Issuer<'_, KeyPair>, client: bool) -> String {
|
||||
let mut p = CertificateParams::default();
|
||||
p.distinguished_name
|
||||
.push(DnType::CommonName, agent.to_string());
|
||||
p.not_before = rcgen::date_time_ymd(2026, 11, 1);
|
||||
p.not_after = rcgen::date_time_ymd(2026, 12, 1);
|
||||
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
|
||||
p.extended_key_usages = vec![if client {
|
||||
ExtendedKeyUsagePurpose::ClientAuth
|
||||
} else {
|
||||
ExtendedKeyUsagePurpose::ServerAuth
|
||||
}];
|
||||
p.signed_by(
|
||||
&KeyPair::from_pem(std::str::from_utf8(key).unwrap()).unwrap(),
|
||||
issuer,
|
||||
)
|
||||
.unwrap()
|
||||
.pem()
|
||||
}
|
||||
fn setup() -> (
|
||||
Connection,
|
||||
Keys,
|
||||
RotationStore,
|
||||
Issuer<'static, KeyPair>,
|
||||
String,
|
||||
) {
|
||||
let (ca, issuer) = ca();
|
||||
let store = RotationStore::new(Uuid::new_v4(), 1, ca.into_bytes()).unwrap();
|
||||
let keys = Keys::default();
|
||||
keys.create(
|
||||
Uuid::nil(),
|
||||
KeyPair::generate().unwrap().serialize_pem().as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
let cert = certificate(store.agent, &keys.read(Uuid::nil()).unwrap(), &issuer, true);
|
||||
let mut db = Connection::open_in_memory().unwrap();
|
||||
store
|
||||
.initialize(&mut db, &keys, cert.as_bytes(), now())
|
||||
.unwrap();
|
||||
(db, keys, store, issuer, cert)
|
||||
}
|
||||
fn reply(agent: Uuid, cert: &str) -> Vec<u8> {
|
||||
serde_json::to_vec(
|
||||
&serde_json::json!({"agent_id":agent,"certificate_pem":cert,"overlap_seconds":300}),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn response_loss_reuses_exact_pending_csr_and_private_key_stays_outside_sqlite() {
|
||||
let (mut db, keys, store, issuer, old) = setup();
|
||||
assert!(store.due(&db, &keys, now()).unwrap());
|
||||
let first = store.prepare(&mut db, &keys, now()).unwrap();
|
||||
let second = store.prepare(&mut db, &keys, now()).unwrap();
|
||||
assert_eq!(first.version, second.version);
|
||||
assert_eq!(first.csr_pem, second.csr_pem);
|
||||
assert_eq!(keys.0.borrow().len(), 2);
|
||||
assert_eq!(
|
||||
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
||||
old.as_bytes()
|
||||
);
|
||||
let new = certificate(
|
||||
store.agent,
|
||||
&keys.read(first.version).unwrap(),
|
||||
&issuer,
|
||||
true,
|
||||
);
|
||||
store
|
||||
.install(&mut db, &keys, &first, &reply(store.agent, &new), now())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
||||
new.as_bytes()
|
||||
);
|
||||
assert_eq!(store.selector(&db).unwrap(), (first.version, None));
|
||||
assert!(
|
||||
store
|
||||
.install(&mut db, &keys, &second, &reply(store.agent, &new), now())
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(keys.0.borrow().len(), 2);
|
||||
let values:Vec<String>=db.prepare("SELECT coalesce(CAST(certificate AS TEXT),'') || coalesce(csr,'') FROM tls_versions").unwrap().query_map([],|r|r.get(0)).unwrap().collect::<rusqlite::Result<_>>().unwrap();
|
||||
assert!(values.iter().all(|v| !v.contains("PRIVATE KEY")));
|
||||
}
|
||||
#[test]
|
||||
fn bad_reply_preserves_current_pending_and_original_identity() {
|
||||
let (mut db, keys, store, issuer, old) = setup();
|
||||
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
||||
let key = keys.read(pending.version).unwrap();
|
||||
let (_wrong_ca, wrong_issuer) = ca();
|
||||
let wrong_key = KeyPair::generate().unwrap().serialize_pem();
|
||||
for cert in [
|
||||
certificate(Uuid::new_v4(), &key, &issuer, true),
|
||||
certificate(store.agent, wrong_key.as_bytes(), &issuer, true),
|
||||
certificate(store.agent, &key, &issuer, false),
|
||||
certificate(store.agent, &key, &wrong_issuer, true),
|
||||
] {
|
||||
assert!(
|
||||
store
|
||||
.install(&mut db, &keys, &pending, &reply(store.agent, &cert), now())
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
||||
old.as_bytes()
|
||||
);
|
||||
assert_eq!(
|
||||
store.selector(&db).unwrap(),
|
||||
(Uuid::nil(), Some(pending.version))
|
||||
);
|
||||
}
|
||||
let valid = certificate(store.agent, &key, &issuer, true);
|
||||
assert!(
|
||||
store
|
||||
.install(
|
||||
&mut db,
|
||||
&keys,
|
||||
&pending,
|
||||
&reply(store.agent, &valid),
|
||||
now() + 11 * 86400
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.install(
|
||||
&mut db,
|
||||
&keys,
|
||||
&pending,
|
||||
&reply(Uuid::new_v4(), &valid),
|
||||
now()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn committed_version_never_falls_back_to_legacy_on_restart_or_missing_key() {
|
||||
let (mut db, keys, store, issuer, old) = setup();
|
||||
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
||||
let valid = certificate(
|
||||
store.agent,
|
||||
&keys.read(pending.version).unwrap(),
|
||||
&issuer,
|
||||
true,
|
||||
);
|
||||
store
|
||||
.install(&mut db, &keys, &pending, &reply(store.agent, &valid), now())
|
||||
.unwrap();
|
||||
store
|
||||
.initialize(&mut db, &keys, old.as_bytes(), now())
|
||||
.unwrap();
|
||||
assert_eq!(store.selector(&db).unwrap().0, pending.version);
|
||||
keys.0.borrow_mut().remove(&pending.version);
|
||||
assert!(
|
||||
store
|
||||
.initialize(&mut db, &keys, old.as_bytes(), now())
|
||||
.is_err()
|
||||
);
|
||||
assert!(store.current(&db, &keys, now()).is_err());
|
||||
assert_eq!(store.selector(&db).unwrap().0, pending.version);
|
||||
assert!(keys.read(Uuid::nil()).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn changed_pending_key_or_identity_cannot_create_a_second_request() {
|
||||
let (mut db, keys, store, _issuer, _old) = setup();
|
||||
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
||||
keys.0.borrow_mut().insert(
|
||||
pending.version,
|
||||
KeyPair::generate().unwrap().serialize_pem().into_bytes(),
|
||||
);
|
||||
assert!(store.prepare(&mut db, &keys, now()).is_err());
|
||||
assert_eq!(keys.0.borrow().len(), 2);
|
||||
let other = RotationStore::new(store.agent, 2, store.ca.clone()).unwrap();
|
||||
assert!(other.current(&db, &keys, now()).is_err());
|
||||
db.execute("DELETE FROM tls_rotation", []).unwrap();
|
||||
assert!(
|
||||
store
|
||||
.initialize(&mut db, &keys, b"not a bootstrap", now())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn journal_reopen_recovers_pending_before_hello_and_install_is_one_transaction() {
|
||||
let (_db, keys, store, issuer, old) = setup();
|
||||
let directory = std::env::temp_dir().join(format!("rmm-tls-renewal-{}", Uuid::new_v4()));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let mut journal = crate::journal::Journal::open(&directory).unwrap();
|
||||
journal.pin_identity(&store.agent.to_string()).unwrap();
|
||||
assert_eq!(journal.next_sequence().unwrap(), 1);
|
||||
store
|
||||
.initialize(journal.connection_mut(), &keys, old.as_bytes(), now())
|
||||
.unwrap();
|
||||
let pending = store
|
||||
.prepare(journal.connection_mut(), &keys, now())
|
||||
.unwrap();
|
||||
drop(journal);
|
||||
let mut journal = crate::journal::Journal::open(&directory).unwrap();
|
||||
journal.pin_identity(&store.agent.to_string()).unwrap();
|
||||
assert_eq!(journal.next_sequence().unwrap(), 2);
|
||||
assert!(store.has_pending(journal.connection()).unwrap());
|
||||
let recovered = store
|
||||
.prepare(journal.connection_mut(), &keys, now())
|
||||
.unwrap();
|
||||
assert_eq!(pending.version, recovered.version);
|
||||
assert_eq!(pending.csr_pem, recovered.csr_pem);
|
||||
let new = certificate(
|
||||
store.agent,
|
||||
&keys.read(pending.version).unwrap(),
|
||||
&issuer,
|
||||
true,
|
||||
);
|
||||
let response = reply(store.agent, &new);
|
||||
// Force the second SQL write to fail, after writing the certificate:
|
||||
// neither the cert nor selector may survive this aborted transaction.
|
||||
journal.connection().execute_batch("CREATE TEMP TRIGGER refuse_tls_commit BEFORE UPDATE OF current_version ON tls_rotation BEGIN SELECT RAISE(ABORT,'TEST_COMMIT_DENIED'); END;").unwrap();
|
||||
assert!(
|
||||
store
|
||||
.install(
|
||||
journal.connection_mut(),
|
||||
&keys,
|
||||
&recovered,
|
||||
&response,
|
||||
now()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.current(journal.connection(), &keys, now())
|
||||
.unwrap()
|
||||
.certificate_pem,
|
||||
old.as_bytes()
|
||||
);
|
||||
let staged: Option<Vec<u8>> = journal
|
||||
.connection()
|
||||
.query_row(
|
||||
"SELECT certificate FROM tls_versions WHERE version=?1",
|
||||
[pending.version.to_string()],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(staged.is_none());
|
||||
journal
|
||||
.connection()
|
||||
.execute_batch("DROP TRIGGER refuse_tls_commit;")
|
||||
.unwrap();
|
||||
store
|
||||
.install(
|
||||
journal.connection_mut(),
|
||||
&keys,
|
||||
&recovered,
|
||||
&response,
|
||||
now(),
|
||||
)
|
||||
.unwrap();
|
||||
drop(journal);
|
||||
let journal = crate::journal::Journal::open(&directory).unwrap();
|
||||
assert!(!store.has_pending(journal.connection()).unwrap());
|
||||
assert_eq!(
|
||||
store
|
||||
.current(journal.connection(), &keys, now())
|
||||
.unwrap()
|
||||
.certificate_pem,
|
||||
new.as_bytes()
|
||||
);
|
||||
// Windows SQLite holds byte-range locks in the live WAL/SHM files.
|
||||
// Release the database before inspecting its remaining raw files.
|
||||
drop(journal);
|
||||
for entry in std::fs::read_dir(&directory).unwrap() {
|
||||
let bytes = std::fs::read(entry.unwrap().path()).unwrap();
|
||||
assert!(
|
||||
!bytes
|
||||
.windows(b"PRIVATE KEY".len())
|
||||
.any(|s| s == b"PRIVATE KEY")
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
/// Deliberately selected fixture-only native I/O, never a default elevated
|
||||
/// operation. Uses the production KeyFiles implementation; no service,
|
||||
/// account, impersonation, installed state or network operation is involved.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
#[ignore = "explicit Windows administrator fixture; does not prove LocalService execution"]
|
||||
fn protected_key_files_create_new_reopen_acl_and_hardlink_guards() {
|
||||
use std::{fs, os::windows::ffi::OsStrExt, ptr};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW,
|
||||
CheckTokenMembership, CreateWellKnownSid, SECURITY_ATTRIBUTES,
|
||||
WinBuiltinAdministratorsSid,
|
||||
},
|
||||
Storage::FileSystem::CreateDirectoryW,
|
||||
};
|
||||
// The current token must already be an administrator. This fixture
|
||||
// never obtains or substitutes a different principal's token.
|
||||
let mut admin = [0usize; 16];
|
||||
let mut length = std::mem::size_of_val(&admin) as u32;
|
||||
let mut member = 0;
|
||||
assert!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
ptr::null_mut(),
|
||||
admin.as_mut_ptr().cast(),
|
||||
&mut length,
|
||||
)
|
||||
} != 0
|
||||
);
|
||||
assert!(
|
||||
unsafe {
|
||||
CheckTokenMembership(ptr::null_mut(), admin.as_mut_ptr().cast(), &mut member)
|
||||
} != 0
|
||||
&& member == 1
|
||||
);
|
||||
let service_sid = crate::native::service_sid().unwrap();
|
||||
let create_directory = |path: &std::path::Path, broad: bool| {
|
||||
let sddl = format!(
|
||||
"O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{service_sid}){}",
|
||||
if broad { "(A;OICI;FR;;;BU)" } else { "" }
|
||||
);
|
||||
let sddl: Vec<u16> = sddl.encode_utf16().chain(Some(0)).collect();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
assert!(
|
||||
unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
sddl.as_ptr(),
|
||||
1,
|
||||
&mut descriptor,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0
|
||||
);
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
let created = unsafe { CreateDirectoryW(wide.as_ptr(), &attributes) };
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
assert!(created != 0, "fresh protected fixture directory required");
|
||||
};
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("rmm-protected-key-fixture-{}", Uuid::new_v4()));
|
||||
create_directory(&root, false);
|
||||
// On failure retain this isolated case for the operator to inspect;
|
||||
// successful cleanup addresses only this newly created fixed namespace.
|
||||
let files = ProtectedKeyFiles::open(&root).unwrap();
|
||||
// A broad ACL is tested only on an empty, separate fixture directory;
|
||||
// no private key is ever written there.
|
||||
let broad = root.join("broad-empty");
|
||||
create_directory(&broad, true);
|
||||
let denied = match ProtectedKeyFiles::open(&broad) {
|
||||
Err(error) => error,
|
||||
Ok(_) => panic!("broad fixture DACL must be refused"),
|
||||
};
|
||||
assert_eq!(denied.to_string(), "PRIVATE_PATH_BROAD_ACL");
|
||||
fs::remove_dir(broad).unwrap();
|
||||
let version = Uuid::new_v4();
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let pem = key.serialize_pem();
|
||||
files.create(version, pem.as_bytes()).unwrap();
|
||||
let path = root.join(format!("device-{version}.key"));
|
||||
crate::native::private_path(&path, false).unwrap();
|
||||
let read = files.read(version).unwrap();
|
||||
// Never put private key bytes into assert_eq's panic formatter.
|
||||
assert!(read == pem.as_bytes(), "private key bytes changed");
|
||||
let parsed = KeyPair::from_pem(std::str::from_utf8(&read).unwrap()).unwrap();
|
||||
use sha2::{Digest, Sha256};
|
||||
assert_eq!(
|
||||
Sha256::digest(parsed.public_key_raw()),
|
||||
Sha256::digest(key.public_key_raw())
|
||||
);
|
||||
let duplicate = files
|
||||
.create(version, b"must not replace the key")
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
duplicate.downcast_ref::<std::io::Error>().unwrap().kind(),
|
||||
std::io::ErrorKind::AlreadyExists
|
||||
);
|
||||
assert!(files.read(version).unwrap() == pem.as_bytes());
|
||||
// The actual held directory handle must prevent rename while in use.
|
||||
assert!(fs::rename(&root, root.with_extension("renamed")).is_err());
|
||||
drop(files);
|
||||
let files = ProtectedKeyFiles::open(&root).unwrap();
|
||||
assert!(files.read(version).unwrap() == pem.as_bytes());
|
||||
let link = root.join("own-fixture-hardlink");
|
||||
fs::hard_link(&path, &link).unwrap();
|
||||
let denied = match files.read(version) {
|
||||
Err(error) => error,
|
||||
Ok(_) => panic!("hardlinked private key must be refused"),
|
||||
};
|
||||
assert_eq!(denied.to_string(), "ROTATION_FILE_TYPE_OR_LINKS");
|
||||
fs::remove_file(link).unwrap();
|
||||
assert!(files.read(version).unwrap() == pem.as_bytes());
|
||||
drop(files);
|
||||
fs::remove_file(path).unwrap();
|
||||
fs::remove_dir(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
//! No executor, startgrant consumer or privileged helper is advertised.
|
||||
#[cfg(windows)]
|
||||
pub mod actions;
|
||||
pub mod certificate_rotation;
|
||||
#[cfg(windows)]
|
||||
pub mod clock;
|
||||
pub mod event_log;
|
||||
|
||||
@@ -11,7 +11,12 @@ mod transport;
|
||||
mod wire_channel;
|
||||
#[cfg(windows)]
|
||||
mod certificate_rotation {
|
||||
pub use rmm_agent_windows::certificate_rotation::DeviceIdentity;
|
||||
// Shared transport input only. Windows certificate rotation is not yet a
|
||||
// capability: this first slice refuses expired TLS identities normally.
|
||||
pub struct DeviceIdentity {
|
||||
pub certificate_pem: Vec<u8>,
|
||||
pub private_key_pem: Vec<u8>,
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn main() {
|
||||
|
||||
@@ -7,7 +7,6 @@ use rmm_agent_core::{
|
||||
jobs, ledger,
|
||||
reconcile::{self, SyncClock},
|
||||
};
|
||||
use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore};
|
||||
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
|
||||
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
|
||||
use rmm_protocol::*;
|
||||
@@ -437,8 +436,6 @@ struct Agent {
|
||||
identity: EnrollmentResponse,
|
||||
ca: Vec<u8>,
|
||||
journal: Journal,
|
||||
certificates: RotationStore,
|
||||
key_files: ProtectedKeyFiles,
|
||||
boot: String,
|
||||
instance: String,
|
||||
started: Instant,
|
||||
@@ -1259,11 +1256,7 @@ impl Agent {
|
||||
let msi = job.action.windows_msi().cloned();
|
||||
let address = self.config.connect_address;
|
||||
let ca = self.ca.clone();
|
||||
let tls_identity = self.certificates.current(
|
||||
self.journal.connection(),
|
||||
&self.key_files,
|
||||
Utc::now().timestamp(),
|
||||
)?;
|
||||
let state = self.config.state_directory.clone();
|
||||
let request_for_stage = request.clone();
|
||||
let binding_for_stage = binding.clone();
|
||||
let worker = tokio::spawn(async move {
|
||||
@@ -1275,12 +1268,9 @@ impl Agent {
|
||||
"MSI_DOWNLOAD_FENCED"
|
||||
);
|
||||
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
|
||||
let tls = crate::https_channel::mtls_client(
|
||||
address,
|
||||
&ca,
|
||||
&tls_identity.certificate_pem,
|
||||
&tls_identity.private_key_pem,
|
||||
)?;
|
||||
let cert = protected_read(&state.join("device.pem"), 32768)?;
|
||||
let key = protected_read(&state.join("device.key"), 16384)?;
|
||||
let tls = crate::https_channel::mtls_client(address, &ca, &cert, &key)?;
|
||||
let response = tls
|
||||
.get(format!(
|
||||
"https://{}:{}/agent/v1/artifacts/{}?job_id={}&attempt_id={}",
|
||||
@@ -1546,15 +1536,6 @@ impl Agent {
|
||||
result
|
||||
}
|
||||
async fn session_inner(&mut self, stop: &AtomicBool) -> Result<()> {
|
||||
// Server commit may have fenced Hello even if its HTTP response was
|
||||
// lost. Recover the durable original CSR before requiring any channel.
|
||||
if self.certificates.has_pending(self.journal.connection())? {
|
||||
ensure!(
|
||||
!self.config.enable_jobs,
|
||||
"ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY"
|
||||
);
|
||||
self.renew_certificate().await?;
|
||||
}
|
||||
self.boot = native::boot_id().await?;
|
||||
let advertised = self.capabilities();
|
||||
let hello = self.envelope(
|
||||
@@ -1564,11 +1545,16 @@ impl Agent {
|
||||
capabilities: advertised.clone(),
|
||||
}),
|
||||
)?;
|
||||
let identity = self.certificates.current(
|
||||
self.journal.connection(),
|
||||
&self.key_files,
|
||||
Utc::now().timestamp(),
|
||||
)?;
|
||||
let identity = crate::certificate_rotation::DeviceIdentity {
|
||||
certificate_pem: protected_read(
|
||||
&self.config.state_directory.join("device.pem"),
|
||||
32768,
|
||||
)?,
|
||||
private_key_pem: protected_read(
|
||||
&self.config.state_directory.join("device.key"),
|
||||
16384,
|
||||
)?,
|
||||
};
|
||||
let mode = crate::wire_channel::Mode::parse(&self.config.transport)?;
|
||||
let mut channel = crate::wire_channel::connect(
|
||||
mode,
|
||||
@@ -1616,7 +1602,6 @@ impl Agent {
|
||||
let mut replay = Instant::now() - Duration::from_secs(10);
|
||||
let mut inventory = Instant::now();
|
||||
let mut update_at = Instant::now();
|
||||
let mut rotation_at = Instant::now();
|
||||
let mut heartbeat = Instant::now() - Duration::from_secs(60);
|
||||
let mut heartbeat_after = Duration::from_secs(30);
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
||||
@@ -1702,21 +1687,6 @@ impl Agent {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
continue;
|
||||
}
|
||||
// This slice renews only passive clients. Job admission and helper
|
||||
// lifecycle are not extended by certificate maintenance.
|
||||
if !self.config.enable_jobs && rotation_at.elapsed() >= Duration::from_secs(30) {
|
||||
rotation_at = Instant::now();
|
||||
let now = Utc::now().timestamp();
|
||||
if self
|
||||
.certificates
|
||||
.due(self.journal.connection(), &self.key_files, now)?
|
||||
{
|
||||
self.renew_certificate().await?;
|
||||
// The server fences the previous connection generation.
|
||||
// A new Hello/Sync uses the newly selected pair.
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if heartbeat.elapsed() >= heartbeat_after {
|
||||
#[cfg(feature = "system-helper")]
|
||||
if !self.config.enable_jobs
|
||||
@@ -1769,38 +1739,6 @@ impl Agent {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn renew_certificate(&mut self) -> Result<()> {
|
||||
ensure!(!self.config.enable_jobs, "PASSIVE_RENEWAL_ONLY");
|
||||
self.close_gate();
|
||||
let request = self.certificates.prepare(
|
||||
self.journal.connection_mut(),
|
||||
&self.key_files,
|
||||
Utc::now().timestamp(),
|
||||
)?;
|
||||
let client = crate::https_channel::mtls_client(
|
||||
self.config.connect_address,
|
||||
&self.ca,
|
||||
&request.identity.certificate_pem,
|
||||
&request.identity.private_key_pem,
|
||||
)?;
|
||||
let response = client
|
||||
.post(format!(
|
||||
"https://{}:{}/agent/v1/certificates/renew",
|
||||
crate::https_channel::server_name()?,
|
||||
self.config.connect_address.port()
|
||||
))
|
||||
.json(&serde_json::json!({"csr_pem":request.csr_pem}))
|
||||
.send()
|
||||
.await?;
|
||||
let bytes = crate::https_channel::bounded_body(response, 65536, "application/json").await?;
|
||||
self.certificates.install(
|
||||
self.journal.connection_mut(),
|
||||
&self.key_files,
|
||||
&request,
|
||||
&bytes,
|
||||
Utc::now().timestamp(),
|
||||
)
|
||||
}
|
||||
}
|
||||
fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
let arguments: Vec<String> = std::env::args().skip(1).collect();
|
||||
@@ -1843,11 +1781,6 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
import_legacy_inventory(&mut journal)?;
|
||||
}
|
||||
ensure!(!config.enable_jobs || binding.is_some(),"ENABLED_JOBS_REQUIRE_BINDING");
|
||||
let certificates=RotationStore::new(Uuid::parse_str(&identity.agent_id)?,binding.as_ref().map_or(1,|b|b.enrollment_generation),ca.clone())?;
|
||||
let key_files=ProtectedKeyFiles::open(&config.state_directory)?;
|
||||
certificates.initialize(journal.connection_mut(),&key_files,&protected_read(&config.state_directory.join("device.pem"),32768)?,Utc::now().timestamp())?;
|
||||
// SQLite and sidecars inherit the same service-SID-only state ACL.
|
||||
for child in fs::read_dir(&config.state_directory)? { let child=child?;native::private_path(&child.path(),child.file_type()?.is_dir())?; }
|
||||
let (ledger,ledger_file)=match &binding {Some(binding)=>{let (db,file)=open_ledger(&config.state_directory,binding)?;(Some(db),Some(file))},None=>(None,None)};
|
||||
let clock=JobClock::new(config.enable_jobs);
|
||||
let sync=if config.enable_jobs {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
|
||||
@@ -1857,8 +1790,6 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
identity,
|
||||
ca,
|
||||
journal,
|
||||
certificates,
|
||||
key_files,
|
||||
boot,
|
||||
instance: Uuid::new_v4().to_string(),
|
||||
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
|
||||
|
||||
@@ -32,5 +32,3 @@ libc = "0.2.177"
|
||||
rmm-updater-handoff = { path = "../updater-handoff" }
|
||||
base64 = "=0.22.1"
|
||||
hex.workspace = true
|
||||
|
||||
rmm-updater = { path = "../updater" }
|
||||
|
||||
@@ -1,966 +0,0 @@
|
||||
//! Passive authenticated catalog metadata only. No artifact request, preview,
|
||||
//! approval, staging, consumption, capability, service or filesystem write.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use openssl::{
|
||||
pkey::{Id, PKey},
|
||||
sign::Verifier,
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{Platform, ReleaseEnvelope, ReleaseManifest, UpdateKeyringFile},
|
||||
agent_update_provisioning::{
|
||||
BASELINE_SIGNATURE_DOMAIN, InstalledReleaseRecord, LocalUpdatePolicy,
|
||||
},
|
||||
jobs::hash,
|
||||
};
|
||||
use rmm_privileged_helper::{Binding, TrustedClock};
|
||||
use rmm_updater::{
|
||||
ActiveRelease, Platform as ReleasePlatform, ReleaseRelation, SignedRelease, TrustedContext,
|
||||
TrustedUpdateKey, UpdateKeyring, verify_release,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::Read,
|
||||
net::SocketAddr,
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt},
|
||||
path::{Path, PathBuf},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
#[cfg(test)]
|
||||
use uuid::Uuid;
|
||||
|
||||
const POLICY: &str = "/etc/rmm-agent-updater/policy.json";
|
||||
const KEYRING: &str = "/etc/rmm-agent-updater/keyring.json";
|
||||
const RECORD: &str = "/var/lib/rmm-agent-updater/installed-record.json";
|
||||
const RESPONSE_LIMIT: usize = 64 * 1024;
|
||||
const DAY: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
use rmm_domain::agent_update::{
|
||||
CatalogCandidate as Candidate, CatalogCheckReport as Report, CatalogCheckStatus as Status,
|
||||
};
|
||||
fn empty(status: Status) -> Report {
|
||||
Report {
|
||||
schema_version: 1,
|
||||
source_id: "mtls:release-catalog-v1".into(),
|
||||
checked_at: Utc::now(),
|
||||
status,
|
||||
candidate: None,
|
||||
}
|
||||
}
|
||||
/// Old servers already accept this ordinary bounded Linux observation shape.
|
||||
/// The outer timestamp says when the cache was read; checked_at is not restamped.
|
||||
pub fn observation(report: Report, collected_at: DateTime<Utc>) -> serde_json::Value {
|
||||
let (quality, error) = match report.status {
|
||||
Status::Available | Status::Current => ("valid", None),
|
||||
Status::NotConfigured => ("unknown", Some("UPDATE_CATALOG_NOT_CONFIGURED")),
|
||||
Status::Unavailable => ("error", Some("UPDATE_CATALOG_CHECK_UNAVAILABLE")),
|
||||
};
|
||||
serde_json::json!({"scope":"linux.agent_update.catalog","source_id":"agent:cached-release-catalog-v1",
|
||||
"observed_at":collected_at,"quality":quality,"completeness":"complete","truncated":false,
|
||||
"error_code":error,"data":report})
|
||||
}
|
||||
struct Pending {
|
||||
receiver: oneshot::Receiver<Report>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Pending {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Checker {
|
||||
report: Option<Report>,
|
||||
started: Option<Instant>,
|
||||
pending: Option<Pending>,
|
||||
}
|
||||
impl Checker {
|
||||
pub fn cached(&self, now: DateTime<Utc>) -> Option<Report> {
|
||||
self.report
|
||||
.as_ref()
|
||||
.filter(|report| report.validate(now, now))
|
||||
.cloned()
|
||||
}
|
||||
/// Called by the normal passive update collector. IO runs in a background
|
||||
/// task; a slow HTTPS peer never blocks heartbeat/cancel/control dispatch.
|
||||
pub fn poll(
|
||||
&mut self,
|
||||
binding: Option<&Binding>,
|
||||
clock: TrustedClock,
|
||||
address: SocketAddr,
|
||||
client: impl FnOnce() -> Result<reqwest::Client>,
|
||||
) -> Report {
|
||||
if let Some(pending) = &mut self.pending {
|
||||
match pending.receiver.try_recv() {
|
||||
Ok(report) => {
|
||||
self.report = Some(report);
|
||||
self.pending.take();
|
||||
}
|
||||
Err(oneshot::error::TryRecvError::Empty) => {}
|
||||
Err(oneshot::error::TryRecvError::Closed) => {
|
||||
self.report = Some(empty(Status::Unavailable));
|
||||
self.pending.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
let interval = if self
|
||||
.report
|
||||
.as_ref()
|
||||
.is_some_and(|r| matches!(r.status, Status::Available | Status::Current))
|
||||
{
|
||||
DAY
|
||||
} else {
|
||||
Duration::from_secs(60)
|
||||
};
|
||||
if self.pending.is_none() && self.started.is_none_or(|t| t.elapsed() >= interval) {
|
||||
self.started = Some(Instant::now());
|
||||
let prepared = binding
|
||||
.map(|binding| {
|
||||
Trust::load(
|
||||
binding,
|
||||
Path::new(POLICY),
|
||||
Path::new(KEYRING),
|
||||
Path::new(RECORD),
|
||||
)
|
||||
})
|
||||
.transpose();
|
||||
match prepared {
|
||||
Ok(None | Some(None)) => self.report = Some(empty(Status::NotConfigured)),
|
||||
Err(_) => self.report = Some(empty(Status::Unavailable)),
|
||||
Ok(Some(Some(trust))) => {
|
||||
let transport = if clock.trusted() {
|
||||
client()
|
||||
} else {
|
||||
Err(anyhow::anyhow!("UPDATE_CATALOG_CLOCK_UNTRUSTED"))
|
||||
};
|
||||
match transport {
|
||||
Err(_) => self.report = Some(empty(Status::Unavailable)),
|
||||
Ok(client) => {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(35),
|
||||
request(&client, address, &trust, &clock),
|
||||
)
|
||||
.await;
|
||||
let report = result
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.unwrap_or_else(|| empty(Status::Unavailable));
|
||||
let _ = sender.send(report);
|
||||
});
|
||||
self.pending = Some(Pending { receiver, task });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.report
|
||||
.clone()
|
||||
.unwrap_or_else(|| empty(Status::Unavailable))
|
||||
}
|
||||
}
|
||||
|
||||
/// Protected, public local records only. Missing provisioning is not an invitation
|
||||
/// to bootstrap trust from the HTTP response, current job or a writable file.
|
||||
struct Protected {
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
stamp: [u64; 10],
|
||||
raw: Vec<u8>,
|
||||
limit: usize,
|
||||
}
|
||||
fn stamp(m: &std::fs::Metadata) -> [u64; 10] {
|
||||
[
|
||||
m.dev(),
|
||||
m.ino(),
|
||||
m.uid().into(),
|
||||
m.gid().into(),
|
||||
m.mode().into(),
|
||||
m.len(),
|
||||
m.mtime() as u64,
|
||||
m.ctime() as u64,
|
||||
m.mtime_nsec() as u64,
|
||||
m.ctime_nsec() as u64,
|
||||
]
|
||||
}
|
||||
fn parents(path: &Path) -> Result<()> {
|
||||
ensure!(path.is_absolute(), "UPDATE_CATALOG_ANCHOR_PATH");
|
||||
for parent in path.ancestors().skip(1) {
|
||||
let m = std::fs::symlink_metadata(parent)?;
|
||||
ensure!(
|
||||
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0,
|
||||
"UPDATE_CATALOG_ANCHOR_PARENT"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl Protected {
|
||||
fn read(path: &Path, limit: usize) -> Result<Self> {
|
||||
parents(path)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
|
||||
.open(path)?;
|
||||
let m = file.metadata()?;
|
||||
ensure!(
|
||||
m.is_file()
|
||||
&& m.uid() == 0
|
||||
&& m.mode() & 0o022 == 0
|
||||
&& m.nlink() == 1
|
||||
&& m.len() > 0
|
||||
&& m.len() <= limit as u64,
|
||||
"UPDATE_CATALOG_ANCHOR_FILE"
|
||||
);
|
||||
let before = stamp(&m);
|
||||
let mut raw = Vec::new();
|
||||
(&mut file).take(limit as u64 + 1).read_to_end(&mut raw)?;
|
||||
ensure!(
|
||||
raw.len() as u64 == m.len() && stamp(&file.metadata()?) == before,
|
||||
"UPDATE_CATALOG_ANCHOR_CHANGED"
|
||||
);
|
||||
let result = Self {
|
||||
path: path.to_owned(),
|
||||
file,
|
||||
stamp: before,
|
||||
raw,
|
||||
limit,
|
||||
};
|
||||
ensure!(
|
||||
stamp(&std::fs::symlink_metadata(path)?) == result.stamp,
|
||||
"UPDATE_CATALOG_ANCHOR_REPLACED"
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
fn recheck(&self) -> Result<()> {
|
||||
let current = Self::read(&self.path, self.limit)?;
|
||||
ensure!(
|
||||
stamp(&self.file.metadata()?) == self.stamp
|
||||
&& current.stamp == self.stamp
|
||||
&& current.raw == self.raw,
|
||||
"UPDATE_CATALOG_ANCHOR_REPLACED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct Trust {
|
||||
files: Vec<Protected>,
|
||||
keys: UpdateKeyring,
|
||||
record: InstalledReleaseRecord,
|
||||
protocol: u32,
|
||||
state: u32,
|
||||
generation: u64,
|
||||
}
|
||||
impl Trust {
|
||||
fn load(binding: &Binding, policy: &Path, keys: &Path, record: &Path) -> Result<Option<Self>> {
|
||||
let result = (|| -> Result<Self> {
|
||||
let policy = Protected::read(policy, 65536)?;
|
||||
let (local, _) =
|
||||
LocalUpdatePolicy::from_bytes(&policy.raw).map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
local.keyring_path == KEYRING && local.installed_record_path == RECORD,
|
||||
"UPDATE_CATALOG_FIXED_ANCHOR_PATHS"
|
||||
);
|
||||
let keys = Protected::read(keys, 16384)?;
|
||||
let record = Protected::read(record, 32768)?;
|
||||
let result = Self::verify(binding, &policy.raw, &keys.raw, &record.raw)?;
|
||||
Ok(Self {
|
||||
files: vec![policy, keys, record],
|
||||
..result
|
||||
})
|
||||
})();
|
||||
match result {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
fn verify(
|
||||
binding: &Binding,
|
||||
policy_raw: &[u8],
|
||||
keys_raw: &[u8],
|
||||
record_raw: &[u8],
|
||||
) -> Result<Self> {
|
||||
let (policy, _) = LocalUpdatePolicy::from_bytes(policy_raw).map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
policy.tenant_id == binding.tenant_id
|
||||
&& policy.asset_id == binding.asset_id
|
||||
&& policy.agent_id == binding.agent_id
|
||||
&& policy.enrollment_generation == binding.enrollment_generation
|
||||
&& policy.assignment_version == binding.assignment_version,
|
||||
"UPDATE_CATALOG_LOCAL_IDENTITY"
|
||||
);
|
||||
let keys: UpdateKeyringFile = serde_json::from_slice(keys_raw)?;
|
||||
ensure!(keys.validate(), "UPDATE_CATALOG_KEYRING");
|
||||
let mut trusted = Vec::new();
|
||||
for key in &keys.keys {
|
||||
let public: [u8; 32] = hex::decode(&key.public_key_hex)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_CATALOG_KEY_SIZE"))?;
|
||||
ensure!(
|
||||
key.platform == Platform::LinuxX64 && key.public_key_hex != binding.public_key_hex,
|
||||
"UPDATE_CATALOG_KEY_SEPARATION"
|
||||
);
|
||||
trusted.push(TrustedUpdateKey::new(
|
||||
public,
|
||||
ReleasePlatform::LinuxX64,
|
||||
key.first_sequence,
|
||||
key.last_sequence,
|
||||
key.revoked,
|
||||
)?);
|
||||
}
|
||||
let keyring = UpdateKeyring::new(keys.generation, trusted)?;
|
||||
let baseline = policy
|
||||
.initial_baseline
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
// Only the independently signed bootstrap can currently authenticate
|
||||
// the floor here. Later Updated records require the separate guarded
|
||||
// Full history observer; do not guess a floor from parsed root JSON.
|
||||
ensure!(
|
||||
baseline.payload_bytes == record_raw
|
||||
&& hash(record_raw) == policy.initial_record_sha256,
|
||||
"UPDATE_CATALOG_GUARDED_HISTORY_REQUIRED"
|
||||
);
|
||||
let signer = keys
|
||||
.keys
|
||||
.iter()
|
||||
.find(|key| {
|
||||
hash(&hex::decode(&key.public_key_hex).unwrap_or_default())
|
||||
== policy.initial_baseline.key_id
|
||||
})
|
||||
.context("UPDATE_CATALOG_BASELINE_KEY")?;
|
||||
ensure!(!signer.revoked, "UPDATE_CATALOG_BASELINE_REVOKED");
|
||||
let public =
|
||||
PKey::public_key_from_raw_bytes(&hex::decode(&signer.public_key_hex)?, Id::ED25519)?;
|
||||
let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec();
|
||||
signed.extend_from_slice(&baseline.payload_bytes);
|
||||
ensure!(
|
||||
Verifier::new_without_digest(&public)?.verify_oneshot(&baseline.signature, &signed)?,
|
||||
"UPDATE_CATALOG_BASELINE_SIGNATURE"
|
||||
);
|
||||
let decoded = baseline
|
||||
.record
|
||||
.release_envelope
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let result = Self {
|
||||
files: vec![],
|
||||
keys: keyring,
|
||||
protocol: decoded.manifest.protocol_major,
|
||||
state: decoded.manifest.state_schema,
|
||||
generation: keys.generation,
|
||||
record: baseline.record,
|
||||
};
|
||||
result.release(&result.record.release_envelope, result.record.activated_at)?;
|
||||
Ok(result)
|
||||
}
|
||||
fn release(
|
||||
&self,
|
||||
envelope: &ReleaseEnvelope,
|
||||
now: u64,
|
||||
) -> Result<rmm_updater::VerifiedRelease> {
|
||||
let decoded = envelope.decode().map_err(anyhow::Error::msg)?;
|
||||
verify_release(
|
||||
SignedRelease {
|
||||
schema_version: envelope.schema_version,
|
||||
key_id: &envelope.key_id,
|
||||
payload_bytes: &decoded.payload_bytes,
|
||||
signature: &decoded.signature,
|
||||
},
|
||||
&self.keys,
|
||||
&TrustedContext {
|
||||
platform: ReleasePlatform::LinuxX64,
|
||||
now_utc_seconds: now,
|
||||
keyring_generation: self.generation,
|
||||
protocol_major: self.protocol,
|
||||
state_schema: self.state,
|
||||
updater_version: 1,
|
||||
minimum_release_sequence: self.record.activation_floor,
|
||||
active_release: Some(ActiveRelease {
|
||||
sequence: self.record.activation_floor,
|
||||
manifest_sha256: self.record.manifest_sha256.clone(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
fn response(&self, bytes: &[u8], now: DateTime<Utc>) -> Result<Report> {
|
||||
ensure!(
|
||||
!bytes.is_empty() && bytes.len() <= RESPONSE_LIMIT,
|
||||
"UPDATE_CATALOG_RESPONSE_LIMIT"
|
||||
);
|
||||
let response: CatalogResponse = serde_json::from_slice(bytes)?;
|
||||
ensure!(!response.job_created, "UPDATE_CATALOG_UNEXPECTED_JOB");
|
||||
match (response.status.as_str(), response.release) {
|
||||
("not_configured", None) => Ok(empty(Status::NotConfigured)),
|
||||
("available", Some(release)) => {
|
||||
ensure!(
|
||||
release
|
||||
.release_envelope
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?
|
||||
.manifest
|
||||
== release.manifest,
|
||||
"UPDATE_CATALOG_UNSIGNED_VIEW_CHANGED"
|
||||
);
|
||||
let verified =
|
||||
self.release(&release.release_envelope, u64::try_from(now.timestamp())?)?;
|
||||
let manifest = verified.manifest();
|
||||
Ok(Report {
|
||||
schema_version: 1,
|
||||
source_id: "mtls:release-catalog-v1".into(),
|
||||
checked_at: now,
|
||||
status: if verified.relation() == ReleaseRelation::SameActiveManifest {
|
||||
Status::Current
|
||||
} else {
|
||||
Status::Available
|
||||
},
|
||||
candidate: Some(Candidate {
|
||||
release_id: manifest.release_id,
|
||||
release_sequence: manifest.release_sequence,
|
||||
version: manifest.version.clone(),
|
||||
manifest_sha256: verified.manifest_sha256().into(),
|
||||
keyring_generation: verified.keyring_generation(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
_ => anyhow::bail!("UPDATE_CATALOG_RESPONSE_SHAPE"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CatalogResponse {
|
||||
status: String,
|
||||
release: Option<CatalogRelease>,
|
||||
#[serde(rename = "observed_at")]
|
||||
_observed_at: DateTime<Utc>,
|
||||
#[serde(rename = "server_time")]
|
||||
_server_time: DateTime<Utc>,
|
||||
job_created: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CatalogRelease {
|
||||
release_envelope: ReleaseEnvelope,
|
||||
manifest: ReleaseManifest,
|
||||
}
|
||||
async fn request(
|
||||
client: &reqwest::Client,
|
||||
address: SocketAddr,
|
||||
trust: &Trust,
|
||||
clock: &TrustedClock,
|
||||
) -> Result<Report> {
|
||||
ensure!(clock.trusted(), "UPDATE_CATALOG_CLOCK_UNTRUSTED");
|
||||
let bytes = fetch(client, address).await?;
|
||||
ensure!(clock.trusted(), "UPDATE_CATALOG_CLOCK_UNTRUSTED");
|
||||
for file in &trust.files {
|
||||
file.recheck()?;
|
||||
}
|
||||
trust.response(&bytes, Utc::now())
|
||||
}
|
||||
|
||||
async fn fetch(client: &reqwest::Client, address: SocketAddr) -> Result<Vec<u8>> {
|
||||
let response = client
|
||||
.get(format!(
|
||||
"https://{}:{}/agent/v1/releases/current?platform=x86_64-unknown-linux-gnu",
|
||||
crate::https_channel::server_name()?,
|
||||
address.port()
|
||||
))
|
||||
.send()
|
||||
.await?;
|
||||
crate::https_channel::bounded_body(response, RESPONSE_LIMIT, "application/json").await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use openssl::{
|
||||
pkey::Private,
|
||||
sign::Signer,
|
||||
ssl::{SslAcceptor, SslMethod, SslVerifyMode},
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{ArtifactDescriptor, ArtifactRole},
|
||||
agent_update_provisioning::{ActivationEvidence, SignedBaselineRecord},
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
io::Write,
|
||||
net::TcpListener,
|
||||
os::unix::fs::{PermissionsExt, symlink},
|
||||
};
|
||||
|
||||
fn envelope(
|
||||
key: &PKey<Private>,
|
||||
sequence: u64,
|
||||
protocol: u32,
|
||||
state: u32,
|
||||
expires: u64,
|
||||
) -> ReleaseEnvelope {
|
||||
let manifest = ReleaseManifest {
|
||||
schema_version: 1,
|
||||
release_id: Uuid::from_u128(sequence.into()),
|
||||
release_sequence: sequence,
|
||||
version: format!("test-{sequence}"),
|
||||
platform: Platform::LinuxX64,
|
||||
published_at: 1,
|
||||
expires_at: expires,
|
||||
protocol_major: protocol,
|
||||
state_schema: state,
|
||||
minimum_updater_version: 1,
|
||||
artifacts: [
|
||||
ArtifactDescriptor {
|
||||
role: ArtifactRole::Agent,
|
||||
artifact_id: Uuid::from_u128(100),
|
||||
sha256: hash(b"test agent"),
|
||||
bytes: 10,
|
||||
},
|
||||
ArtifactDescriptor {
|
||||
role: ArtifactRole::Helper,
|
||||
artifact_id: Uuid::from_u128(101),
|
||||
sha256: hash(b"test helper"),
|
||||
bytes: 11,
|
||||
},
|
||||
],
|
||||
};
|
||||
let raw = serde_json::to_vec(&manifest).unwrap();
|
||||
let mut signed = rmm_updater::RELEASE_SIGNATURE_DOMAIN.to_vec();
|
||||
signed.extend_from_slice(&raw);
|
||||
ReleaseEnvelope {
|
||||
schema_version: 1,
|
||||
key_id: hash(&key.raw_public_key().unwrap()),
|
||||
payload_bytes: URL_SAFE_NO_PAD.encode(raw),
|
||||
signature: URL_SAFE_NO_PAD.encode(
|
||||
Signer::new_without_digest(key)
|
||||
.unwrap()
|
||||
.sign_oneshot_to_vec(&signed)
|
||||
.unwrap(),
|
||||
),
|
||||
}
|
||||
}
|
||||
struct Fixture {
|
||||
trust: Trust,
|
||||
key: PKey<Private>,
|
||||
binding: Binding,
|
||||
policy: Vec<u8>,
|
||||
keys: Vec<u8>,
|
||||
record: Vec<u8>,
|
||||
}
|
||||
fn fixture() -> Fixture {
|
||||
let key = PKey::generate_ed25519().unwrap();
|
||||
let binding = Binding {
|
||||
tenant_id: Uuid::new_v4(),
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: Uuid::new_v4(),
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 2,
|
||||
public_key_hex: hex::encode(
|
||||
PKey::generate_ed25519().unwrap().raw_public_key().unwrap(),
|
||||
),
|
||||
};
|
||||
let release = envelope(&key, 7, 1, 1, u64::MAX);
|
||||
let record = InstalledReleaseRecord {
|
||||
schema_version: 1,
|
||||
profile: "decoder_compatible_handoff_v1".into(),
|
||||
platform: Platform::LinuxX64,
|
||||
manifest_sha256: hash(&release.decode().unwrap().payload_bytes),
|
||||
release_envelope: release,
|
||||
activation_floor: 7,
|
||||
activated_at: 2,
|
||||
previous_record_sha256: None,
|
||||
activation_evidence: ActivationEvidence::Bootstrap {
|
||||
qualification_receipt_sha256: hash(b"synthetic qualification"),
|
||||
},
|
||||
rolled_back: false,
|
||||
}
|
||||
.bytes()
|
||||
.unwrap();
|
||||
let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec();
|
||||
signed.extend_from_slice(&record);
|
||||
let baseline = SignedBaselineRecord {
|
||||
schema_version: 1,
|
||||
key_id: hash(&key.raw_public_key().unwrap()),
|
||||
payload_bytes: URL_SAFE_NO_PAD.encode(&record),
|
||||
signature: URL_SAFE_NO_PAD.encode(
|
||||
Signer::new_without_digest(&key)
|
||||
.unwrap()
|
||||
.sign_oneshot_to_vec(&signed)
|
||||
.unwrap(),
|
||||
),
|
||||
};
|
||||
let keys = serde_json::to_vec(&json!({"schema_version":1,"generation":4,"keys":[{"public_key_hex":hex::encode(key.raw_public_key().unwrap()),"platform":"x86_64-unknown-linux-gnu","first_sequence":1,"last_sequence":20,"revoked":false}]})).unwrap();
|
||||
let policy = serde_json::to_vec(&json!({"schema_version":1,"profile":"linux_general_full_v1","tenant_id":binding.tenant_id,"asset_id":binding.asset_id,"agent_id":binding.agent_id,"enrollment_generation":1,"assignment_version":2,
|
||||
"ledger_path":"/var/lib/rmm-helper/consumption.sqlite","lock_path":"/var/lib/rmm-helper/executor.lock","installed_record_path":RECORD,"keyring_path":KEYRING,"health_pin_path":"/etc/rmm-agent-updater/health-key.json","registry_path":"/etc/rmm-agent-updater/reader-registry.json","reader_registry_sha256":hash(b"fixture registry"),
|
||||
"services":[{"unit":"rmm-agent-remote.service","unit_sha256":hash(b"agent")},{"unit":"rmm-helper-cloud.service","unit_sha256":hash(b"general")},{"unit":"rmm-full-maintenance-helper.service","unit_sha256":hash(b"full")}],"updater_service":{"unit":"rmm-agent-updater.service","unit_sha256":hash(b"updater unit")},"updater_binary_sha256":hash(b"updater"),"initial_baseline":baseline,"initial_record_sha256":hash(&record),"initial_manifest_sha256":InstalledReleaseRecord::from_bytes(&record).unwrap().manifest_sha256,"initial_activation_floor":7})).unwrap();
|
||||
let trust = Trust::verify(&binding, &policy, &keys, &record).unwrap();
|
||||
Fixture {
|
||||
trust,
|
||||
key,
|
||||
binding,
|
||||
policy,
|
||||
keys,
|
||||
record,
|
||||
}
|
||||
}
|
||||
fn response(envelope: ReleaseEnvelope) -> Vec<u8> {
|
||||
serde_json::to_vec(&json!({"status":"available","release":{"manifest":envelope.decode().unwrap().manifest,"release_envelope":envelope},"observed_at":Utc::now(),"server_time":Utc::now(),"job_created":false})).unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn catalog_binds_real_release_signatures_floor_protocol_expiry_and_separate_baseline() {
|
||||
let f = fixture();
|
||||
let now = Utc::now();
|
||||
assert_eq!(
|
||||
f.trust
|
||||
.response(&response(envelope(&f.key, 8, 1, 1, u64::MAX)), now)
|
||||
.unwrap()
|
||||
.status,
|
||||
Status::Available
|
||||
);
|
||||
assert_eq!(
|
||||
f.trust
|
||||
.response(&response(envelope(&f.key, 7, 1, 1, u64::MAX)), now)
|
||||
.unwrap()
|
||||
.status,
|
||||
Status::Current
|
||||
);
|
||||
for release in [
|
||||
envelope(&f.key, 6, 1, 1, u64::MAX),
|
||||
envelope(&f.key, 8, 2, 1, u64::MAX),
|
||||
envelope(&f.key, 8, 1, 2, u64::MAX),
|
||||
envelope(&f.key, 8, 1, 1, 10),
|
||||
] {
|
||||
assert!(f.trust.response(&response(release), now).is_err());
|
||||
}
|
||||
let mut bad = envelope(&f.key, 8, 1, 1, u64::MAX);
|
||||
let mut signature = URL_SAFE_NO_PAD.decode(&bad.signature).unwrap();
|
||||
signature[0] ^= 1;
|
||||
bad.signature = URL_SAFE_NO_PAD.encode(signature);
|
||||
assert!(f.trust.response(&response(bad), now).is_err());
|
||||
let mut keys: serde_json::Value = serde_json::from_slice(&f.keys).unwrap();
|
||||
keys["keys"][0]["revoked"] = json!(true);
|
||||
assert!(
|
||||
Trust::verify(
|
||||
&f.binding,
|
||||
&f.policy,
|
||||
&serde_json::to_vec(&keys).unwrap(),
|
||||
&f.record
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut policy: serde_json::Value = serde_json::from_slice(&f.policy).unwrap();
|
||||
policy["initial_baseline"]["signature"] = json!("A".repeat(86));
|
||||
assert!(
|
||||
Trust::verify(
|
||||
&f.binding,
|
||||
&serde_json::to_vec(&policy).unwrap(),
|
||||
&f.keys,
|
||||
&f.record
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut binding = f.binding.clone();
|
||||
binding.public_key_hex = hex::encode(f.key.raw_public_key().unwrap());
|
||||
assert!(Trust::verify(&binding, &f.policy, &f.keys, &f.record).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn catalog_rejects_unsigned_view_extra_fields_and_unqualified_record_floor() {
|
||||
let f = fixture();
|
||||
let now = Utc::now();
|
||||
let raw = response(envelope(&f.key, 8, 1, 1, u64::MAX));
|
||||
for field in ["job", "view", "unknown", "missing"] {
|
||||
let mut changed: serde_json::Value = serde_json::from_slice(&raw).unwrap();
|
||||
match field {
|
||||
"job" => changed["job_created"] = json!(true),
|
||||
"view" => changed["release"]["manifest"]["version"] = json!("unsigned"),
|
||||
"unknown" => changed["trusted"] = json!(true),
|
||||
_ => changed["release"] = serde_json::Value::Null,
|
||||
}
|
||||
assert!(
|
||||
f.trust
|
||||
.response(&serde_json::to_vec(&changed).unwrap(), now)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
f.trust
|
||||
.response(&vec![b' '; RESPONSE_LIMIT + 1], now)
|
||||
.is_err()
|
||||
);
|
||||
let mut record = InstalledReleaseRecord::from_bytes(&f.record).unwrap();
|
||||
record.activated_at += 1;
|
||||
assert!(Trust::verify(&f.binding, &f.policy, &f.keys, &record.bytes().unwrap()).is_err());
|
||||
let mut binding = f.binding.clone();
|
||||
binding.assignment_version += 1;
|
||||
assert!(Trust::verify(&binding, &f.policy, &f.keys, &f.record).is_err());
|
||||
let empty = serde_json::to_vec(&json!({"status":"not_configured","release":null,"observed_at":now,"server_time":now,"job_created":false})).unwrap();
|
||||
assert_eq!(
|
||||
f.trust.response(&empty, now).unwrap().status,
|
||||
Status::NotConfigured
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn public_anchors_are_read_only_protected_and_missing_configuration_never_builds_client() {
|
||||
// Normal unprivileged cargo test exercises rejection without requiring
|
||||
// chown/sudo. An isolated root run additionally covers the genuine
|
||||
// protected positive file/recheck branch; report that coverage separately.
|
||||
let root_fixture = unsafe { libc::geteuid() } == 0;
|
||||
let root = if root_fixture {
|
||||
PathBuf::from("/run")
|
||||
} else {
|
||||
std::env::temp_dir()
|
||||
}
|
||||
.join(format!("rmm-catalog-test-{}", Uuid::new_v4()));
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let path = root.join("public.json");
|
||||
std::fs::write(&path, b"public synthetic trust bytes").unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let before = std::fs::metadata(&path).unwrap();
|
||||
if !root_fixture {
|
||||
assert!(Protected::read(&path, 128).is_err());
|
||||
assert_eq!(before.ino(), std::fs::metadata(&path).unwrap().ino());
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
} else {
|
||||
let held = Protected::read(&path, 128).unwrap();
|
||||
held.recheck().unwrap();
|
||||
assert_eq!(before.ino(), std::fs::metadata(&path).unwrap().ino());
|
||||
let alias = root.join("alias");
|
||||
symlink(&path, &alias).unwrap();
|
||||
assert!(Protected::read(&alias, 128).is_err());
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o622)).unwrap();
|
||||
assert!(Protected::read(&path, 128).is_err());
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
std::fs::write(&path, b"different synthetic public bytes").unwrap();
|
||||
assert!(held.recheck().is_err());
|
||||
drop(held);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
let mut checker = Checker::default();
|
||||
let report = checker.poll(
|
||||
None,
|
||||
TrustedClock::new(),
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
|| panic!("missing anchor must not load device TLS keys"),
|
||||
);
|
||||
assert_eq!(report.status, Status::NotConfigured);
|
||||
let again = checker.poll(
|
||||
None,
|
||||
TrustedClock::new(),
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
|| panic!("cadence must not create client"),
|
||||
);
|
||||
assert_eq!(report.checked_at, again.checked_at);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn actual_mtls_catalog_fetch_keeps_fixed_route_and_bounds_untrusted_http() {
|
||||
let f = fixture();
|
||||
let name = crate::https_channel::server_name().unwrap();
|
||||
let (ca, ca_key) = crate::runtime_tests::certificate("catalog test CA", None, false);
|
||||
let (server, server_key) =
|
||||
crate::runtime_tests::certificate(&name, Some((&ca, &ca_key)), true);
|
||||
let (device, device_key) =
|
||||
crate::runtime_tests::certificate("catalog test device", Some((&ca, &ca_key)), false);
|
||||
let cases = [
|
||||
("200 OK", response(envelope(&f.key, 8, 1, 1, u64::MAX))),
|
||||
("302 Found", b"no redirect".to_vec()),
|
||||
("200 OK", vec![b'x'; RESPONSE_LIMIT + 1]),
|
||||
];
|
||||
for (index, (status, body)) in cases.into_iter().enumerate() {
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls_server()).unwrap();
|
||||
acceptor.set_certificate(&server).unwrap();
|
||||
acceptor.set_private_key(&server_key).unwrap();
|
||||
acceptor.cert_store_mut().add_cert(ca.clone()).unwrap();
|
||||
acceptor.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let acceptor = acceptor.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let (socket, _) = listener.accept().unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut tls = acceptor.accept(socket).unwrap();
|
||||
assert!(tls.ssl().peer_certificate().is_some());
|
||||
let mut request = Vec::new();
|
||||
let mut byte = [0];
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
tls.read_exact(&mut byte).unwrap();
|
||||
request.push(byte[0]);
|
||||
assert!(request.len() < 8192);
|
||||
}
|
||||
let headers = String::from_utf8(request).unwrap();
|
||||
assert!(headers.starts_with(
|
||||
"GET /agent/v1/releases/current?platform=x86_64-unknown-linux-gnu HTTP/1.1\r\n"
|
||||
));
|
||||
assert!(!headers.to_ascii_lowercase().contains("authorization:"));
|
||||
let wire = format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nLocation: https://unexpected.invalid/\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
);
|
||||
tls.write_all(wire.as_bytes()).unwrap();
|
||||
let _ = tls.write_all(&body);
|
||||
});
|
||||
let client = crate::https_channel::mtls_client(
|
||||
address,
|
||||
&ca.to_pem().unwrap(),
|
||||
&device.to_pem().unwrap(),
|
||||
&device_key.private_key_to_pem_pkcs8().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let result = fetch(&client, address).await;
|
||||
if index == 0 {
|
||||
assert_eq!(
|
||||
f.trust
|
||||
.response(&result.unwrap(), Utc::now())
|
||||
.unwrap()
|
||||
.status,
|
||||
Status::Available
|
||||
);
|
||||
} else {
|
||||
assert!(result.is_err());
|
||||
}
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod wire_tests {
|
||||
use super::*;
|
||||
use prost::Message;
|
||||
use rmm_protocol::{Envelope, InventorySnapshot, Payload};
|
||||
use serde_json::json;
|
||||
use sha2::Digest;
|
||||
#[test]
|
||||
fn catalog_wire_shape_is_accepted_by_original_linux_observation_contract() {
|
||||
let original = include_bytes!("../../../tests/agent_update/catalog-check-inventory.json");
|
||||
let now = "2026-11-15T12:00:00Z".parse().unwrap();
|
||||
let stored =
|
||||
rmm_domain::inventory_document::validate_for_scope(original, now, "linux.base")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored,
|
||||
serde_json::from_slice::<serde_json::Value>(original).unwrap()
|
||||
);
|
||||
let report: Report =
|
||||
serde_json::from_value(stored["observations"][0]["data"].clone()).unwrap();
|
||||
let document = serde_json::to_vec(&report).unwrap();
|
||||
assert_eq!(serde_json::from_slice::<Report>(&document).unwrap(), report);
|
||||
assert!(report.validate(now, now));
|
||||
}
|
||||
#[test]
|
||||
fn normal_linux_snapshot_carries_cached_check_through_existing_scope_without_restamping_it() {
|
||||
let now = Utc::now();
|
||||
let report = Report {
|
||||
schema_version: 1,
|
||||
source_id: "mtls:release-catalog-v1".into(),
|
||||
checked_at: now - chrono::Duration::hours(2),
|
||||
status: Status::Unavailable,
|
||||
candidate: None,
|
||||
};
|
||||
let base = json!({"os":"Linux","hostname":"synthetic-codec","architecture":"x86_64","root_total_bytes":2,"root_available_bytes":1,"root_available_inodes":1,
|
||||
"collection_started_at":now,"collection_completed_at":now,"observations":[observation(report.clone(),now)]});
|
||||
let data = serde_json::to_vec(&base).unwrap();
|
||||
let envelope = Envelope {
|
||||
protocol_major: 1,
|
||||
protocol_minor: 0,
|
||||
message_id: Uuid::new_v4().to_string(),
|
||||
agent_id: Uuid::new_v4().to_string(),
|
||||
enrollment_generation: 1,
|
||||
connection_generation: 1,
|
||||
boot_id: Uuid::new_v4().to_string(),
|
||||
sequence: 1,
|
||||
observed_at: now.timestamp_millis(),
|
||||
payload: Some(Payload::InventorySnapshot(InventorySnapshot {
|
||||
snapshot_id: Uuid::new_v4().to_string(),
|
||||
scope: "linux.base".into(),
|
||||
schema_version: 1,
|
||||
chunk_index: 0,
|
||||
chunk_count: 1,
|
||||
sha256: sha2::Sha256::digest(&data).to_vec(),
|
||||
data,
|
||||
completeness: "partial".into(),
|
||||
})),
|
||||
};
|
||||
let decoded = Envelope::decode(envelope.encode_to_vec().as_slice()).unwrap();
|
||||
let Some(Payload::InventorySnapshot(snapshot)) = decoded.payload else {
|
||||
panic!("snapshot")
|
||||
};
|
||||
let stored = rmm_domain::inventory_document::validate_for_scope(
|
||||
&snapshot.data,
|
||||
now,
|
||||
&snapshot.scope,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stored, base);
|
||||
assert_eq!(
|
||||
stored["observations"][0]["data"]["checked_at"],
|
||||
json!(report.checked_at)
|
||||
);
|
||||
// Exact pre-existing outer keys/scopes: old validators already support
|
||||
// bounded generic linux.* observations; no agent.update extension is sent.
|
||||
assert!(!stored.as_object().unwrap().contains_key("catalog_check"));
|
||||
assert_eq!(
|
||||
stored["observations"][0]["scope"],
|
||||
"linux.agent_update.catalog"
|
||||
);
|
||||
for field in ["candidate", "schema", "time", "unknown"] {
|
||||
let mut bad = base.clone();
|
||||
match field {
|
||||
"candidate" => bad["observations"][0]["data"]["candidate"] = json!({}),
|
||||
"schema" => bad["observations"][0]["data"]["schema_version"] = json!(2),
|
||||
"time" => {
|
||||
bad["observations"][0]["data"]["checked_at"] =
|
||||
json!(now + chrono::Duration::seconds(2))
|
||||
}
|
||||
_ => bad["observations"][0]["data"]["ready"] = json!(true),
|
||||
}
|
||||
assert!(
|
||||
rmm_domain::inventory_document::validate_for_scope(
|
||||
&serde_json::to_vec(&bad).unwrap(),
|
||||
now,
|
||||
"linux.base"
|
||||
)
|
||||
.is_err(),
|
||||
"catalog field must be denied: {field}"
|
||||
);
|
||||
}
|
||||
let original = json!({"agent_update":rmm_domain::agent_update::AgentUpdateObservation::not_configured(Platform::LinuxX64,now)});
|
||||
assert!(
|
||||
rmm_domain::inventory_document::validate_for_scope(
|
||||
&serde_json::to_vec(&original).unwrap(),
|
||||
now,
|
||||
"agent.update"
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
let mut no_catalog = base;
|
||||
no_catalog.as_object_mut().unwrap().remove("observations");
|
||||
no_catalog
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("collection_started_at");
|
||||
no_catalog
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("collection_completed_at");
|
||||
assert!(
|
||||
rmm_domain::inventory_document::validate_for_scope(
|
||||
&serde_json::to_vec(&no_catalog).unwrap(),
|
||||
now,
|
||||
"linux.base"
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
mod agent_update_catalog;
|
||||
mod agent_update_health;
|
||||
mod apt;
|
||||
mod bootstrap;
|
||||
@@ -61,7 +60,6 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
mode: wire_channel::Mode,
|
||||
certificates: certificate_rotation::RotationStore,
|
||||
rotation_policy: certificate_rotation::RotationPolicy,
|
||||
catalog: agent_update_catalog::Checker,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct EffectFence {
|
||||
@@ -497,9 +495,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
let sender = self.inventory_tx.clone();
|
||||
let extended = env::var("RMM_EXTENDED_INVENTORY").unwrap_or_else(|_| "1".into()) == "1";
|
||||
let binding = self.binding.clone();
|
||||
let catalog = self.catalog.cached(Utc::now());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let collected_at = Utc::now();
|
||||
let result = rmm_agent_linux::wire::snapshot(extended).and_then(|mut inventory| {
|
||||
if extended {
|
||||
inventory["observations"]
|
||||
@@ -508,17 +504,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.push(apt::planning_observation(binding.as_ref()));
|
||||
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
|
||||
}
|
||||
if let Some(report) = catalog {
|
||||
if inventory.get("observations").is_none() {
|
||||
inventory["observations"] = serde_json::json!([]);
|
||||
inventory["collection_started_at"] = serde_json::json!(collected_at);
|
||||
}
|
||||
inventory["observations"]
|
||||
.as_array_mut()
|
||||
.context("INVENTORY_OBSERVATIONS")?
|
||||
.push(agent_update_catalog::observation(report, Utc::now()));
|
||||
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
|
||||
}
|
||||
let bytes = serde_json::to_vec(&inventory)?;
|
||||
ensure!(bytes.len() <= 512 * 1024, "INVENTORY_WIRE_LIMIT");
|
||||
Ok((bytes, Utc::now().timestamp_millis()))
|
||||
@@ -537,19 +522,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
rmm_domain::agent_update::Platform::LinuxX64,
|
||||
Utc::now(),
|
||||
);
|
||||
let address = self.address;
|
||||
let ca = &self.ca;
|
||||
let certificates = &self.certificates;
|
||||
self.catalog
|
||||
.poll(self.binding.as_ref(), self.clock.clone(), address, || {
|
||||
let identity = certificates.current(Utc::now().timestamp())?;
|
||||
https_channel::mtls_client(
|
||||
address,
|
||||
ca,
|
||||
&identity.certificate_pem,
|
||||
&identity.private_key_pem,
|
||||
)
|
||||
});
|
||||
let data = serde_json::to_vec(&serde_json::json!({"agent_update":observation}))?;
|
||||
let envelope = self.envelope(
|
||||
generation,
|
||||
@@ -1016,7 +988,6 @@ async fn main() -> Result<()> {
|
||||
mode,
|
||||
certificates,
|
||||
rotation_policy,
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
};
|
||||
agent.recover_interrupted()?;
|
||||
let mut backoff = 1_u64;
|
||||
|
||||
@@ -150,7 +150,6 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
mode: wire_channel::Mode::Wss,
|
||||
certificates,
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
};
|
||||
// A forged local consumption/start cannot become a purported grant result.
|
||||
agent
|
||||
@@ -220,7 +219,7 @@ impl reconcile::SyncClock for Clock {
|
||||
Ok(Utc::now())
|
||||
}
|
||||
}
|
||||
pub(super) fn certificate(
|
||||
fn certificate(
|
||||
name: &str,
|
||||
issuer: Option<(&X509, &PKey<openssl::pkey::Private>)>,
|
||||
server: bool,
|
||||
@@ -538,7 +537,6 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
|
||||
mode,
|
||||
certificates,
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
};
|
||||
for _ in 0..rounds {
|
||||
assert!(
|
||||
|
||||
@@ -780,63 +780,3 @@ pub fn job_health_public_key(job: &crate::jobs::JobPayload) -> Result<[u8; 32],
|
||||
.try_into()
|
||||
.map_err(|_| "UPDATE_HEALTH_KEY")
|
||||
}
|
||||
|
||||
/// Diagnostic catalog metadata inside the existing linux.base observations
|
||||
/// vector. This is never an AgentUpdateObservation/CandidatePreview or authority.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CatalogCheckStatus {
|
||||
NotConfigured,
|
||||
Unavailable,
|
||||
Available,
|
||||
Current,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CatalogCandidate {
|
||||
pub release_id: Uuid,
|
||||
pub release_sequence: u64,
|
||||
pub version: String,
|
||||
pub manifest_sha256: String,
|
||||
pub keyring_generation: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CatalogCheckReport {
|
||||
pub schema_version: u32,
|
||||
pub source_id: String,
|
||||
/// Actual authenticated check, not the later cache/inventory collection.
|
||||
pub checked_at: chrono::DateTime<chrono::Utc>,
|
||||
pub status: CatalogCheckStatus,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub candidate: Option<CatalogCandidate>,
|
||||
}
|
||||
impl CatalogCheckReport {
|
||||
pub fn validate(
|
||||
&self,
|
||||
collected_at: chrono::DateTime<chrono::Utc>,
|
||||
now: chrono::DateTime<chrono::Utc>,
|
||||
) -> bool {
|
||||
self.schema_version == 1
|
||||
&& self.source_id == "mtls:release-catalog-v1"
|
||||
&& self.checked_at <= collected_at + chrono::Duration::seconds(1)
|
||||
&& self.checked_at <= now + chrono::Duration::seconds(45)
|
||||
&& self.checked_at >= now - chrono::Duration::hours(72)
|
||||
&& match (&self.status, &self.candidate) {
|
||||
(CatalogCheckStatus::Available | CatalogCheckStatus::Current, Some(candidate)) => {
|
||||
!candidate.release_id.is_nil()
|
||||
&& candidate.release_sequence > 0
|
||||
&& candidate.keyring_generation > 0
|
||||
&& digest(&candidate.manifest_sha256)
|
||||
&& !candidate.version.is_empty()
|
||||
&& candidate.version.len() <= 64
|
||||
&& candidate
|
||||
.version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b))
|
||||
}
|
||||
(CatalogCheckStatus::NotConfigured | CatalogCheckStatus::Unavailable, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,8 +223,6 @@ pub struct LocalUpdatePolicy {
|
||||
pub installed_record_path: String,
|
||||
pub keyring_path: String,
|
||||
pub health_pin_path: String,
|
||||
pub registry_path: String,
|
||||
pub reader_registry_sha256: String,
|
||||
pub services: Vec<LocalServicePin>,
|
||||
pub updater_service: LocalServicePin,
|
||||
pub updater_binary_sha256: String,
|
||||
@@ -256,8 +254,6 @@ impl LocalUpdatePolicy {
|
||||
&& self.installed_record_path == "/var/lib/rmm-agent-updater/installed-record.json"
|
||||
&& self.keyring_path == "/etc/rmm-agent-updater/keyring.json"
|
||||
&& self.health_pin_path == "/etc/rmm-agent-updater/health-key.json"
|
||||
&& self.registry_path == "/etc/rmm-agent-updater/reader-registry.json"
|
||||
&& digest(&self.reader_registry_sha256)
|
||||
&& (names == SERVICES
|
||||
|| names
|
||||
== [
|
||||
|
||||
@@ -150,26 +150,6 @@ pub fn validate_for_scope(
|
||||
.data
|
||||
.get("host_reboot_required")
|
||||
.is_some_and(|v| !v.is_boolean());
|
||||
if o.scope == "linux.agent_update.catalog" {
|
||||
let report: crate::agent_update::CatalogCheckReport =
|
||||
serde_json::from_value(o.data.clone())
|
||||
.map_err(|_| "INVALID_AGENT_UPDATE_CATALOG_REPORT")?;
|
||||
let quality = match report.status {
|
||||
crate::agent_update::CatalogCheckStatus::Available
|
||||
| crate::agent_update::CatalogCheckStatus::Current => "valid",
|
||||
crate::agent_update::CatalogCheckStatus::NotConfigured => "unknown",
|
||||
crate::agent_update::CatalogCheckStatus::Unavailable => "error",
|
||||
};
|
||||
if scope != "linux.base"
|
||||
|| o.source_id != "agent:cached-release-catalog-v1"
|
||||
|| o.quality != quality
|
||||
|| o.completeness != "complete"
|
||||
|| o.truncated
|
||||
|| !report.validate(o.observed_at, now)
|
||||
{
|
||||
return Err("INVALID_AGENT_UPDATE_CATALOG_REPORT");
|
||||
}
|
||||
}
|
||||
if !o.scope.starts_with(prefix)
|
||||
|| o.scope.len() > 64
|
||||
|| !(o
|
||||
|
||||
@@ -128,7 +128,7 @@ async fn device_list(
|
||||
.map_err(|e| e.0)?;
|
||||
let mut page =
|
||||
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base') AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
.bind(asset)
|
||||
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
||||
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
|
||||
@@ -1,558 +0,0 @@
|
||||
//! Complete current FD/maps observations plus exact known process generations.
|
||||
//! This is one half of admission, never a replacement for the independently
|
||||
//! qualified closed bootstrap/service registry or actual singleton/flock guard.
|
||||
use crate::{
|
||||
agent_startup::{BoundAgentLock, HeldAgentLock},
|
||||
census_process::{Proc, Stamp},
|
||||
reader_registry::QualifiedRegistry,
|
||||
retained::{RetainedSet, Retention},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_updater_linux::{
|
||||
Budget,
|
||||
files::{Directory, Identity, LedgerGuard, LedgerIdentity},
|
||||
services::{HeldService, Service, ServiceProof, StoppedServices},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt},
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const PATHS: [&str; 5] = [
|
||||
"/var/lib/rmm-agent-remote/journal.sqlite",
|
||||
"/var/lib/rmm-agent-remote/consumption.sqlite",
|
||||
"/var/lib/rmm-helper/consumption.sqlite",
|
||||
"/var/lib/rmm-helper/executor.lock",
|
||||
"/var/lib/rmm-agent-remote/agent.lock",
|
||||
];
|
||||
/// Raw metadata only. Authority requires equality with the separately protected
|
||||
/// compatible-bootstrap registry; own-namespace == PID1 alone is insufficient.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HostContext {
|
||||
pub proc_device: u64,
|
||||
pub proc_inode: u64,
|
||||
pub user_namespace_device: u64,
|
||||
pub user_namespace_inode: u64,
|
||||
pub pid_namespace_device: u64,
|
||||
pub pid_namespace_inode: u64,
|
||||
pub cgroup_namespace_device: u64,
|
||||
pub cgroup_namespace_inode: u64,
|
||||
}
|
||||
pub fn current_host_context() -> Result<HostContext> {
|
||||
Proc::open()?.context()
|
||||
}
|
||||
struct Target {
|
||||
directory: Directory,
|
||||
file: File,
|
||||
identity: Identity,
|
||||
}
|
||||
/// Always the fixed three existing databases and two distinct existing locks.
|
||||
pub struct Targets {
|
||||
files: Vec<Target>,
|
||||
sha256: String,
|
||||
}
|
||||
impl Targets {
|
||||
pub fn bind(
|
||||
retained: &RetainedSet,
|
||||
ledger: &LedgerIdentity,
|
||||
agent: &BoundAgentLock,
|
||||
) -> Result<Self> {
|
||||
retained.verify()?;
|
||||
let specs = retained.specs();
|
||||
let mut files = Vec::new();
|
||||
for (index, path) in PATHS.iter().enumerate() {
|
||||
let expected = match index {
|
||||
3 => ledger.lock.clone(),
|
||||
4 => agent.identity().clone(),
|
||||
_ => {
|
||||
let spec = specs
|
||||
.iter()
|
||||
.find(|s| s.path == Path::new(path))
|
||||
.context("UPDATE_CENSUS_DATABASE_WITNESS_REQUIRED")?;
|
||||
ensure!(
|
||||
spec.retention == Retention::MutableDatabase,
|
||||
"UPDATE_CENSUS_DATABASE_WITNESS_REQUIRED"
|
||||
);
|
||||
if index == 2 {
|
||||
ensure!(
|
||||
spec.identity == ledger.ledger,
|
||||
"UPDATE_CENSUS_ROOT_LEDGER_CHANGED"
|
||||
);
|
||||
}
|
||||
spec.identity.clone()
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
expected.uid == if index < 2 || index == 4 { 993 } else { 0 }
|
||||
&& expected.mode & 0o022 == 0,
|
||||
"UPDATE_CENSUS_TARGET_PERMISSIONS"
|
||||
);
|
||||
let directory = Directory::open(
|
||||
Path::new(path)
|
||||
.parent()
|
||||
.context("UPDATE_CENSUS_TARGET_PARENT")?,
|
||||
expected.uid,
|
||||
true,
|
||||
)?;
|
||||
// O_PATH binds identity without reading any database/key contents.
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||
.open(path)?;
|
||||
files.push(Target {
|
||||
directory,
|
||||
file,
|
||||
identity: expected,
|
||||
});
|
||||
}
|
||||
let sha256 = hash(&serde_json::to_vec(
|
||||
&files.iter().map(|t| &t.identity).collect::<Vec<_>>(),
|
||||
)?);
|
||||
let result = Self { files, sha256 };
|
||||
result.verify()?;
|
||||
Ok(result)
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
ensure!(self.files.len() == 5, "UPDATE_CENSUS_TARGET_SET");
|
||||
for (target, path) in self.files.iter().zip(PATHS) {
|
||||
target.directory.verify()?;
|
||||
let held = target.file.metadata()?;
|
||||
let named = std::fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
held.is_file()
|
||||
&& named.is_file()
|
||||
&& !named.file_type().is_symlink()
|
||||
&& identity(&held) == target.identity
|
||||
&& identity(&named) == target.identity,
|
||||
"UPDATE_CENSUS_TARGET_REPLACED"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct Known {
|
||||
service: ServiceProof,
|
||||
stamp: Stamp,
|
||||
}
|
||||
/// Private observation, no Deserialize/Clone/caller completeness boolean.
|
||||
pub struct Admission {
|
||||
host: HostContext,
|
||||
targets_sha256: String,
|
||||
known: Vec<Known>,
|
||||
finished: Instant,
|
||||
summary: Summary,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Summary {
|
||||
schema_version: u32,
|
||||
phase: &'static str,
|
||||
targets_sha256: String,
|
||||
host_context_sha256: String,
|
||||
known_generations_sha256: String,
|
||||
pid_count: usize,
|
||||
fd_count: usize,
|
||||
map_count: usize,
|
||||
project_matches: Vec<Match>,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Match {
|
||||
pid: u32,
|
||||
birth: u64,
|
||||
target_indices: Vec<usize>,
|
||||
}
|
||||
pub struct Stopped {
|
||||
host: HostContext,
|
||||
targets_sha256: String,
|
||||
updater: ServiceProof,
|
||||
finished: Instant,
|
||||
summary: Summary,
|
||||
}
|
||||
pub struct ClosureInputs<'a, 'stopped> {
|
||||
pub targets: &'a Targets,
|
||||
pub root: &'a LedgerGuard<'stopped>,
|
||||
pub agent: &'a HeldAgentLock,
|
||||
pub stopped: &'a StoppedServices,
|
||||
pub updater: &'a HeldService,
|
||||
pub registry: &'a QualifiedRegistry,
|
||||
}
|
||||
/// The observed absence is retained only under continuously borrowed original
|
||||
/// singleton/flock guards. No freshness timestamp is renewed and no future
|
||||
/// noncooperating privileged process absence is claimed.
|
||||
pub struct ClosedReaders<'a, 'stopped> {
|
||||
proof: Stopped,
|
||||
input: ClosureInputs<'a, 'stopped>,
|
||||
}
|
||||
impl ClosedReaders<'_, '_> {
|
||||
pub fn verify(&self, budget: &Budget) -> Result<()> {
|
||||
self.input.registry.verify_protected()?;
|
||||
self.proof.verify_held(
|
||||
self.input.targets,
|
||||
self.input.root,
|
||||
self.input.agent,
|
||||
self.input.stopped,
|
||||
self.input.updater,
|
||||
budget,
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Admission {
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(hash(&serde_json::to_vec(&self.summary)?))
|
||||
}
|
||||
/// Must be called again by the exact live original authorizer immediately
|
||||
/// before consumption; a passive persisted hash cannot stand in for it.
|
||||
pub fn verify_fresh(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
known: &[&HeldService],
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1)
|
||||
&& self.targets_sha256 == targets.sha256,
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
known.len() == self.known.len(),
|
||||
"UPDATE_CENSUS_READER_SET_CHANGED"
|
||||
);
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == self.host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
for (held, old) in known.iter().zip(&self.known) {
|
||||
held.verify(budget)?;
|
||||
ensure!(
|
||||
*held.proof() == old.service && proc.process(old.stamp.pid)?.stamp == old.stamp,
|
||||
"UPDATE_CENSUS_READER_GENERATION_CHANGED"
|
||||
);
|
||||
}
|
||||
targets.verify()?;
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Stopped {
|
||||
pub fn bind<'a, 'stopped>(
|
||||
self,
|
||||
input: ClosureInputs<'a, 'stopped>,
|
||||
budget: &Budget,
|
||||
) -> Result<ClosedReaders<'a, 'stopped>> {
|
||||
input.registry.verify_protected()?;
|
||||
ensure!(
|
||||
*input.registry.host_context() == self.host,
|
||||
"UPDATE_CENSUS_REGISTRY_HOST_MISMATCH"
|
||||
);
|
||||
self.verify_fresh(
|
||||
input.targets,
|
||||
input.root,
|
||||
input.agent,
|
||||
input.stopped,
|
||||
input.updater,
|
||||
budget,
|
||||
)?;
|
||||
Ok(ClosedReaders { proof: self, input })
|
||||
}
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(hash(&serde_json::to_vec(&self.summary)?))
|
||||
}
|
||||
pub fn verify_fresh(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1)
|
||||
&& self.targets_sha256 == targets.sha256,
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
self.verify_held(targets, root, agent, stopped, updater, budget)?;
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn verify_held(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
targets.verify()?;
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
ensure!(
|
||||
self.targets_sha256 == targets.sha256
|
||||
&& targets.files[2].identity == root.identity().ledger
|
||||
&& targets.files[3].identity == root.identity().lock
|
||||
&& targets.files[4].identity == *agent.identity()
|
||||
&& *updater.proof() == self.updater
|
||||
&& current_host_context()? == self.host,
|
||||
"UPDATE_CENSUS_HELD_CLOSURE_CHANGED"
|
||||
);
|
||||
targets.verify()?;
|
||||
budget.check()
|
||||
}
|
||||
}
|
||||
pub fn scan_admission(
|
||||
targets: &Targets,
|
||||
known: &[&HeldService],
|
||||
qualified_host: &HostContext,
|
||||
budget: &Budget,
|
||||
) -> Result<Admission> {
|
||||
ensure!(
|
||||
known.iter().map(|s| s.proof().service).eq([
|
||||
Service::Agent,
|
||||
Service::General,
|
||||
Service::Full,
|
||||
Service::Updater
|
||||
]),
|
||||
"UPDATE_CENSUS_KNOWN_READERS"
|
||||
);
|
||||
targets.verify()?;
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == *qualified_host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_UNQUALIFIED"
|
||||
);
|
||||
let mut saved = Vec::new();
|
||||
for held in known {
|
||||
held.verify(budget)?;
|
||||
let process = proc.process(held.proof().process.pid)?;
|
||||
proc.verify_known_namespace(&process.stamp)?;
|
||||
bind_process(&process.stamp, held.proof())?;
|
||||
saved.push(Known {
|
||||
service: held.proof().clone(),
|
||||
stamp: process.stamp,
|
||||
});
|
||||
}
|
||||
ensure!(
|
||||
saved
|
||||
.iter()
|
||||
.filter(|s| s.stamp.pid == std::process::id()
|
||||
&& matches!(s.service.service, Service::Full | Service::Updater))
|
||||
.count()
|
||||
== 1,
|
||||
"UPDATE_CENSUS_AUTHORIZER_PROCESS_REQUIRED"
|
||||
);
|
||||
let summary = scan(&proc, targets, &saved, &[], "admission", budget)?;
|
||||
let finished = Instant::now();
|
||||
for (held, old) in known.iter().zip(&saved) {
|
||||
held.verify(budget)?;
|
||||
ensure!(
|
||||
proc.process(old.stamp.pid)?.stamp == old.stamp,
|
||||
"UPDATE_CENSUS_READER_CHANGED"
|
||||
);
|
||||
}
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
Ok(Admission {
|
||||
host: proc.context()?,
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
known: saved,
|
||||
finished,
|
||||
summary,
|
||||
})
|
||||
}
|
||||
pub fn scan_stopped(
|
||||
targets: &Targets,
|
||||
admission: &Admission,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<Stopped> {
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
admission.targets_sha256 == targets.sha256
|
||||
&& targets.files[2].identity == root.identity().ledger
|
||||
&& targets.files[3].identity == root.identity().lock
|
||||
&& targets.files[4].identity == *agent.identity()
|
||||
&& updater.proof().service == Service::Updater
|
||||
&& updater.proof().process.pid == std::process::id(),
|
||||
"UPDATE_CENSUS_STOPPED_LOCKS_OR_OWNER"
|
||||
);
|
||||
let old = stopped.proofs();
|
||||
ensure!(
|
||||
old.len() == 3
|
||||
&& old
|
||||
.iter()
|
||||
.zip(&admission.known)
|
||||
.all(|(s, k)| *s == k.service),
|
||||
"UPDATE_CENSUS_ORIGINAL_STOP_SET_CHANGED"
|
||||
);
|
||||
let original_updater = admission
|
||||
.known
|
||||
.last()
|
||||
.context("UPDATE_CENSUS_UPDATER_MISSING")?;
|
||||
ensure!(
|
||||
*updater.proof() == original_updater.service,
|
||||
"UPDATE_CENSUS_ORIGINAL_UPDATER_CHANGED"
|
||||
);
|
||||
let forbidden = admission.known[..3]
|
||||
.iter()
|
||||
.flat_map(|k| k.stamp.cgroup.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == admission.host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
proc.verify_known_namespace(&original_updater.stamp)?;
|
||||
let summary = scan(
|
||||
&proc,
|
||||
targets,
|
||||
std::slice::from_ref(original_updater),
|
||||
&forbidden,
|
||||
"stopped",
|
||||
budget,
|
||||
)?;
|
||||
let finished = Instant::now();
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
Ok(Stopped {
|
||||
host: admission.host.clone(),
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
updater: updater.proof().clone(),
|
||||
finished,
|
||||
summary,
|
||||
})
|
||||
}
|
||||
fn scan(
|
||||
proc: &Proc,
|
||||
targets: &Targets,
|
||||
allowed: &[Known],
|
||||
forbidden_cgroups: &[String],
|
||||
phase: &'static str,
|
||||
budget: &Budget,
|
||||
) -> Result<Summary> {
|
||||
let began = Instant::now();
|
||||
let pids = proc.pids(budget)?;
|
||||
let ids = targets
|
||||
.files
|
||||
.iter()
|
||||
.map(|t| t.identity.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut summary = Summary {
|
||||
schema_version: 1,
|
||||
phase,
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
host_context_sha256: hash(&serde_json::to_vec(&proc.context()?)?),
|
||||
known_generations_sha256: hash(&serde_json::to_vec(
|
||||
&allowed.iter().map(|k| &k.service).collect::<Vec<_>>(),
|
||||
)?),
|
||||
pid_count: pids.len(),
|
||||
fd_count: 0,
|
||||
map_count: 0,
|
||||
project_matches: Vec::new(),
|
||||
};
|
||||
for pid in &pids {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
began.elapsed() < Duration::from_secs(5),
|
||||
"UPDATE_CENSUS_TOTAL_DEADLINE"
|
||||
);
|
||||
let process = proc.process(*pid)?;
|
||||
let hits = process.inspect(&ids, budget)?;
|
||||
ensure!(
|
||||
!hits.task_cgroups.iter().any(|c| forbidden_cgroups
|
||||
.iter()
|
||||
.any(|old| c == old || c.starts_with(&(old.to_owned() + "/")))),
|
||||
"UPDATE_CENSUS_STOPPED_CGROUP_HAS_PROCESS"
|
||||
);
|
||||
summary.fd_count += hits.fd_count;
|
||||
summary.map_count += hits.map_count;
|
||||
let known = allowed.iter().find(|k| k.stamp.pid == *pid);
|
||||
if let Some(known) = known {
|
||||
ensure!(
|
||||
known.stamp == hits.stamp,
|
||||
"UPDATE_CENSUS_KNOWN_PROCESS_CHANGED"
|
||||
);
|
||||
}
|
||||
if !hits.descriptors.is_empty() || !hits.mappings.is_empty() {
|
||||
ensure!(known.is_some(), "UPDATE_CENSUS_UNKNOWN_READER");
|
||||
proc.verify_known_namespace(&hits.stamp)?;
|
||||
let mut indices = hits.descriptors;
|
||||
indices.extend(hits.mappings);
|
||||
indices.sort_unstable();
|
||||
indices.dedup();
|
||||
summary.project_matches.push(Match {
|
||||
pid: *pid,
|
||||
birth: hits.stamp.birth,
|
||||
target_indices: indices,
|
||||
});
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
proc.pids(budget)? == pids && began.elapsed() < Duration::from_secs(5),
|
||||
"UPDATE_CENSUS_INCOMPLETE_OR_CHANGED_PID_SET"
|
||||
);
|
||||
Ok(summary)
|
||||
}
|
||||
fn bind_process(stamp: &Stamp, service: &ServiceProof) -> Result<()> {
|
||||
ensure!(
|
||||
stamp.pid == service.process.pid
|
||||
&& stamp.birth == service.process.birth
|
||||
&& stamp.uid == service.process.uid
|
||||
&& stamp.gid == service.process.gid
|
||||
&& stamp.image.is_some(),
|
||||
"UPDATE_CENSUS_PINNED_PROCESS_CHANGED"
|
||||
);
|
||||
ensure!(
|
||||
stamp
|
||||
.cgroup
|
||||
.iter()
|
||||
.any(|p| p.rsplit('/').next() == Some(service.service.unit())),
|
||||
"UPDATE_CENSUS_SERVICE_CGROUP_UNBOUND"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn identity(meta: &std::fs::Metadata) -> Identity {
|
||||
Identity {
|
||||
device: meta.dev(),
|
||||
inode: meta.ino(),
|
||||
uid: meta.uid(),
|
||||
gid: meta.gid(),
|
||||
mode: meta.mode(),
|
||||
links: meta.nlink(),
|
||||
}
|
||||
}
|
||||
@@ -1,730 +0,0 @@
|
||||
//! Bounded kernel observations only. No command line/environment/key reads and
|
||||
//! no data from unrelated processes is returned. Not admission by itself.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_updater_linux::{Budget, files::Identity};
|
||||
use std::{
|
||||
ffi::CString,
|
||||
fs::File,
|
||||
io::Read,
|
||||
os::{
|
||||
fd::{AsRawFd, FromRawFd},
|
||||
unix::fs::MetadataExt,
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_PIDS: usize = 16384;
|
||||
const MAX_FDS: usize = 65536;
|
||||
const MAX_MAPS: usize = 8 * 1024 * 1024;
|
||||
const PROC_MAGIC: libc::c_long = 0x9fa0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Namespace {
|
||||
pub device: u64,
|
||||
pub inode: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Stamp {
|
||||
pub pid: u32,
|
||||
pub birth: u64,
|
||||
pub tgid: u32,
|
||||
pub uid: u32,
|
||||
pub gid: u32,
|
||||
pub image: Option<(u64, u64, i64, i64, i64, i64)>,
|
||||
pub cgroup: Vec<String>,
|
||||
pub user_ns: Namespace,
|
||||
pub pid_ns: Namespace,
|
||||
pub cgroup_ns: Namespace,
|
||||
}
|
||||
pub(crate) struct Process {
|
||||
pidfd: File,
|
||||
directory: File,
|
||||
pub stamp: Stamp,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Hits {
|
||||
pub stamp: Stamp,
|
||||
pub descriptors: Vec<usize>,
|
||||
pub mappings: Vec<usize>,
|
||||
pub fd_count: usize,
|
||||
pub task_cgroups: Vec<String>,
|
||||
pub map_count: usize,
|
||||
}
|
||||
|
||||
pub(crate) struct Proc {
|
||||
directory: File,
|
||||
user_ns: Namespace,
|
||||
pid_ns: Namespace,
|
||||
cgroup_ns: Namespace,
|
||||
}
|
||||
impl Proc {
|
||||
pub fn context(&self) -> Result<crate::census::HostContext> {
|
||||
let meta = self.directory.metadata()?;
|
||||
Ok(crate::census::HostContext {
|
||||
proc_device: meta.dev(),
|
||||
proc_inode: meta.ino(),
|
||||
user_namespace_device: self.user_ns.device,
|
||||
user_namespace_inode: self.user_ns.inode,
|
||||
pid_namespace_device: self.pid_ns.device,
|
||||
pid_namespace_inode: self.pid_ns.inode,
|
||||
cgroup_namespace_device: self.cgroup_ns.device,
|
||||
cgroup_namespace_inode: self.cgroup_ns.inode,
|
||||
})
|
||||
}
|
||||
pub fn open() -> Result<Self> {
|
||||
ensure!(
|
||||
unsafe { libc::geteuid() } == 0,
|
||||
"UPDATE_CENSUS_HOST_ROOT_REQUIRED"
|
||||
);
|
||||
let path = CString::new("/proc")?;
|
||||
let fd = unsafe {
|
||||
libc::open(
|
||||
path.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PROC_OPEN");
|
||||
let directory = unsafe { File::from_raw_fd(fd) };
|
||||
let mut info = std::mem::MaybeUninit::<libc::statfs>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatfs(directory.as_raw_fd(), info.as_mut_ptr()) } == 0
|
||||
&& unsafe { info.assume_init() }.f_type == PROC_MAGIC,
|
||||
"UPDATE_CENSUS_PROC_FILESYSTEM"
|
||||
);
|
||||
ensure!(
|
||||
directory.metadata()?.uid() == 0 && directory.metadata()?.mode() & 0o022 == 0,
|
||||
"UPDATE_CENSUS_PROC_OWNER"
|
||||
);
|
||||
let group = open_dir(&directory, &std::process::id().to_string())?;
|
||||
let tasks = open_dir(&group, "task")?;
|
||||
let tid = unsafe { libc::syscall(libc::SYS_gettid) };
|
||||
ensure!(tid > 0, "UPDATE_CENSUS_CURRENT_TASK");
|
||||
let own = open_dir(&tasks, &tid.to_string())?;
|
||||
let own_stamp = stamp(&own, u32::try_from(tid)?)?;
|
||||
ensure!(
|
||||
own_stamp.tgid == std::process::id() && own_stamp.uid == 0,
|
||||
"UPDATE_CENSUS_CURRENT_TASK_NOT_HOST_ROOT"
|
||||
);
|
||||
let init = open_dir(&directory, "1")?;
|
||||
let user_ns = namespace(&own, "user")?;
|
||||
let pid_ns = namespace(&own, "pid")?;
|
||||
let cgroup_ns = namespace(&own, "cgroup")?;
|
||||
ensure!(
|
||||
namespace(&init, "user")? == user_ns && namespace(&init, "pid")? == pid_ns,
|
||||
"UPDATE_CENSUS_NAMESPACE_NOT_HOST_VIEW"
|
||||
);
|
||||
// A hidden/subset proc mount cannot prove a complete PID enumeration.
|
||||
// Paths are examined only in memory; no mountinfo content is exported.
|
||||
let raw = read(&own, "mountinfo", 256 * 1024)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut count = 0;
|
||||
for row in text.lines() {
|
||||
let (left, right) = row.split_once(" - ").context("UPDATE_CENSUS_MOUNTINFO")?;
|
||||
let left = left.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
let right = right.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
ensure!(
|
||||
left.len() >= 6 && right.len() >= 3,
|
||||
"UPDATE_CENSUS_MOUNTINFO"
|
||||
);
|
||||
if left[4] == "/proc" {
|
||||
count += 1;
|
||||
ensure!(
|
||||
left[3] == "/"
|
||||
&& right[0] == "proc"
|
||||
&& left[5]
|
||||
.split(',')
|
||||
.chain(right[2].split(','))
|
||||
.all(|v| matches!(
|
||||
v,
|
||||
"rw" | "ro"
|
||||
| "nosuid"
|
||||
| "nodev"
|
||||
| "noexec"
|
||||
| "relatime"
|
||||
| "strictatime"
|
||||
| "noatime"
|
||||
| "nodiratime"
|
||||
| "hidepid=0"
|
||||
| "hidepid=off"
|
||||
)),
|
||||
"UPDATE_CENSUS_HIDDEN_OR_UNKNOWN_PROC_OPTIONS"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(count == 1, "UPDATE_CENSUS_PROC_MOUNT_AMBIGUOUS");
|
||||
Ok(Self {
|
||||
directory,
|
||||
user_ns,
|
||||
pid_ns,
|
||||
cgroup_ns,
|
||||
})
|
||||
}
|
||||
pub fn pids(&self, budget: &Budget) -> Result<Vec<u32>> {
|
||||
let mut pids = Vec::new();
|
||||
for entry in std::fs::read_dir(format!(
|
||||
"/proc/thread-self/fd/{}",
|
||||
self.directory.as_raw_fd()
|
||||
))? {
|
||||
budget.check()?;
|
||||
let name = entry?.file_name();
|
||||
let Some(name) = name.to_str() else {
|
||||
anyhow::bail!("UPDATE_CENSUS_PROC_ENTRY")
|
||||
};
|
||||
if name.bytes().all(|v| v.is_ascii_digit()) {
|
||||
let pid: u32 = name.parse()?;
|
||||
ensure!(pid > 0 && pids.len() < MAX_PIDS, "UPDATE_CENSUS_PID_LIMIT");
|
||||
pids.push(pid);
|
||||
}
|
||||
}
|
||||
pids.sort_unstable();
|
||||
ensure!(
|
||||
!pids.is_empty() && !pids.windows(2).any(|w| w[0] == w[1]),
|
||||
"UPDATE_CENSUS_PID_SET"
|
||||
);
|
||||
Ok(pids)
|
||||
}
|
||||
pub fn process(&self, pid: u32) -> Result<Process> {
|
||||
ensure!(pid > 0, "UPDATE_CENSUS_PID");
|
||||
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PIDFD_UNAVAILABLE");
|
||||
let pidfd = unsafe { File::from_raw_fd(fd as i32) };
|
||||
let directory = open_dir(&self.directory, &pid.to_string())?;
|
||||
let stamp = stamp(&directory, pid)?;
|
||||
let result = Process {
|
||||
pidfd,
|
||||
directory,
|
||||
stamp,
|
||||
};
|
||||
result.verify()?;
|
||||
Ok(result)
|
||||
}
|
||||
pub fn verify_known_namespace(&self, stamp: &Stamp) -> Result<()> {
|
||||
ensure!(
|
||||
stamp.user_ns == self.user_ns
|
||||
&& stamp.pid_ns == self.pid_ns
|
||||
&& stamp.cgroup_ns == self.cgroup_ns,
|
||||
"UPDATE_CENSUS_READER_NAMESPACE_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Process {
|
||||
pub fn verify(&self) -> Result<()> {
|
||||
let mut poll = libc::pollfd {
|
||||
fd: self.pidfd.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
ensure!(
|
||||
unsafe { libc::poll(&mut poll, 1, 0) } == 0
|
||||
&& poll.revents == 0
|
||||
&& stamp(&self.directory, self.stamp.pid)? == self.stamp,
|
||||
"UPDATE_CENSUS_PROCESS_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn inspect(&self, targets: &[Identity], budget: &Budget) -> Result<Hits> {
|
||||
self.verify()?;
|
||||
let task_dir = open_dir(&self.directory, "task")?;
|
||||
let tids = task_ids(&task_dir, budget)?;
|
||||
let mut held_tasks = Vec::new();
|
||||
let mut descriptors = Vec::new();
|
||||
let mut fd_count = 0;
|
||||
let mut task_cgroups = Vec::new();
|
||||
for tid in &tids {
|
||||
self.verify()?;
|
||||
let directory = open_dir(&task_dir, &tid.to_string())?;
|
||||
let before = stamp(&directory, *tid)?;
|
||||
ensure!(
|
||||
before.tgid == self.stamp.pid,
|
||||
"UPDATE_CENSUS_TASK_GROUP_CHANGED"
|
||||
);
|
||||
let (hits, count) = inspect_fds(&directory, targets, budget)?;
|
||||
fd_count += count;
|
||||
ensure!(fd_count <= MAX_FDS, "UPDATE_CENSUS_TOTAL_FD_LIMIT");
|
||||
if !hits.is_empty() {
|
||||
ensure!(
|
||||
before.uid == self.stamp.uid
|
||||
&& before.gid == self.stamp.gid
|
||||
&& before.user_ns == self.stamp.user_ns
|
||||
&& before.pid_ns == self.stamp.pid_ns
|
||||
&& before.cgroup_ns == self.stamp.cgroup_ns,
|
||||
"UPDATE_CENSUS_READER_TASK_CONTEXT_CHANGED"
|
||||
);
|
||||
}
|
||||
descriptors.extend(hits);
|
||||
task_cgroups.extend(before.cgroup.iter().cloned());
|
||||
ensure!(
|
||||
stamp(&directory, *tid)? == before,
|
||||
"UPDATE_CENSUS_TASK_CHANGED"
|
||||
);
|
||||
// Retain each actual task directory until the complete probe ends;
|
||||
// a same-TID replacement cannot substitute a new task directory.
|
||||
held_tasks.push((directory, before));
|
||||
}
|
||||
let raw = read(&self.directory, "maps", MAX_MAPS)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut mappings = Vec::new();
|
||||
let mut map_count = 0;
|
||||
for row in text.lines() {
|
||||
budget.check()?;
|
||||
map_count += 1;
|
||||
ensure!(map_count <= 65536, "UPDATE_CENSUS_MAP_LIMIT");
|
||||
let mut fields = row.split_ascii_whitespace();
|
||||
for _ in 0..3 {
|
||||
fields.next().context("UPDATE_CENSUS_MAP_FIELDS")?;
|
||||
}
|
||||
let (major, minor) = fields
|
||||
.next()
|
||||
.context("UPDATE_CENSUS_MAP_DEVICE")?
|
||||
.split_once(':')
|
||||
.context("UPDATE_CENSUS_MAP_DEVICE")?;
|
||||
let device = libc::makedev(
|
||||
u32::from_str_radix(major, 16)?,
|
||||
u32::from_str_radix(minor, 16)?,
|
||||
);
|
||||
let inode: u64 = fields.next().context("UPDATE_CENSUS_MAP_INODE")?.parse()?;
|
||||
if inode != 0 {
|
||||
for (index, target) in targets.iter().enumerate() {
|
||||
if device == target.device && inode == target.inode {
|
||||
mappings.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
descriptors.sort_unstable();
|
||||
descriptors.dedup();
|
||||
mappings.sort_unstable();
|
||||
mappings.dedup();
|
||||
ensure!(
|
||||
task_ids(&task_dir, budget)? == tids,
|
||||
"UPDATE_CENSUS_TASK_SET_CHANGED"
|
||||
);
|
||||
for (directory, before) in held_tasks {
|
||||
ensure!(
|
||||
stamp(&directory, before.pid)? == before,
|
||||
"UPDATE_CENSUS_TASK_CHANGED"
|
||||
);
|
||||
}
|
||||
task_cgroups.sort();
|
||||
task_cgroups.dedup();
|
||||
self.verify()?;
|
||||
Ok(Hits {
|
||||
stamp: self.stamp.clone(),
|
||||
descriptors,
|
||||
mappings,
|
||||
fd_count,
|
||||
task_cgroups,
|
||||
map_count,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn inspect_fds(
|
||||
directory: &File,
|
||||
targets: &[Identity],
|
||||
budget: &Budget,
|
||||
) -> Result<(Vec<usize>, usize)> {
|
||||
let fd_dir = open_dir(directory, "fd")?;
|
||||
let mut descriptors = Vec::new();
|
||||
let mut fd_count = 0;
|
||||
// Keep read_dir's descriptor alive while inspecting every magic link;
|
||||
// this also handles enumeration of our own descriptor without a gap.
|
||||
for entry in std::fs::read_dir(format!("/proc/thread-self/fd/{}", fd_dir.as_raw_fd()))? {
|
||||
budget.check()?;
|
||||
fd_count += 1;
|
||||
ensure!(fd_count <= MAX_FDS, "UPDATE_CENSUS_FD_LIMIT");
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
let name = name.to_str().context("UPDATE_CENSUS_FD_NAME")?;
|
||||
ensure!(
|
||||
!name.is_empty() && name.bytes().all(|v| v.is_ascii_digit()),
|
||||
"UPDATE_CENSUS_FD_NAME"
|
||||
);
|
||||
let name = CString::new(name)?;
|
||||
let mut info = std::mem::MaybeUninit::<libc::stat>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatat(fd_dir.as_raw_fd(), name.as_ptr(), info.as_mut_ptr(), 0) } == 0,
|
||||
"UPDATE_CENSUS_INCOMPLETE_FD"
|
||||
);
|
||||
let info = unsafe { info.assume_init() };
|
||||
for (index, target) in targets.iter().enumerate() {
|
||||
if info.st_dev == target.device && info.st_ino == target.inode {
|
||||
descriptors.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((descriptors, fd_count))
|
||||
}
|
||||
fn task_ids(directory: &File, budget: &Budget) -> Result<Vec<u32>> {
|
||||
let mut ids = Vec::new();
|
||||
for entry in std::fs::read_dir(format!("/proc/thread-self/fd/{}", directory.as_raw_fd()))? {
|
||||
budget.check()?;
|
||||
let name = entry?.file_name();
|
||||
let text = name.to_str().context("UPDATE_CENSUS_TASK_NAME")?;
|
||||
ensure!(
|
||||
!text.is_empty() && text.bytes().all(|v| v.is_ascii_digit()) && ids.len() < 4096,
|
||||
"UPDATE_CENSUS_TASK_LIMIT"
|
||||
);
|
||||
ids.push(text.parse()?);
|
||||
}
|
||||
ids.sort_unstable();
|
||||
ensure!(
|
||||
!ids.is_empty() && !ids.windows(2).any(|w| w[0] == w[1]),
|
||||
"UPDATE_CENSUS_TASK_SET"
|
||||
);
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn open_dir(parent: &File, name: &str) -> Result<File> {
|
||||
let name = CString::new(name)?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_DIRECTORY_UNAVAILABLE");
|
||||
Ok(unsafe { File::from_raw_fd(fd) })
|
||||
}
|
||||
fn read(parent: &File, name: &str, max: usize) -> Result<Vec<u8>> {
|
||||
let name = CString::new(name)?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PROC_DATA_UNAVAILABLE");
|
||||
let mut raw = Vec::new();
|
||||
unsafe { File::from_raw_fd(fd) }
|
||||
.take((max + 1) as u64)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= max, "UPDATE_CENSUS_PROC_DATA_LIMIT");
|
||||
Ok(raw)
|
||||
}
|
||||
fn namespace(parent: &File, kind: &str) -> Result<Namespace> {
|
||||
let name = CString::new(format!("ns/{kind}"))?;
|
||||
let mut info = std::mem::MaybeUninit::<libc::stat>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatat(parent.as_raw_fd(), name.as_ptr(), info.as_mut_ptr(), 0) } == 0,
|
||||
"UPDATE_CENSUS_NAMESPACE_UNAVAILABLE"
|
||||
);
|
||||
let info = unsafe { info.assume_init() };
|
||||
Ok(Namespace {
|
||||
device: info.st_dev,
|
||||
inode: info.st_ino,
|
||||
})
|
||||
}
|
||||
fn stamp(parent: &File, pid: u32) -> Result<Stamp> {
|
||||
let raw = read(parent, "stat", 65536)?;
|
||||
let raw = std::str::from_utf8(&raw)?;
|
||||
let (_, fields) = raw.rsplit_once(") ").context("UPDATE_CENSUS_STAT")?;
|
||||
let fields = fields.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
ensure!(fields.len() >= 20, "UPDATE_CENSUS_STAT");
|
||||
let birth = fields[19].parse()?;
|
||||
let flags: u64 = fields[6].parse()?;
|
||||
let raw = read(parent, "status", 65536)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let id = |label: &str| -> Result<u32> {
|
||||
let mut rows = text.lines().filter_map(|r| r.strip_prefix(label));
|
||||
let row = rows.next().context("UPDATE_CENSUS_CREDENTIALS")?;
|
||||
ensure!(rows.next().is_none(), "UPDATE_CENSUS_CREDENTIALS");
|
||||
let fields = row
|
||||
.split_ascii_whitespace()
|
||||
.map(str::parse)
|
||||
.collect::<std::result::Result<Vec<u32>, _>>()?;
|
||||
ensure!(
|
||||
fields.len() == 4 && fields.iter().all(|v| *v == fields[0]),
|
||||
"UPDATE_CENSUS_CHANGING_CREDENTIALS"
|
||||
);
|
||||
Ok(fields[0])
|
||||
};
|
||||
let uid = id("Uid:")?;
|
||||
let gid = id("Gid:")?;
|
||||
let mut tgids = text.lines().filter_map(|r| r.strip_prefix("Tgid:"));
|
||||
let tgid = tgids
|
||||
.next()
|
||||
.context("UPDATE_CENSUS_TASK_GROUP")?
|
||||
.trim()
|
||||
.parse()?;
|
||||
ensure!(tgids.next().is_none(), "UPDATE_CENSUS_TASK_GROUP");
|
||||
let name = CString::new("exe")?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_PATH | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
let image = if fd >= 0 {
|
||||
let file = unsafe { File::from_raw_fd(fd) };
|
||||
let meta = file.metadata()?;
|
||||
ensure!(meta.is_file(), "UPDATE_CENSUS_PROCESS_IMAGE");
|
||||
Some((
|
||||
meta.dev(),
|
||||
meta.ino(),
|
||||
meta.mtime(),
|
||||
meta.mtime_nsec(),
|
||||
meta.ctime(),
|
||||
meta.ctime_nsec(),
|
||||
))
|
||||
} else {
|
||||
ensure!(
|
||||
std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT)
|
||||
&& flags & 0x0020_0000 != 0,
|
||||
"UPDATE_CENSUS_PROCESS_IMAGE_UNAVAILABLE"
|
||||
);
|
||||
None
|
||||
};
|
||||
let raw = read(parent, "cgroup", 65536)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut cgroup = Vec::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(3, ':');
|
||||
fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
let path = fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
// Kernel cgroup paths are compared only as bounded opaque strings;
|
||||
// they are never used as filesystem paths. Host namespace authority
|
||||
// comes separately from the protected bootstrap registry.
|
||||
ensure!(
|
||||
path.starts_with('/') && path.len() <= 4096,
|
||||
"UPDATE_CENSUS_CGROUP"
|
||||
);
|
||||
cgroup.push(path.to_owned());
|
||||
}
|
||||
ensure!(
|
||||
!cgroup.is_empty() && cgroup.len() <= 64,
|
||||
"UPDATE_CENSUS_CGROUP"
|
||||
);
|
||||
Ok(Stamp {
|
||||
pid,
|
||||
birth,
|
||||
tgid,
|
||||
uid,
|
||||
gid,
|
||||
image,
|
||||
cgroup,
|
||||
user_ns: namespace(parent, "user")?,
|
||||
pid_ns: namespace(parent, "pid")?,
|
||||
cgroup_ns: namespace(parent, "cgroup")?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
os::unix::fs::OpenOptionsExt,
|
||||
time::Duration,
|
||||
};
|
||||
// The production census correctly denies a changing descriptor table.
|
||||
// Other parallel unit tests open/close files in this same test process;
|
||||
// exercise each actual /proc fixture in a separate exact-test process.
|
||||
fn in_isolated_fixture(name: &str) -> bool {
|
||||
const CHILD: &str = "RMM_CENSUS_EXACT_TEST_PROCESS";
|
||||
if std::env::var_os(CHILD).as_deref() == Some(std::ffi::OsStr::new(name)) {
|
||||
return true;
|
||||
}
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", name, "--test-threads=1"])
|
||||
.env(CHILD, name)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed"),
|
||||
"isolated census fixture: {:?}\n{}\n{}",
|
||||
output.status.code(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
false
|
||||
}
|
||||
#[test]
|
||||
fn private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe() {
|
||||
if !in_isolated_fixture(
|
||||
"census_process::tests::private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
assert_eq!(unsafe { libc::geteuid() }, 0);
|
||||
let path = std::path::Path::new("/run")
|
||||
.join(format!("rmm-census-thread-{}", uuid::Uuid::new_v4()));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_file(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(path.clone());
|
||||
let meta = file.metadata().unwrap();
|
||||
let target = Identity {
|
||||
device: meta.dev(),
|
||||
inode: meta.ino(),
|
||||
uid: meta.uid(),
|
||||
gid: meta.gid(),
|
||||
mode: meta.mode(),
|
||||
links: meta.nlink(),
|
||||
};
|
||||
let (ready, wait_ready) = std::sync::mpsc::channel();
|
||||
let (release, wait_release) = std::sync::mpsc::channel();
|
||||
let thread = std::thread::spawn(move || {
|
||||
// Only this owned fixture thread separates its descriptor table.
|
||||
// close_range(UNSHARE) is the same files-table operation without
|
||||
// Docker's unrelated unshare syscall gate. UINT_MAX cannot name
|
||||
// an open Linux fd, so no descriptor is closed. No namespace,
|
||||
// mount, machine policy, seccomp profile or service is changed.
|
||||
if unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_close_range,
|
||||
u32::MAX,
|
||||
u32::MAX,
|
||||
libc::CLOSE_RANGE_UNSHARE,
|
||||
)
|
||||
} != 0
|
||||
{
|
||||
ready
|
||||
.send(Err(std::io::Error::last_os_error().raw_os_error()))
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
let private = File::open(path).unwrap();
|
||||
ready.send(Ok(())).unwrap();
|
||||
let _ = wait_release.recv();
|
||||
drop(private);
|
||||
});
|
||||
struct Thread {
|
||||
release: Option<std::sync::mpsc::Sender<()>>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
impl Drop for Thread {
|
||||
fn drop(&mut self) {
|
||||
if let Some(tx) = self.release.take() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
if let Some(thread) = self.thread.take() {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
let thread = Thread {
|
||||
release: Some(release),
|
||||
thread: Some(thread),
|
||||
};
|
||||
assert_eq!(
|
||||
wait_ready.recv().unwrap(),
|
||||
Ok(()),
|
||||
"fixture requires close_range private-files-table support"
|
||||
);
|
||||
drop(file);
|
||||
let budget = Budget::new(
|
||||
fs::read_to_string("/proc/sys/kernel/random/boot_id")
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
let proc = Proc::open().unwrap();
|
||||
let process = proc.process(std::process::id()).unwrap();
|
||||
// Reproduces the incomplete TGID-only algorithm: no matching FD.
|
||||
assert!(
|
||||
inspect_fds(&process.directory, std::slice::from_ref(&target), &budget)
|
||||
.unwrap()
|
||||
.0
|
||||
.is_empty()
|
||||
);
|
||||
// The real complete probe must still find the reader's task table.
|
||||
let hits = process.inspect(&[target], &budget).unwrap();
|
||||
assert_eq!(hits.descriptors, [0]);
|
||||
assert!(hits.mappings.is_empty());
|
||||
drop(thread);
|
||||
}
|
||||
#[test]
|
||||
fn actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths() {
|
||||
if !in_isolated_fixture(
|
||||
"census_process::tests::actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// An isolated network-none container process, not a host-wide scan,
|
||||
// service/namespace qualification or admission-positive fixture.
|
||||
assert_eq!(unsafe { libc::geteuid() }, 0);
|
||||
let path =
|
||||
std::path::Path::new("/run").join(format!("rmm-census-probe-{}", uuid::Uuid::new_v4()));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.set_len(4096).unwrap();
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_file(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(path);
|
||||
let meta = file.metadata().unwrap();
|
||||
let target = Identity {
|
||||
device: meta.dev(),
|
||||
inode: meta.ino(),
|
||||
uid: meta.uid(),
|
||||
gid: meta.gid(),
|
||||
mode: meta.mode(),
|
||||
links: meta.nlink(),
|
||||
};
|
||||
let budget = Budget::new(
|
||||
fs::read_to_string("/proc/sys/kernel/random/boot_id")
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
let proc = Proc::open().unwrap();
|
||||
let process = proc.process(std::process::id()).unwrap();
|
||||
let before = process
|
||||
.inspect(std::slice::from_ref(&target), &budget)
|
||||
.unwrap();
|
||||
assert_eq!(before.descriptors, [0]);
|
||||
assert!(before.mappings.is_empty());
|
||||
let pointer = unsafe {
|
||||
libc::mmap(
|
||||
std::ptr::null_mut(),
|
||||
4096,
|
||||
libc::PROT_READ,
|
||||
libc::MAP_PRIVATE,
|
||||
file.as_raw_fd(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_ne!(pointer, libc::MAP_FAILED);
|
||||
struct Mapping(*mut libc::c_void);
|
||||
impl Drop for Mapping {
|
||||
fn drop(&mut self) {
|
||||
assert_eq!(unsafe { libc::munmap(self.0, 4096) }, 0);
|
||||
}
|
||||
}
|
||||
let _mapping = Mapping(pointer);
|
||||
drop(file);
|
||||
let mapped = process.inspect(&[target], &budget).unwrap();
|
||||
assert!(mapped.descriptors.is_empty());
|
||||
assert_eq!(mapped.mappings, [0]);
|
||||
assert_eq!(before.stamp, mapped.stamp);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,12 @@
|
||||
use crate::{
|
||||
agent_startup::BoundAgentLock,
|
||||
bridge::{BridgeContext, FullBridge, Generation},
|
||||
bundle, census,
|
||||
bundle,
|
||||
clock::NativeClock,
|
||||
fence::LedgerFence,
|
||||
ledger::{OwnedInputs, OwnedLedger},
|
||||
original::Original,
|
||||
participants::{StableParticipant, verify_original_helper},
|
||||
reader_registry::QualifiedRegistry,
|
||||
retained::RetainedSet,
|
||||
returned,
|
||||
trust::TrustState,
|
||||
@@ -22,7 +21,7 @@ use rmm_agent_core::{
|
||||
update_handoff::{NativeControlOperation, NativeEffect, NativeEffectClaim, NativeService},
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{ParticipantIdentity, ParticipantRole},
|
||||
agent_update::{ParticipantIdentity, ParticipantRole, UpdateInflightProof},
|
||||
agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy},
|
||||
jobs::hash,
|
||||
};
|
||||
@@ -76,7 +75,6 @@ impl Protected {
|
||||
pub struct Runtime {
|
||||
binding: Binding,
|
||||
policy: LocalUpdatePolicy,
|
||||
registry: QualifiedRegistry,
|
||||
policy_sha256: String,
|
||||
installed: InstalledReleaseRecord,
|
||||
installed_sha256: String,
|
||||
@@ -93,8 +91,12 @@ pub struct Runtime {
|
||||
head: Option<String>,
|
||||
}
|
||||
struct Queued {
|
||||
header: bundle::Header,
|
||||
agent_startup: BoundAgentLock,
|
||||
original: Original,
|
||||
witnesses: bundle::Loaded,
|
||||
trust: TrustState,
|
||||
budget: Budget,
|
||||
proof: UpdateInflightProof,
|
||||
}
|
||||
impl Runtime {
|
||||
pub fn new(binding: Binding) -> Result<Self> {
|
||||
@@ -115,7 +117,6 @@ impl Runtime {
|
||||
let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?;
|
||||
let installed_sha256 = hash(&raw);
|
||||
let old_policies = service_policies(&policy, &installed, None)?;
|
||||
let registry = QualifiedRegistry::load(&policy)?;
|
||||
let (health_file, raw) = Protected::read(&policy.health_pin_path, 4096)?;
|
||||
let health: HealthKeyPin = serde_json::from_slice(&raw)?;
|
||||
let health_key = health.public_key().map_err(anyhow::Error::msg)?;
|
||||
@@ -130,7 +131,6 @@ impl Runtime {
|
||||
Ok(Self {
|
||||
binding,
|
||||
policy,
|
||||
registry,
|
||||
policy_sha256,
|
||||
installed,
|
||||
installed_sha256,
|
||||
@@ -150,7 +150,7 @@ impl Runtime {
|
||||
/// A lost activation reply disables this live runtime before any stop.
|
||||
/// Drive is deliberately private: it cannot run inside Engine::handle.
|
||||
pub fn serve_one(&mut self, listener: &ipc::Listener) -> Result<()> {
|
||||
self.registry.verify_protected()?;
|
||||
self.require_reader_registry_and_census()?;
|
||||
ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED");
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
let budget = observation_budget()?;
|
||||
@@ -173,6 +173,12 @@ impl Runtime {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn require_reader_registry_and_census(&self) -> Result<()> {
|
||||
// This is an explicit source-checkpoint barrier, not a caller boolean
|
||||
// or a known-unit-list substitute. Replace only with the real protected
|
||||
// bootstrap registry + complete live FD/maps census and both locks.
|
||||
anyhow::bail!("UPDATE_READER_CENSUS_NOT_CONFIGURED")
|
||||
}
|
||||
fn enqueue(
|
||||
&mut self,
|
||||
peer: &ParticipantIdentity,
|
||||
@@ -210,33 +216,17 @@ impl Runtime {
|
||||
verify_original_helper(&services, &header.delegation, &budget)?;
|
||||
self.updater
|
||||
.verify_delegation(&header.delegation, &budget)?;
|
||||
// The original Full is still synchronously waiting for this reply.
|
||||
// Do not recursively query its socket or ledger in the Activate handler.
|
||||
self.queued = Some(Queued { header, budget });
|
||||
Ok(())
|
||||
}
|
||||
fn drive(&mut self, queued: Queued) -> Result<()> {
|
||||
let Queued { header, budget } = queued;
|
||||
for file in &self.protected {
|
||||
file.verify()?;
|
||||
}
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
verify_original_helper(&services, &header.delegation, &budget)?;
|
||||
self.updater
|
||||
.verify_delegation(&header.delegation, &budget)?;
|
||||
let reply = {
|
||||
let mut bridge = FullBridge::original(BridgeContext {
|
||||
handoff: &header.handoff,
|
||||
delegation: &header.delegation,
|
||||
services: &services,
|
||||
updater: &self.updater,
|
||||
clock: &self.clock,
|
||||
budget: &budget,
|
||||
health_public_key: self.health_key,
|
||||
generation: Generation::Original,
|
||||
})?;
|
||||
bridge.call(NativeControlOperation::ReadOriginal)?
|
||||
};
|
||||
let mut bridge = FullBridge::original(BridgeContext {
|
||||
handoff: &header.handoff,
|
||||
delegation: &header.delegation,
|
||||
services: &services,
|
||||
updater: &self.updater,
|
||||
clock: &self.clock,
|
||||
budget: &budget,
|
||||
health_public_key: self.health_key,
|
||||
generation: Generation::Original,
|
||||
})?;
|
||||
let reply = bridge.call(NativeControlOperation::ReadOriginal)?;
|
||||
let proof = reply.proof.context("UPDATE_ENGINE_ORIGINAL_PROOF")?;
|
||||
let original = Original::verify(
|
||||
&self.binding,
|
||||
@@ -266,19 +256,32 @@ impl Runtime {
|
||||
witnesses.retained.verify()?;
|
||||
let agent_startup = BoundAgentLock::bind(&witnesses.retained)?;
|
||||
self.head = Some(proof.head_sha256.clone());
|
||||
self.queued = Some(Queued {
|
||||
agent_startup,
|
||||
original,
|
||||
witnesses,
|
||||
trust,
|
||||
budget,
|
||||
proof,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn drive(&mut self, queued: Queued) -> Result<()> {
|
||||
let Queued {
|
||||
agent_startup,
|
||||
original,
|
||||
witnesses,
|
||||
trust,
|
||||
budget,
|
||||
proof,
|
||||
} = queued;
|
||||
original.check_current(&self.binding, &self.clock, &budget)?;
|
||||
trust.recheck(&original, &self.clock)?;
|
||||
self.registry.verify_admission(&self.policy, &budget)?;
|
||||
let held = [Service::Agent, Service::General, Service::Full]
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
let old = [Service::Agent, Service::General, Service::Full]
|
||||
.into_iter()
|
||||
.map(|s| services.observe(s, &budget))
|
||||
.map(|s| services.observe(s, &budget).map(|h| h.proof().clone()))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let known = vec![&held[0], &held[1], &held[2], self.updater.held_service()];
|
||||
let old = held.iter().map(|h| h.proof().clone()).collect::<Vec<_>>();
|
||||
let targets =
|
||||
census::Targets::bind(&witnesses.retained, &witnesses.ledger, &agent_startup)?;
|
||||
let admission =
|
||||
census::scan_admission(&targets, &known, self.registry.host_context(), &budget)?;
|
||||
let mut bridge = FullBridge::new(
|
||||
BridgeContext {
|
||||
handoff: original.handoff(),
|
||||
@@ -318,10 +321,6 @@ impl Runtime {
|
||||
updater: &self.updater,
|
||||
trust: &trust,
|
||||
retained: &witnesses.retained,
|
||||
registry: &self.registry,
|
||||
targets: &targets,
|
||||
admission: &admission,
|
||||
known: &known,
|
||||
claims,
|
||||
old,
|
||||
next: 0,
|
||||
@@ -332,30 +331,8 @@ impl Runtime {
|
||||
let claims = stop_fence.finish()?;
|
||||
let agent_startup = agent_startup.acquire(&stopped, &budget)?;
|
||||
let os = LedgerGuard::acquire(&stopped, &witnesses.ledger, &budget)?;
|
||||
self.registry.verify_stopped(&self.policy, &budget)?;
|
||||
let readers = census::scan_stopped(
|
||||
&targets,
|
||||
&admission,
|
||||
&os,
|
||||
&agent_startup,
|
||||
&stopped,
|
||||
self.updater.held_service(),
|
||||
&budget,
|
||||
)?;
|
||||
let readers = readers.bind(
|
||||
census::ClosureInputs {
|
||||
targets: &targets,
|
||||
root: &os,
|
||||
agent: &agent_startup,
|
||||
stopped: &stopped,
|
||||
updater: self.updater.held_service(),
|
||||
registry: &self.registry,
|
||||
},
|
||||
&budget,
|
||||
)?;
|
||||
let mut ledger = OwnedLedger::open(OwnedInputs {
|
||||
os: &os,
|
||||
readers: &readers,
|
||||
original: &original,
|
||||
binding: &self.binding,
|
||||
clock: &self.clock,
|
||||
@@ -414,9 +391,6 @@ impl Runtime {
|
||||
return Err(error);
|
||||
}
|
||||
let prepared = ledger.prepare_return_and_close()?;
|
||||
// The original DB is actually closed. End the continuous census/lock
|
||||
// borrow before the same concrete guard can be consumed by Return.
|
||||
drop(readers);
|
||||
let reservation = prepared.bind(returned::Inputs {
|
||||
original: &original,
|
||||
binding: &self.binding,
|
||||
@@ -516,10 +490,6 @@ struct StopFence<'a> {
|
||||
updater: &'a StableParticipant,
|
||||
trust: &'a TrustState,
|
||||
retained: &'a RetainedSet,
|
||||
registry: &'a QualifiedRegistry,
|
||||
targets: &'a census::Targets,
|
||||
admission: &'a census::Admission,
|
||||
known: &'a [&'a rmm_updater_linux::services::HeldService],
|
||||
claims: Vec<NativeEffectClaim>,
|
||||
old: Vec<ServiceProof>,
|
||||
next: usize,
|
||||
@@ -533,7 +503,6 @@ impl StopFence<'_> {
|
||||
self.updater
|
||||
.verify_delegation(self.original.delegation(), self.budget)?;
|
||||
self.trust.recheck(self.original, self.clock)?;
|
||||
self.registry.verify_protected()?;
|
||||
self.retained.verify()
|
||||
}
|
||||
fn finish(self) -> Result<Vec<NativeEffectClaim>> {
|
||||
@@ -553,10 +522,6 @@ impl DurableEffectFence for StopFence<'_> {
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.current()?;
|
||||
if self.next == 0 {
|
||||
self.admission
|
||||
.verify_fresh(self.targets, self.known, self.budget)?;
|
||||
}
|
||||
let service = [Service::Agent, Service::General, Service::Full][self.next];
|
||||
let native = [
|
||||
NativeService::Agent,
|
||||
|
||||
@@ -81,13 +81,7 @@ pub fn verify_history(
|
||||
let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec();
|
||||
signed.extend_from_slice(&initial.payload_bytes);
|
||||
verifier.verify_strict(&signed, &Signature::from_bytes(&initial.signature))?;
|
||||
verify_record_release(
|
||||
&keyring,
|
||||
protected_keyring.generation,
|
||||
&initial.record,
|
||||
initial_release.manifest.protocol_major,
|
||||
initial_release.manifest.state_schema,
|
||||
)?;
|
||||
verify_record_release(&keyring, protected_keyring.generation, &initial.record)?;
|
||||
|
||||
ensure!(
|
||||
predecessor_records.len() < MAX_RECORDS
|
||||
@@ -162,13 +156,7 @@ pub fn verify_history(
|
||||
&& record.activated_at >= parent.activated_at,
|
||||
"UPDATE_HISTORY_FLOOR_OR_ROLLBACK"
|
||||
);
|
||||
verify_record_release(
|
||||
&keyring,
|
||||
protected_keyring.generation,
|
||||
record,
|
||||
initial_release.manifest.protocol_major,
|
||||
initial_release.manifest.state_schema,
|
||||
)?;
|
||||
verify_record_release(&keyring, protected_keyring.generation, record)?;
|
||||
let grant = verify_update(db, guard, binding, raw, record, parent_digest, parent)?;
|
||||
ensure!(grants.insert(grant), "UPDATE_HISTORY_REUSED_GRANT");
|
||||
ensure!(*digest == hash(raw), "UPDATE_HISTORY_RECORD_CHANGED");
|
||||
@@ -292,8 +280,6 @@ fn verify_record_release(
|
||||
keys: &UpdateKeyring,
|
||||
generation: u64,
|
||||
record: &InstalledReleaseRecord,
|
||||
baseline_protocol_major: u32,
|
||||
baseline_state_schema: u32,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
!record.rolled_back,
|
||||
@@ -320,11 +306,8 @@ fn verify_record_release(
|
||||
platform,
|
||||
now_utc_seconds: record.activated_at,
|
||||
keyring_generation: generation,
|
||||
// Anchor compatibility to the separately signed, qualified
|
||||
// bootstrap. A signed successor cannot attest its own decoder
|
||||
// compatibility by supplying both sides of this comparison.
|
||||
protocol_major: baseline_protocol_major,
|
||||
state_schema: baseline_state_schema,
|
||||
protocol_major: decoded.manifest.protocol_major,
|
||||
state_schema: decoded.manifest.state_schema,
|
||||
updater_version: 1,
|
||||
minimum_release_sequence: record.activation_floor,
|
||||
active_release: Some(ActiveRelease {
|
||||
@@ -803,9 +786,6 @@ mod tests {
|
||||
active: Vec<u8>,
|
||||
}
|
||||
fn fixture() -> Fixture {
|
||||
fixture_target_contract(1, 1)
|
||||
}
|
||||
fn fixture_target_contract(protocol_major: u32, state_schema: u32) -> Fixture {
|
||||
let release = SigningKey::from_bytes(&[71; 32]); // public synthetic TEST seed
|
||||
let jobs = SigningKey::from_bytes(&[72; 32]);
|
||||
let health = SigningKey::from_bytes(&[73; 32]);
|
||||
@@ -821,13 +801,8 @@ mod tests {
|
||||
let Action::UpdateAgent { update } = &mut job.action else {
|
||||
panic!("fixture action")
|
||||
};
|
||||
let mut target_manifest = update.manifest().unwrap();
|
||||
target_manifest.protocol_major = protocol_major;
|
||||
target_manifest.state_schema = state_schema;
|
||||
let target = envelope(target_manifest, 2, &release);
|
||||
let target = envelope(update.manifest().unwrap(), 2, &release);
|
||||
let mut old = target.decode().unwrap().manifest;
|
||||
old.protocol_major = 1;
|
||||
old.state_schema = 1;
|
||||
old.release_id = update.predecessor.release_id;
|
||||
old.artifacts[0].artifact_id = Uuid::from_u128(901);
|
||||
old.artifacts[1].artifact_id = Uuid::from_u128(902);
|
||||
@@ -1429,150 +1404,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_successor_cannot_self_attest_compatibility_with_retained_baseline() {
|
||||
// These fixtures contain genuine release, baseline, job and health
|
||||
// signatures and a complete consumed/native publication chain. Only
|
||||
// the successor's decoder contract differs from the original baseline.
|
||||
for (protocol, schema, error) in [
|
||||
(2, 1, "incompatible release protocol"),
|
||||
(1, 2, "incompatible release state schema"),
|
||||
] {
|
||||
let f = fixture_target_contract(protocol, schema);
|
||||
let before = f.db.total_changes();
|
||||
let rejected = verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
&[],
|
||||
&f.active,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(rejected.to_string().contains(error), "{rejected:#}");
|
||||
assert_eq!(f.db.total_changes(), before);
|
||||
assert_eq!(
|
||||
InstalledReleaseRecord::from_bytes(&f.initial)
|
||||
.unwrap()
|
||||
.activation_floor,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
InstalledReleaseRecord::from_bytes(&f.active)
|
||||
.unwrap()
|
||||
.activation_floor,
|
||||
2
|
||||
);
|
||||
}
|
||||
let f = fixture();
|
||||
let before = f.db.total_changes();
|
||||
assert_eq!(
|
||||
verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
&[],
|
||||
&f.active,
|
||||
)
|
||||
.unwrap()
|
||||
.bytes()
|
||||
.unwrap(),
|
||||
f.active
|
||||
);
|
||||
assert_eq!(f.db.total_changes(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_predecessor_is_not_a_rollback_receipt_and_unknown_stays_closed() {
|
||||
let f = fixture();
|
||||
// Even a genuine release-signed exact predecessor with the retained
|
||||
// higher floor is only metadata. V1 has no rollback activation witness.
|
||||
let active = InstalledReleaseRecord::from_bytes(&f.active).unwrap();
|
||||
let mut returned = InstalledReleaseRecord::from_bytes(&f.initial).unwrap();
|
||||
returned.activation_floor = active.activation_floor;
|
||||
returned.activated_at = active.activated_at + 1;
|
||||
returned.previous_record_sha256 = Some(hash(&f.active));
|
||||
returned.activation_evidence = active.activation_evidence.clone();
|
||||
returned.rolled_back = true;
|
||||
let returned = returned.bytes().unwrap();
|
||||
let before = f.db.total_changes();
|
||||
assert!(
|
||||
verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
std::slice::from_ref(&f.active),
|
||||
&returned,
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("UPDATE_HISTORY_FLOOR_OR_ROLLBACK")
|
||||
);
|
||||
assert!(
|
||||
verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
&[],
|
||||
&f.initial,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(f.db.total_changes(), before);
|
||||
assert_eq!(
|
||||
InstalledReleaseRecord::from_bytes(&returned)
|
||||
.unwrap()
|
||||
.activation_floor,
|
||||
2
|
||||
);
|
||||
|
||||
// A previously stored Unknown is never reclassified from a retained
|
||||
// healthy target or a proposed predecessor return. This is a synthetic
|
||||
// local fixture mutation; the verifier itself performs no writes.
|
||||
let unknown = serde_json::to_vec(&Outcome::unknown("synthetic unresolved update")).unwrap();
|
||||
f.db.execute("UPDATE execution_evidence SET outcome=?1", [&unknown])
|
||||
.unwrap();
|
||||
f.db.execute("UPDATE consumed SET result=?1", [&unknown])
|
||||
.unwrap();
|
||||
let before = f.db.total_changes();
|
||||
assert!(
|
||||
verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
&[],
|
||||
&f.active,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
verify_history(
|
||||
&f.db,
|
||||
&f.guard,
|
||||
&f.binding,
|
||||
&f.keys,
|
||||
&f.baseline,
|
||||
std::slice::from_ref(&f.active),
|
||||
&returned,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let retained: Vec<u8> =
|
||||
f.db.query_row("SELECT outcome FROM execution_evidence", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(retained, unknown);
|
||||
assert_eq!(f.db.total_changes(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
//! OS guard confirms every reader stopped. This module performs no bootstrap,
|
||||
//! consumption, schema reset, outcome healing or readiness transition.
|
||||
use crate::{
|
||||
census::ClosedReaders, clock::NativeClock, files::FileWitnesses, original::Original,
|
||||
participants::StableParticipant, retained::RetainedSet, returned::PreparedReservation,
|
||||
trust::TrustState,
|
||||
clock::NativeClock, files::FileWitnesses, original::Original, participants::StableParticipant,
|
||||
retained::RetainedSet, returned::PreparedReservation, trust::TrustState,
|
||||
};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
@@ -42,7 +41,6 @@ fn file_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole {
|
||||
|
||||
pub struct OwnedGuard<'a, 'stopped> {
|
||||
os: &'a LedgerGuard<'stopped>,
|
||||
readers: &'a ClosedReaders<'a, 'stopped>,
|
||||
original: &'a Original,
|
||||
binding: &'a Binding,
|
||||
clock: &'a NativeClock,
|
||||
@@ -56,7 +54,6 @@ pub struct OwnedGuard<'a, 'stopped> {
|
||||
}
|
||||
pub struct OwnedInputs<'a, 'stopped> {
|
||||
pub os: &'a LedgerGuard<'stopped>,
|
||||
pub readers: &'a ClosedReaders<'a, 'stopped>,
|
||||
pub original: &'a Original,
|
||||
pub binding: &'a Binding,
|
||||
pub clock: &'a NativeClock,
|
||||
@@ -73,7 +70,6 @@ pub struct OwnedLedger<'a, 'stopped> {
|
||||
}
|
||||
impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
pub fn open(input: OwnedInputs<'a, 'stopped>) -> Result<Self> {
|
||||
input.readers.verify(&observation_budget()?)?;
|
||||
input.os.verify_for_effect(&observation_budget()?)?;
|
||||
ensure!(
|
||||
input.os.identity().sha256()? == input.original.handoff().ledger_identity_sha256
|
||||
@@ -96,7 +92,6 @@ impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
input.files.bind(input.original.handoff())?;
|
||||
let guard = OwnedGuard {
|
||||
os: input.os,
|
||||
readers: input.readers,
|
||||
original: input.original,
|
||||
binding: input.binding,
|
||||
clock: input.clock,
|
||||
@@ -295,7 +290,6 @@ impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
impl ExecutorLedgerGuard for OwnedGuard<'_, '_> {
|
||||
fn check(&self, db: &Connection) -> Result<()> {
|
||||
let observation = observation_budget()?;
|
||||
self.readers.verify(&observation)?;
|
||||
self.os.verify_for_effect(&observation)?;
|
||||
ensure!(
|
||||
unsafe { db.handle() } as usize == self.sqlite_handle,
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
pub mod agent_startup;
|
||||
pub mod bridge;
|
||||
pub mod bundle;
|
||||
pub mod census;
|
||||
mod census_process;
|
||||
pub mod clock;
|
||||
pub mod engine;
|
||||
pub mod fence;
|
||||
@@ -15,7 +13,6 @@ pub mod history;
|
||||
pub mod ledger;
|
||||
pub mod original;
|
||||
pub mod participants;
|
||||
pub mod reader_registry;
|
||||
pub mod record;
|
||||
pub mod retained;
|
||||
pub mod returned;
|
||||
|
||||
@@ -43,9 +43,6 @@ impl StableParticipant {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn held_service(&self) -> &HeldService {
|
||||
&self.held
|
||||
}
|
||||
pub fn identity(&self) -> &ParticipantIdentity {
|
||||
&self.identity
|
||||
}
|
||||
|
||||
@@ -1,835 +0,0 @@
|
||||
//! Protected compatible-reader registry plus read-only systemd closure.
|
||||
//! This does not replace complete current task/FD/maps census, both real locks,
|
||||
//! original authorization or live process/image proofs. No future-exec promise.
|
||||
use crate::census::{HostContext, current_host_context};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::{
|
||||
agent_update::digest,
|
||||
agent_update_provisioning::{ActivationEvidence, LocalUpdatePolicy},
|
||||
jobs::hash,
|
||||
};
|
||||
use rmm_updater_linux::{
|
||||
Budget,
|
||||
files::{Directory, FileProof, HeldFile},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs::Metadata,
|
||||
io::Read,
|
||||
os::{
|
||||
fd::{AsRawFd, FromRawFd},
|
||||
unix::fs::MetadataExt,
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Command, Stdio},
|
||||
sync::Mutex,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub const READER_CONTRACT: &[u8] = b"rmm.linux-shared-readers.v1\0root-helper:existing-executor.lock-before-sqlite-open-and-every-sql-or-effect-operation;agent:existing-agent.lock-before-both-agent-sqlite-opens-and-held-for-process-lifetime;all-allowed-readers:update-handoff-inflight-decoder-compatible;admission:protected-bootstrap-plus-current-complete-task-fd-maps-census-and-both-original-locks;scope:no-global-future-exec-absence-promise\n";
|
||||
pub fn reader_contract_sha256() -> String {
|
||||
hash(READER_CONTRACT)
|
||||
}
|
||||
const REGISTRY: &str = "/etc/rmm-agent-updater/reader-registry.json";
|
||||
const MAX_BYTES: u64 = 65536;
|
||||
const MAX_ROLLBACK: usize = 32;
|
||||
const MAX_FILES: usize = 128;
|
||||
const SERVICES: [&str; 7] = [
|
||||
"rmm-agent-remote.service",
|
||||
"rmm-helper-cloud.service",
|
||||
"rmm-full-maintenance-helper.service",
|
||||
"rmm-agent-updater.service",
|
||||
"rmm-apt-helper.service",
|
||||
"rmm-agent.service",
|
||||
"rmm-helper-dev-test.service",
|
||||
];
|
||||
const ROLLBACK_PATTERN: &str = "rmm-general-startup-rollback-*.timer";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Registry {
|
||||
schema_version: u32,
|
||||
profile: String,
|
||||
bootstrap_receipt_sha256: String,
|
||||
reader_contract_sha256: String,
|
||||
host_context: HostContext,
|
||||
units: Vec<Unit>,
|
||||
rollback_timers: Vec<Unit>,
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Unit {
|
||||
unit: String,
|
||||
unit_file_state: String,
|
||||
/// Exactly the Frozen OS unit_composition vector: fragment, then DropInPaths
|
||||
/// in their actual order. FileProof includes original device/inode metadata.
|
||||
composition: Vec<(String, FileProof)>,
|
||||
triggers: Vec<String>,
|
||||
triggered_by: Vec<String>,
|
||||
}
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct Stamp {
|
||||
dev: u64,
|
||||
ino: u64,
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
mode: u32,
|
||||
links: u64,
|
||||
bytes: u64,
|
||||
mtime: i64,
|
||||
mtime_ns: i64,
|
||||
ctime: i64,
|
||||
ctime_ns: i64,
|
||||
}
|
||||
impl Stamp {
|
||||
fn read(path: &Path) -> Result<Self> {
|
||||
let m = std::fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
m.is_file() && !m.file_type().is_symlink(),
|
||||
"UPDATE_REGISTRY_REGULAR_FILE"
|
||||
);
|
||||
Ok(Self::of(&m))
|
||||
}
|
||||
fn of(m: &Metadata) -> Self {
|
||||
Self {
|
||||
dev: m.dev(),
|
||||
ino: m.ino(),
|
||||
uid: m.uid(),
|
||||
gid: m.gid(),
|
||||
mode: m.mode(),
|
||||
links: m.nlink(),
|
||||
bytes: m.len(),
|
||||
mtime: m.mtime(),
|
||||
mtime_ns: m.mtime_nsec(),
|
||||
ctime: m.ctime(),
|
||||
ctime_ns: m.ctime_nsec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Protected {
|
||||
directory: Directory,
|
||||
file: Mutex<HeldFile>,
|
||||
path: PathBuf,
|
||||
proof: FileProof,
|
||||
stamp: Stamp,
|
||||
raw: Vec<u8>,
|
||||
}
|
||||
impl Protected {
|
||||
fn open(path: &Path) -> Result<Self> {
|
||||
let before = Stamp::read(path)?;
|
||||
let directory =
|
||||
Directory::open(path.parent().context("UPDATE_REGISTRY_PARENT")?, 0, false)?;
|
||||
let mut file = directory.inspect(
|
||||
path.file_name().context("UPDATE_REGISTRY_FILENAME")?,
|
||||
0,
|
||||
MAX_BYTES,
|
||||
)?;
|
||||
let raw = file.bytes(MAX_BYTES)?;
|
||||
let proof = file.proof().clone();
|
||||
ensure!(
|
||||
before == Stamp::read(path)?
|
||||
&& before.uid == 0
|
||||
&& before.mode & 0o022 == 0
|
||||
&& before.bytes == raw.len() as u64,
|
||||
"UPDATE_REGISTRY_CHANGED_DURING_READ"
|
||||
);
|
||||
let result = Self {
|
||||
directory,
|
||||
file: Mutex::new(file),
|
||||
path: path.into(),
|
||||
proof,
|
||||
stamp: before,
|
||||
raw,
|
||||
};
|
||||
result.verify()?;
|
||||
Ok(result)
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
self.directory.verify()?;
|
||||
ensure!(
|
||||
Stamp::read(&self.path)? == self.stamp,
|
||||
"UPDATE_REGISTRY_METADATA_CHANGED"
|
||||
);
|
||||
let mut held = self
|
||||
.file
|
||||
.try_lock()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_REGISTRY_HELD_FILE_BUSY"))?;
|
||||
held.verify(MAX_BYTES)?;
|
||||
let mut named = self.directory.file(
|
||||
self.path.file_name().context("UPDATE_REGISTRY_FILENAME")?,
|
||||
&self.proof,
|
||||
MAX_BYTES,
|
||||
)?;
|
||||
ensure!(
|
||||
named.bytes(MAX_BYTES)? == self.raw && Stamp::read(&self.path)? == self.stamp,
|
||||
"UPDATE_REGISTRY_ORIGINAL_RAW_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-cloneable independently loaded original registry. No caller completeness
|
||||
/// flag and no command/path selection is exposed by its public API.
|
||||
pub struct QualifiedRegistry {
|
||||
registry: Registry,
|
||||
protected: Vec<Protected>,
|
||||
policy_sha256: String,
|
||||
}
|
||||
impl QualifiedRegistry {
|
||||
pub fn load(policy: &LocalUpdatePolicy) -> Result<Self> {
|
||||
ensure!(
|
||||
policy.validate() && policy.registry_path == REGISTRY,
|
||||
"UPDATE_READER_POLICY"
|
||||
);
|
||||
let original = Protected::open(Path::new(REGISTRY))?;
|
||||
ensure!(
|
||||
original.proof.identity.links == 1
|
||||
&& hash(&original.raw) == policy.reader_registry_sha256,
|
||||
"UPDATE_READER_REGISTRY_PIN"
|
||||
);
|
||||
let registry: Registry = serde_json::from_slice(&original.raw)
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_READER_REGISTRY_CODEC"))?;
|
||||
validate_registry(®istry, policy)?;
|
||||
let mut protected = vec![original];
|
||||
let mut seen = BTreeMap::new();
|
||||
for unit in registry.units.iter().chain(®istry.rollback_timers) {
|
||||
for (path, expected) in &unit.composition {
|
||||
if let Some(existing) = seen.get(path) {
|
||||
ensure!(
|
||||
existing == expected,
|
||||
"UPDATE_READER_SHARED_UNIT_PROOF_CONFLICT"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
ensure!(protected.len() <= MAX_FILES, "UPDATE_READER_FILE_LIMIT");
|
||||
let held = Protected::open(Path::new(path))?;
|
||||
ensure!(
|
||||
held.proof == *expected,
|
||||
"UPDATE_READER_UNIT_ORIGINAL_CHANGED"
|
||||
);
|
||||
seen.insert(path.clone(), expected.clone());
|
||||
protected.push(held);
|
||||
}
|
||||
}
|
||||
let result = Self {
|
||||
registry,
|
||||
protected,
|
||||
policy_sha256: hash(&serde_json::to_vec(policy)?),
|
||||
};
|
||||
result.verify_protected()?;
|
||||
Ok(result)
|
||||
}
|
||||
pub fn host_context(&self) -> &HostContext {
|
||||
&self.registry.host_context
|
||||
}
|
||||
pub fn verify_protected(&self) -> Result<()> {
|
||||
for file in &self.protected {
|
||||
file.verify()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn verify_admission(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> {
|
||||
self.verify_phase(policy, budget, false)
|
||||
}
|
||||
pub fn verify_stopped(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> {
|
||||
self.verify_phase(policy, budget, true)
|
||||
}
|
||||
fn verify_phase(
|
||||
&self,
|
||||
policy: &LocalUpdatePolicy,
|
||||
budget: &Budget,
|
||||
stopped: bool,
|
||||
) -> Result<()> {
|
||||
budget.check()?;
|
||||
self.verify_protected()?;
|
||||
ensure!(
|
||||
hash(&serde_json::to_vec(policy)?) == self.policy_sha256,
|
||||
"UPDATE_READER_POLICY_CHANGED"
|
||||
);
|
||||
ensure!(
|
||||
current_host_context()? == self.registry.host_context,
|
||||
"UPDATE_READER_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
let first_names = rollback_names(budget)?;
|
||||
let allowed: BTreeSet<_> = self
|
||||
.registry
|
||||
.rollback_timers
|
||||
.iter()
|
||||
.map(|u| u.unit.as_str())
|
||||
.collect();
|
||||
ensure!(
|
||||
first_names
|
||||
.iter()
|
||||
.all(|name| allowed.contains(name.as_str())),
|
||||
"UPDATE_READER_UNKNOWN_ROLLBACK_TIMER"
|
||||
);
|
||||
let mut first = BTreeMap::new();
|
||||
for (index, unit) in self.registry.units.iter().enumerate() {
|
||||
let active = index < 4 && (!stopped || index == 3);
|
||||
let status = observe(unit, budget)?;
|
||||
status.verify(unit, active, index < 4)?;
|
||||
first.insert(unit.unit.clone(), status);
|
||||
}
|
||||
for unit in &self.registry.rollback_timers {
|
||||
let status = observe(unit, budget)?;
|
||||
status.verify(unit, false, false)?;
|
||||
first.insert(unit.unit.clone(), status);
|
||||
}
|
||||
// Structural trigger names are not an assertion that a source is live.
|
||||
// Every exact registered relevant source is independently closed below.
|
||||
for unit in self
|
||||
.registry
|
||||
.units
|
||||
.iter()
|
||||
.chain(&self.registry.rollback_timers)
|
||||
{
|
||||
if !unit.triggers.is_empty() {
|
||||
ensure!(
|
||||
first[&unit.unit].closed(),
|
||||
"UPDATE_READER_ACTIVATION_SOURCE_OPEN"
|
||||
);
|
||||
}
|
||||
for name in &unit.triggered_by {
|
||||
ensure!(
|
||||
first.get(name).is_some_and(|source| source.closed()),
|
||||
"UPDATE_READER_ACTIVATION_PATH_OPEN"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
rollback_names(budget)? == first_names,
|
||||
"UPDATE_READER_ROLLBACK_TIMER_SET_CHANGED"
|
||||
);
|
||||
self.verify_protected()?;
|
||||
for unit in self
|
||||
.registry
|
||||
.units
|
||||
.iter()
|
||||
.chain(&self.registry.rollback_timers)
|
||||
{
|
||||
ensure!(
|
||||
observe(unit, budget)? == first[&unit.unit],
|
||||
"UPDATE_READER_STATUS_CHANGED"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
current_host_context()? == self.registry.host_context,
|
||||
"UPDATE_READER_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
self.verify_protected()?;
|
||||
budget.check()
|
||||
}
|
||||
}
|
||||
fn fixed_units() -> Vec<String> {
|
||||
let mut names = SERVICES.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
for name in SERVICES {
|
||||
let base = name.strip_suffix(".service").expect("fixed service");
|
||||
for suffix in ["socket", "timer"] {
|
||||
names.push(format!("{base}.{suffix}"));
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
fn rollback(name: &str) -> bool {
|
||||
let Some(value) = name
|
||||
.strip_prefix("rmm-general-startup-rollback-")
|
||||
.and_then(|s| s.strip_suffix(".timer"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
uuid::Uuid::parse_str(value)
|
||||
.is_ok_and(|id| id.get_version_num() == 4 && id.to_string() == value)
|
||||
}
|
||||
fn validate_registry(registry: &Registry, policy: &LocalUpdatePolicy) -> Result<()> {
|
||||
ensure!(
|
||||
registry.schema_version == 1
|
||||
&& registry.profile == "linux_shared_readers_v1"
|
||||
&& registry.reader_contract_sha256 == reader_contract_sha256(),
|
||||
"UPDATE_READER_REGISTRY_PROFILE"
|
||||
);
|
||||
let baseline = policy
|
||||
.initial_baseline
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let ActivationEvidence::Bootstrap {
|
||||
qualification_receipt_sha256,
|
||||
} = baseline.record.activation_evidence
|
||||
else {
|
||||
anyhow::bail!("UPDATE_READER_INITIAL_BOOTSTRAP_REQUIRED");
|
||||
};
|
||||
ensure!(
|
||||
digest(®istry.bootstrap_receipt_sha256)
|
||||
&& registry.bootstrap_receipt_sha256 == qualification_receipt_sha256,
|
||||
"UPDATE_READER_BOOTSTRAP_RECEIPT"
|
||||
);
|
||||
let host = ®istry.host_context;
|
||||
ensure!(
|
||||
[
|
||||
host.proc_inode,
|
||||
host.user_namespace_inode,
|
||||
host.pid_namespace_inode,
|
||||
host.cgroup_namespace_inode
|
||||
]
|
||||
.iter()
|
||||
.all(|n| *n > 0),
|
||||
"UPDATE_READER_HOST_CONTEXT_SHAPE"
|
||||
);
|
||||
ensure!(
|
||||
registry
|
||||
.units
|
||||
.iter()
|
||||
.map(|u| u.unit.clone())
|
||||
.eq(fixed_units())
|
||||
&& registry.rollback_timers.len() <= MAX_ROLLBACK,
|
||||
"UPDATE_READER_CLOSED_UNIT_SET"
|
||||
);
|
||||
let mut all: BTreeSet<String> = fixed_units().into_iter().collect();
|
||||
let mut previous = None;
|
||||
for unit in ®istry.rollback_timers {
|
||||
ensure!(
|
||||
rollback(&unit.unit)
|
||||
&& previous
|
||||
.as_ref()
|
||||
.is_none_or(|old: &String| old < &unit.unit)
|
||||
&& all.insert(unit.unit.clone()),
|
||||
"UPDATE_READER_ROLLBACK_NAMES"
|
||||
);
|
||||
previous = Some(unit.unit.clone());
|
||||
}
|
||||
let mut total = 0;
|
||||
for (index, unit) in registry
|
||||
.units
|
||||
.iter()
|
||||
.chain(®istry.rollback_timers)
|
||||
.enumerate()
|
||||
{
|
||||
let active = index < 4;
|
||||
ensure!(
|
||||
unit.composition.len() <= 17
|
||||
&& ((!unit.composition.is_empty()
|
||||
&& if active {
|
||||
matches!(unit.unit_file_state.as_str(), "enabled" | "disabled")
|
||||
} else {
|
||||
unit.unit_file_state == "disabled"
|
||||
})
|
||||
|| (!active && unit.composition.is_empty() && unit.unit_file_state.is_empty())),
|
||||
"UPDATE_READER_UNIT_STATE_SHAPE"
|
||||
);
|
||||
let mut paths = BTreeSet::new();
|
||||
for (position, (path, proof)) in unit.composition.iter().enumerate() {
|
||||
let filename = Path::new(path).file_name().and_then(|name| name.to_str());
|
||||
ensure!(
|
||||
if position == 0 {
|
||||
filename == Some(unit.unit.as_str())
|
||||
} else {
|
||||
filename.is_some_and(|name| name.ends_with(".conf"))
|
||||
},
|
||||
"UPDATE_READER_UNIT_LEAF_NAME"
|
||||
);
|
||||
ensure!(
|
||||
unit_path(path)
|
||||
&& paths.insert(path)
|
||||
&& proof.identity.uid == 0
|
||||
&& proof.identity.inode > 0
|
||||
&& proof.identity.links > 0
|
||||
&& proof.identity.mode & libc::S_IFMT == libc::S_IFREG
|
||||
&& proof.identity.mode & 0o022 == 0
|
||||
&& proof.bytes <= MAX_BYTES
|
||||
&& digest(&proof.sha256),
|
||||
"UPDATE_READER_UNIT_PROOF_SHAPE"
|
||||
);
|
||||
total += 1;
|
||||
}
|
||||
for names in [&unit.triggers, &unit.triggered_by] {
|
||||
ensure!(
|
||||
names.len() <= 32
|
||||
&& names.windows(2).all(|pair| pair[0] < pair[1])
|
||||
&& names.iter().all(|name| all.contains(name)),
|
||||
"UPDATE_READER_UNKNOWN_ACTIVATION_RELATION"
|
||||
);
|
||||
}
|
||||
if unit.composition.is_empty() {
|
||||
ensure!(
|
||||
unit.triggers.is_empty() && unit.triggered_by.is_empty(),
|
||||
"UPDATE_READER_ABSENT_RELATIONS"
|
||||
);
|
||||
}
|
||||
let pin = if index < 3 {
|
||||
Some(&policy.services[index])
|
||||
} else if index == 3 {
|
||||
Some(&policy.updater_service)
|
||||
} else if index == 4 {
|
||||
policy.services.get(3)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(pin) = pin {
|
||||
ensure!(
|
||||
pin.unit == unit.unit
|
||||
&& !unit.composition.is_empty()
|
||||
&& hash(&serde_json::to_vec(&unit.composition)?) == pin.unit_sha256,
|
||||
"UPDATE_READER_POLICY_UNIT_COMPOSITION"
|
||||
);
|
||||
}
|
||||
if index == 4 && policy.services.len() == 3 {
|
||||
ensure!(
|
||||
unit.composition.is_empty(),
|
||||
"UPDATE_READER_APT_NOT_IN_POLICY"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(total <= MAX_FILES, "UPDATE_READER_FILE_LIMIT");
|
||||
Ok(())
|
||||
}
|
||||
fn unit_path(value: &str) -> bool {
|
||||
value.len() <= 4096
|
||||
&& value.starts_with('/')
|
||||
&& value
|
||||
.split('/')
|
||||
.skip(1)
|
||||
.all(|part| !part.is_empty() && part != "." && part != "..")
|
||||
&& value.bytes().all(|b| b.is_ascii_graphic() && b != b'\\')
|
||||
&& [
|
||||
"/etc/systemd/system/",
|
||||
"/usr/lib/systemd/system/",
|
||||
"/lib/systemd/system/",
|
||||
"/run/systemd/system/",
|
||||
"/run/systemd/transient/",
|
||||
]
|
||||
.iter()
|
||||
.any(|root| value.starts_with(root))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Status {
|
||||
fields: BTreeMap<String, String>,
|
||||
main_pid: Option<u32>,
|
||||
control_pid: Option<u32>,
|
||||
connections: Option<u32>,
|
||||
}
|
||||
const GENERIC: [&str; 11] = [
|
||||
"Id",
|
||||
"LoadState",
|
||||
"ActiveState",
|
||||
"SubState",
|
||||
"InvocationID",
|
||||
"UnitFileState",
|
||||
"FragmentPath",
|
||||
"DropInPaths",
|
||||
"Triggers",
|
||||
"TriggeredBy",
|
||||
"Job",
|
||||
];
|
||||
impl Status {
|
||||
fn parse(unit: &str, raw: &[u8]) -> Result<Self> {
|
||||
ensure!(
|
||||
raw.len() <= 16384 && raw.is_ascii(),
|
||||
"UPDATE_READER_STATUS_LIMIT"
|
||||
);
|
||||
let text =
|
||||
std::str::from_utf8(raw).map_err(|_| anyhow::anyhow!("UPDATE_READER_STATUS_CODEC"))?;
|
||||
let mut fields: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut permitted = GENERIC.to_vec();
|
||||
if unit.ends_with(".service") {
|
||||
permitted.extend(["MainPID", "ControlPID"]);
|
||||
} else if unit.ends_with(".socket") {
|
||||
permitted.extend(["ControlPID", "NConnections"]);
|
||||
}
|
||||
for line in text.lines() {
|
||||
let (key, value) = line.split_once('=').context("UPDATE_READER_STATUS_CODEC")?;
|
||||
ensure!(
|
||||
permitted.contains(&key) && fields.insert(key.into(), value.into()).is_none(),
|
||||
"UPDATE_READER_STATUS_FIELDS"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
GENERIC.iter().all(|key| fields.contains_key(*key)) && fields["Id"] == unit,
|
||||
"UPDATE_READER_STATUS_INCOMPLETE"
|
||||
);
|
||||
let loaded = fields["LoadState"] == "loaded";
|
||||
let number = |key: &str, required: bool| -> Result<Option<u32>> {
|
||||
match fields.get(key) {
|
||||
Some(value) => {
|
||||
ensure!(
|
||||
!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
|
||||
"UPDATE_READER_PID_CODEC"
|
||||
);
|
||||
Ok(Some(
|
||||
value
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_READER_PID_RANGE"))?,
|
||||
))
|
||||
}
|
||||
None => {
|
||||
ensure!(!required, "UPDATE_READER_MISSING_PID_PROPERTY");
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
};
|
||||
let main_pid = number("MainPID", loaded && unit.ends_with(".service"))?;
|
||||
let control_pid = number("ControlPID", loaded && !unit.ends_with(".timer"))?;
|
||||
let connections = number("NConnections", loaded && unit.ends_with(".socket"))?;
|
||||
Ok(Self {
|
||||
fields,
|
||||
main_pid,
|
||||
control_pid,
|
||||
connections,
|
||||
})
|
||||
}
|
||||
fn closed(&self) -> bool {
|
||||
self.fields["ActiveState"] == "inactive"
|
||||
&& self.fields["SubState"] == "dead"
|
||||
&& self.main_pid.is_none_or(|n| n == 0)
|
||||
&& self.control_pid.is_none_or(|n| n == 0)
|
||||
&& self.connections.is_none_or(|n| n == 0)
|
||||
&& self.fields["Job"].is_empty()
|
||||
}
|
||||
fn verify(&self, unit: &Unit, active: bool, original_reader: bool) -> Result<()> {
|
||||
let fields = &self.fields;
|
||||
ensure!(
|
||||
fields["UnitFileState"] == unit.unit_file_state
|
||||
&& relations(&fields["Triggers"])? == unit.triggers
|
||||
&& relations(&fields["TriggeredBy"])? == unit.triggered_by,
|
||||
"UPDATE_READER_UNIT_RELATIONS_CHANGED"
|
||||
);
|
||||
if unit.composition.is_empty() {
|
||||
ensure!(
|
||||
!active
|
||||
&& fields["LoadState"] == "not-found"
|
||||
&& fields["FragmentPath"].is_empty()
|
||||
&& fields["DropInPaths"].is_empty()
|
||||
&& self.closed(),
|
||||
"UPDATE_READER_ABSENT_UNIT_CHANGED"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
fields["LoadState"] == "loaded",
|
||||
"UPDATE_READER_UNIT_NOT_LOADED"
|
||||
);
|
||||
let mut paths = vec![fields["FragmentPath"].as_str()];
|
||||
paths.extend(fields["DropInPaths"].split_ascii_whitespace());
|
||||
ensure!(
|
||||
paths
|
||||
.iter()
|
||||
.copied()
|
||||
.eq(unit.composition.iter().map(|(path, _)| path.as_str())),
|
||||
"UPDATE_READER_UNIT_COMPOSITION_CHANGED"
|
||||
);
|
||||
if active {
|
||||
ensure!(
|
||||
fields["ActiveState"] == "active"
|
||||
&& fields["SubState"] == "running"
|
||||
&& self.main_pid.is_some_and(|pid| pid > 1)
|
||||
&& self.control_pid == Some(0)
|
||||
&& fields["Job"].is_empty()
|
||||
&& fields["InvocationID"].len() == 32
|
||||
&& fields["InvocationID"]
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit())
|
||||
&& fields["InvocationID"].bytes().any(|b| b != b'0'),
|
||||
"UPDATE_READER_ACTIVE_REQUIRED"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
(original_reader || unit.unit_file_state == "disabled") && self.closed(),
|
||||
"UPDATE_READER_UNIT_NOT_CLOSED"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn relations(value: &str) -> Result<Vec<String>> {
|
||||
let mut names = value
|
||||
.split_ascii_whitespace()
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
ensure!(names.len() <= 32, "UPDATE_READER_RELATION_LIMIT");
|
||||
names.sort();
|
||||
ensure!(
|
||||
names.windows(2).all(|pair| pair[0] < pair[1]),
|
||||
"UPDATE_READER_DUPLICATE_RELATION"
|
||||
);
|
||||
Ok(names)
|
||||
}
|
||||
fn observe(unit: &Unit, budget: &Budget) -> Result<Status> {
|
||||
let mut properties = GENERIC.to_vec();
|
||||
if unit.unit.ends_with(".service") {
|
||||
properties.extend(["MainPID", "ControlPID"]);
|
||||
} else if unit.unit.ends_with(".socket") {
|
||||
properties.extend(["ControlPID", "NConnections"]);
|
||||
}
|
||||
let property = format!("--property={}", properties.join(","));
|
||||
let raw = command(&["show", "--all", &property, "--", &unit.unit], budget)?;
|
||||
Status::parse(&unit.unit, &raw)
|
||||
}
|
||||
fn rollback_names(budget: &Budget) -> Result<BTreeSet<String>> {
|
||||
let mut names = BTreeSet::new();
|
||||
for args in [
|
||||
vec![
|
||||
"list-units",
|
||||
"--all",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"--type=timer",
|
||||
"--",
|
||||
ROLLBACK_PATTERN,
|
||||
],
|
||||
vec!["list-unit-files", "--no-legend", "--", ROLLBACK_PATTERN],
|
||||
] {
|
||||
let raw = command(&args, budget)?;
|
||||
ensure!(raw.is_ascii(), "UPDATE_READER_TIMER_LIST_CODEC");
|
||||
for line in std::str::from_utf8(&raw)
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_READER_TIMER_LIST_CODEC"))?
|
||||
.lines()
|
||||
{
|
||||
let name = line
|
||||
.split_ascii_whitespace()
|
||||
.next()
|
||||
.context("UPDATE_READER_TIMER_LIST_CODEC")?;
|
||||
ensure!(
|
||||
rollback(name) && names.len() < MAX_ROLLBACK + 1,
|
||||
"UPDATE_READER_TIMER_LIST_LIMIT"
|
||||
);
|
||||
names.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
struct OwnedCommand {
|
||||
child: Child,
|
||||
pidfd: std::fs::File,
|
||||
}
|
||||
impl Drop for OwnedCommand {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_pidfd_send_signal,
|
||||
self.pidfd.as_raw_fd(),
|
||||
libc::SIGKILL,
|
||||
0usize,
|
||||
0,
|
||||
)
|
||||
};
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
fn drain(stream: &mut dyn Read, raw: &mut Vec<u8>) -> Result<()> {
|
||||
let mut chunk = [0; 1024];
|
||||
loop {
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) => break,
|
||||
Ok(count) => {
|
||||
ensure!(
|
||||
raw.len() + count <= 16384,
|
||||
"UPDATE_READER_COMMAND_OUTPUT_LIMIT"
|
||||
);
|
||||
raw.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(_) => anyhow::bail!("UPDATE_READER_COMMAND_READ"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn command(args: &[&str], budget: &Budget) -> Result<Vec<u8>> {
|
||||
budget.check()?;
|
||||
let child = Command::new("/usr/bin/systemctl")
|
||||
.args(["--system", "--no-ask-password", "--no-pager", "--full"])
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin")
|
||||
.env("LC_ALL", "C")
|
||||
.env("SYSTEMD_COLORS", "0")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_SPAWN"))?;
|
||||
let mut child = child;
|
||||
let pid = unsafe { libc::syscall(libc::SYS_pidfd_open, child.id(), 0) };
|
||||
if pid < 0 {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
anyhow::bail!("UPDATE_READER_COMMAND_PIDFD");
|
||||
}
|
||||
let mut owned = OwnedCommand {
|
||||
child,
|
||||
pidfd: unsafe { std::fs::File::from_raw_fd(pid as i32) },
|
||||
};
|
||||
let mut stdout = owned.child.stdout.take().context("UPDATE_READER_STDOUT")?;
|
||||
let mut stderr = owned.child.stderr.take().context("UPDATE_READER_STDERR")?;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
ensure!(
|
||||
unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } >= 0,
|
||||
"UPDATE_READER_COMMAND_NONBLOCK"
|
||||
);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut out = Vec::new();
|
||||
let mut error = Vec::new();
|
||||
loop {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"UPDATE_READER_COMMAND_TIMEOUT"
|
||||
);
|
||||
drain(&mut stdout, &mut out)?;
|
||||
drain(&mut stderr, &mut error)?;
|
||||
if let Some(status) = owned
|
||||
.child
|
||||
.try_wait()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_WAIT"))?
|
||||
{
|
||||
drain(&mut stdout, &mut out)?;
|
||||
drain(&mut stderr, &mut error)?;
|
||||
ensure!(
|
||||
status.success() && error.is_empty(),
|
||||
"UPDATE_READER_SYSTEMD_FAILED"
|
||||
);
|
||||
budget.check()?;
|
||||
return Ok(out);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn timer() -> Vec<u8> {
|
||||
b"Id=rmm-agent-remote.timer\nLoadState=loaded\nActiveState=inactive\nSubState=dead\nInvocationID=\nUnitFileState=disabled\nFragmentPath=/etc/systemd/system/rmm-agent-remote.timer\nDropInPaths=\nTriggers=rmm-agent-remote.service\nTriggeredBy=\nJob=\n".to_vec()
|
||||
}
|
||||
#[test]
|
||||
fn timer_without_process_interface_is_typed_but_missing_service_pid_or_pending_job_denies() {
|
||||
let raw = timer();
|
||||
let status = Status::parse("rmm-agent-remote.timer", &raw).unwrap();
|
||||
assert_eq!(status.main_pid, None);
|
||||
assert_eq!(status.control_pid, None);
|
||||
assert!(status.closed());
|
||||
let pending = String::from_utf8(raw.clone())
|
||||
.unwrap()
|
||||
.replace("Job=\n", "Job=123\n");
|
||||
assert!(
|
||||
!Status::parse("rmm-agent-remote.timer", pending.as_bytes())
|
||||
.unwrap()
|
||||
.closed()
|
||||
);
|
||||
let service = String::from_utf8(raw.clone())
|
||||
.unwrap()
|
||||
.replace("rmm-agent-remote.timer", "rmm-agent-remote.service");
|
||||
assert!(Status::parse("rmm-agent-remote.service", service.as_bytes()).is_err());
|
||||
let mut unknown = raw.clone();
|
||||
unknown.extend_from_slice(b"MainPID=0\n");
|
||||
assert!(Status::parse("rmm-agent-remote.timer", &unknown).is_err());
|
||||
let mut duplicate = raw;
|
||||
duplicate.extend_from_slice(b"Job=\n");
|
||||
assert!(Status::parse("rmm-agent-remote.timer", &duplicate).is_err());
|
||||
assert!(rollback(
|
||||
"rmm-general-startup-rollback-11111111-1111-4111-8111-111111111111.timer"
|
||||
));
|
||||
assert!(!rollback("rmm-general-startup-rollback-*.timer"));
|
||||
}
|
||||
}
|
||||
@@ -89,12 +89,6 @@ impl TrustState {
|
||||
"UPDATE_PROTECTED_POLICY_CHANGED"
|
||||
);
|
||||
protected.push(file);
|
||||
let (file, raw) = Protected::read(Path::new(&policy.registry_path), 65536)?;
|
||||
ensure!(
|
||||
hash(&raw) == policy.reader_registry_sha256,
|
||||
"UPDATE_PROTECTED_READER_REGISTRY_CHANGED"
|
||||
);
|
||||
protected.push(file);
|
||||
let (file, raw) = Protected::read(Path::new(&policy.keyring_path), 16384)?;
|
||||
let keys: UpdateKeyringFile = serde_json::from_slice(&raw)?;
|
||||
ensure!(
|
||||
|
||||
@@ -88,42 +88,10 @@ def status(payload):
|
||||
|
||||
def deploy(payload):
|
||||
import io
|
||||
import stat
|
||||
import tarfile
|
||||
root = Path('/opt/rust-discovery'); backup = root/'devstate'/('source-upgrade-'+payload['id'])
|
||||
def time_broker_overlay():
|
||||
# Optional fixed public overlay. Never follow an untrusted pathname or
|
||||
# silently omit an installed overlay when recreating the gateway.
|
||||
path = root/'deploy/server.time-broker.compose.yaml'
|
||||
try:
|
||||
initial = path.lstat()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
require(stat.S_ISREG(initial.st_mode) and initial.st_uid == initial.st_gid == 0
|
||||
and stat.S_IMODE(initial.st_mode) == 0o644 and initial.st_nlink == 1
|
||||
and initial.st_size == 199, 'protected fixed time broker overlay')
|
||||
for parent in path.parents:
|
||||
item = parent.lstat()
|
||||
require(stat.S_ISDIR(item.st_mode) and item.st_uid == 0 and not item.st_mode & 0o022,
|
||||
'protected time broker overlay ancestry')
|
||||
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
|
||||
try:
|
||||
before = os.fstat(fd)
|
||||
raw = os.pread(fd, 4097, 0)
|
||||
identity = lambda item: (item.st_dev,item.st_ino,item.st_uid,item.st_gid,item.st_mode,
|
||||
item.st_nlink,item.st_size,item.st_mtime_ns,item.st_ctime_ns)
|
||||
require(identity(initial) == identity(before) == identity(os.fstat(fd)) == identity(path.lstat())
|
||||
and len(raw) == 199 and hashlib.sha256(raw).hexdigest()
|
||||
== 'dbd08faea8f58c032562d822f4191c719f9a6828b00d6c368fc2596155a9a314',
|
||||
'exact original time broker overlay bytes')
|
||||
return identity(before)
|
||||
finally:
|
||||
os.close(fd)
|
||||
overlay = time_broker_overlay() # Deny before any UI/tag/migration effect.
|
||||
record = json.loads((backup/'source.json').read_text())
|
||||
built=json.loads((backup/'build-result.json').read_text())
|
||||
require(not (backup/'time-gateway-deploy-intent.json').exists(),
|
||||
'stage reserved by fixed time gateway deployment; read its original case')
|
||||
require(built['exit_code'] == 0, 'build must pass')
|
||||
require(all(hashlib.sha256((root/name).read_bytes()).hexdigest() == sha for name,sha in record['files'].items()), 'source drift')
|
||||
require(not (backup/'deploy-result.json').exists(), 'deployment already recorded')
|
||||
@@ -159,9 +127,6 @@ def deploy(payload):
|
||||
with os.fdopen(fd, 'wb') as f: f.write(data); f.flush(); os.fsync(f.fileno()); os.fchmod(f.fileno(), 0o644)
|
||||
os.replace(next_path, dest)
|
||||
cmd = ['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')]
|
||||
if overlay is not None:
|
||||
cmd += ['-f',str(root/'deploy/server.time-broker.compose.yaml')]
|
||||
require(time_broker_overlay() == overlay, 'same optional time broker overlay before tag')
|
||||
if 'image_tag' in record:
|
||||
inspected=subprocess.run(['docker','image','inspect',record['image_tag'],'--format','{{.Id}}'],capture_output=True,check=True,timeout=10).stdout.decode().strip()
|
||||
require(inspected==built['image_id'] and inspected.startswith('sha256:'),'fixed qualified image required')
|
||||
@@ -169,10 +134,8 @@ def deploy(payload):
|
||||
# concurrently finishing source build cannot alter running services.
|
||||
subprocess.run(['docker','tag',inspected,'rust-discovery-server:local'],capture_output=True,check=True,timeout=10)
|
||||
# Existing migration image runs without rebuild; preserves PG volume/PKI.
|
||||
require(time_broker_overlay() == overlay, 'same optional time broker overlay before migration')
|
||||
migrate = subprocess.run(cmd+['run','--rm','--no-deps','migrate'], capture_output=True, timeout=25)
|
||||
require(migrate.returncode == 0, 'migration failed')
|
||||
require(time_broker_overlay() == overlay, 'same optional time broker overlay before recreate')
|
||||
result = subprocess.run(cmd+['up','-d','--no-deps','api','gateway'], capture_output=True, timeout=25)
|
||||
outcome = dict(deployed=result.returncode == 0, existing_state_preserved=True, approvals_created=False)
|
||||
(backup/'deploy-result.json').write_text(json.dumps(outcome)); (backup/'deploy-result.json').chmod(0o600)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
services:
|
||||
gateway:
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /run/rmm-time-source
|
||||
target: /run/rmm-time-source
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
@@ -36,12 +36,31 @@ BROKER_BYTES = 1067136
|
||||
SERVER = Path('/opt/rust-discovery')
|
||||
CERTIFICATES = tuple(SERVER / 'devstate' / kind / leaf for kind in ('pki', 'api-pki') for leaf in ('ca.pem', 'server.pem'))
|
||||
PROFILE = 'rmm.server-time-broker.bootstrap.v1'
|
||||
GENERATION_CASE_ID = 'c9a94f94-eecd-4c66-933d-c45c1a79c7a8'
|
||||
GENERATION_CASE = CASE.parent / GENERATION_CASE_ID
|
||||
QUALITY_PHASE = 'probe-native-source-v1'
|
||||
QUALITY_CONTROLLER_SHA = 'c15f4dad9aeb51270fbee7ba28a545cfe9f6a879d0bc226cf5ddda9036a5a2b6'
|
||||
QUALITY_RESULT_SHA = 'ab8a6511517c6e3c01db2351ccdc5c48c73f34112c9ac863d0ea64de46665933'
|
||||
QUALITY_PHASE = 'probe-peer-acceptance-v1'
|
||||
QUALITY_CONTROLLER_SHA = 'ca89eac44d6b1e8bbbb14cca58ecabb02fd05d59292b77f703997fad0c29e3c8'
|
||||
QUALITY_RESULT_SHA = None # Root must bind an independently reviewed actual native PASS first.
|
||||
GROUP_FAILURE_SHA = '4977876b935bed8903ce4c880a0d9c77c49cd2c7110551fbf854baeccbe64ea7'
|
||||
GROUPADD_SHA = '468289aa24d8e9bacb1f21d315e59dc49febec5f120eb7a01b44fe6e98700ed0'
|
||||
OLD_QUALITY_ORIGIN = {
|
||||
'original_group_acceptance_controller_sha256': 'd04989ccf6d3e7b379a1b02f5fd3ce2545a3563fbce1368f33102f58a36f2dcf',
|
||||
'original_group_acceptance_result_sha256': '96b714e2e43aa13073317c310b213863a02f26dbf2e6c975dc0801ef621eccd5',
|
||||
'original_group_acceptance_log_sha256': 'f80644630b09f50fdc731418dbe4f17fff32622910b3efd346a0369b75e985ef',
|
||||
'original_group_acceptance_receipt_sha256': '6923cc1893619f67ae8677b84f9cfea6d0edd554120e9139d843115e52aa7643',
|
||||
'original_dac_diagnostic_receipt_sha256': 'd999e5260cab3457a7a66603fdb0288615443628e5a28f31df9c1cecd3401ef5',
|
||||
}
|
||||
PEER_ORIGIN = {
|
||||
'peer_namespace_controller_sha256': '2f1dafece1e5cd1b9be11078edee5f67fbdaef013defa10c527367b42dce9265',
|
||||
'peer_namespace_result_sha256': 'cb1665cb14086d3ba79089a2eb9e01a532dd779bdcf577eafca0e343b5cc6a8b',
|
||||
'peer_namespace_local_profile_sha256': '27e3708a34988fb778cbc8cfd892e0f222b8caf927034e472f391aab65349394',
|
||||
'peer_namespace_receipt_sha256': '1dc76b5a9673f9e08e59f91f05d586cb9335ffd0a33e697d5170823a6f053619',
|
||||
'peer_namespace_read_receipt_sha256': '129584f296b53614e10a9e5eac2bab0a1e70b1c51f7fd70eb31bdf907ce767b3',
|
||||
'original_dac_acceptance_controller_sha256': '1b79a4ab8d587338e43330db0fc73ff2e199dc61f1172da7cc3fc93d3538d2ac',
|
||||
'original_dac_acceptance_result_sha256': '5f8e0634e44c7caeab2020af5f5dd0d6e83249265d0ebd67f938f0797b551fca',
|
||||
'original_dac_acceptance_log_sha256': 'f80644630b09f50fdc731418dbe4f17fff32622910b3efd346a0369b75e985ef',
|
||||
'original_dac_acceptance_receipt_sha256': '553bc8580deb0e78d780b43c569f3827715a54a7b8629c51c705cf4e9ded7c61',
|
||||
}
|
||||
PEER_MAIN_SHA = '214e509af9ab9b713e89b09bf6440c4b4248e97c64d4b0d884d2f869d406e1e2'
|
||||
PEER_CODE = Path('/var/lib/rmm-time-source-operators') / PEER_ORIGIN['peer_namespace_controller_sha256'] / 'peer_namespace_bootstrap.py'
|
||||
PKCS8 = bytes.fromhex('302e020100300506032b657004220420')
|
||||
SPKI = bytes.fromhex('302a300506032b6570032100')
|
||||
UNIT_RAW = b'''[Unit]
|
||||
@@ -119,23 +138,6 @@ def protected_code():
|
||||
'reviewed_pin_controller_unchanged')
|
||||
|
||||
|
||||
def protected_generation(pin):
|
||||
require(type(QUALITY_CONTROLLER_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_CONTROLLER_SHA),
|
||||
'reviewed_new_generation_controller_not_bound')
|
||||
path = Path('/var/lib/rmm-time-source-operators') / QUALITY_CONTROLLER_SHA / 'new_generation_probe.py'
|
||||
record = pin.read_file(path, 128 * 1024)
|
||||
require(sha(record[0]) == QUALITY_CONTROLLER_SHA, 'exact_reviewed_new_generation_controller')
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_new_generation_guard', loader=None))
|
||||
module.__file__ = str(path)
|
||||
exec(compile(record[0], str(path), 'exec'), module.__dict__)
|
||||
require(module.CASE_ID == GENERATION_CASE_ID and module.QUALITY_PHASE == QUALITY_PHASE,
|
||||
'fixed_new_generation_case_and_quality_phase')
|
||||
original = module.SharedGenerationProof(pin)
|
||||
def guard():
|
||||
require(pin.read_file(path, 128 * 1024) == record, 'reviewed_new_generation_controller_unchanged')
|
||||
return original, guard
|
||||
|
||||
|
||||
def command(pin, path, args, data=None):
|
||||
# Fixed public tools only. Private DER is stdin, never argv/environment/file.
|
||||
parent = pin.directory(path.parent)
|
||||
@@ -252,19 +254,124 @@ def forbidden_keys(pin, original):
|
||||
return sorted(keys), {'job_public_key_sha256': sha(bytes.fromhex(job['public_key_hex'])), 'certificates': certificates}
|
||||
|
||||
|
||||
def quality_proof(pin, original):
|
||||
def quality_proof(pin, original, pin_result_raw, pin_result):
|
||||
require(re.fullmatch('[0-9a-f]{64}', QUALITY_CONTROLLER_SHA), 'reviewed_quality_controller_not_bound')
|
||||
require(type(QUALITY_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_RESULT_SHA),
|
||||
'actual_new_generation_quality_pass_not_bound')
|
||||
# The fixed reviewed shared decoder checks the entire new-generation
|
||||
# result/witness/sample contract, not an old successful build or CLI status.
|
||||
records = original.quality_proof(QUALITY_RESULT_SHA)
|
||||
result_path = GENERATION_CASE / QUALITY_PHASE / 'result.json'
|
||||
require(type(records) is dict and result_path in records and
|
||||
sha(records[result_path][0]) == QUALITY_RESULT_SHA,
|
||||
'actual_new_generation_quality_original_result')
|
||||
for path, record in records.items():
|
||||
require(pin.read_file(path, 65536) == record, 'actual_new_generation_quality_records_unchanged')
|
||||
return records
|
||||
'actual_peer_quality_pass_not_bound')
|
||||
phase = CASE / QUALITY_PHASE
|
||||
require(not (phase / 'failure.json').exists(), 'original_quality_probe_failed')
|
||||
raw, proof = pin.read_file(phase / 'result.json', 16384)
|
||||
require(sha(raw) == QUALITY_RESULT_SHA, 'exact_actual_peer_quality_pass')
|
||||
result = pin.parsed(raw)
|
||||
artifact = original.artifacts['examples/operator_probe'][1]
|
||||
old_probe, _ = pin.read_file(CASE / 'probe/result.json', 16384)
|
||||
binding = {'profile': 'rmm.server-time-source.peer-acceptance.v1', 'original_case': CASE_ID,
|
||||
'phase': QUALITY_PHASE, 'unit': 'rmm-time-source-probe-peer-acceptance-' + CASE_ID + '.service',
|
||||
'controller_sha256': QUALITY_CONTROLLER_SHA, 'operator_sha256': pin.OPERATOR_SHA,
|
||||
'pin_controller_sha256': PIN_SHA, 'public_pin_sha256': pin_result['public_pin_sha256'],
|
||||
'source_tar_sha256': original.source_sha, 'manifest_sha256': original.manifest_sha,
|
||||
'artifact': artifact, 'original_group_receipt_sha256': GROUP_FAILURE_SHA,
|
||||
'original_probe_result_sha256': sha(old_probe), 'pin_result_sha256': sha(pin_result_raw), **OLD_QUALITY_ORIGIN, **PEER_ORIGIN}
|
||||
extra = {'before_witness', 'after_witness', 'exit_code', 'sample', 'probe_log_sha256', 'source_quality_qualified',
|
||||
'runtime_boot_pin_source_preserved', 'clock_authority', 'signed_attestation', 'signer_created', 'broker_started', 'http_deployed'}
|
||||
require(set(result) == set(binding) | extra and all(result[key] == value for key, value in binding.items()) and
|
||||
result['source_quality_qualified'] is True and type(result['exit_code']) is int and result['exit_code'] == 0 and
|
||||
result['runtime_boot_pin_source_preserved'] is True and all(result[key] is False for key in
|
||||
('clock_authority', 'signed_attestation', 'signer_created', 'broker_started', 'http_deployed')),
|
||||
'original_quality_result_binding')
|
||||
old_group, old_group_state = pin.read_file(CASE / 'probe-group-acceptance-v1/result.json', 16384)
|
||||
old_log, old_log_state = pin.read_file(CASE / 'probe-group-acceptance-v1/probe.log', 16384)
|
||||
require(sha(old_group) == OLD_QUALITY_ORIGIN['original_group_acceptance_result_sha256'] and
|
||||
sha(old_log) == OLD_QUALITY_ORIGIN['original_group_acceptance_log_sha256'], 'unchanged_original_failed_group_acceptance')
|
||||
witness_records = {CASE / 'probe-group-acceptance-v1/result.json': (old_group, old_group_state),
|
||||
CASE / 'probe-group-acceptance-v1/probe.log': (old_log, old_log_state)}
|
||||
for leaf, expected_sha in (('result.json', PEER_ORIGIN['original_dac_acceptance_result_sha256']),
|
||||
('probe.log', PEER_ORIGIN['original_dac_acceptance_log_sha256'])):
|
||||
path = CASE / 'probe-dac-acceptance-v1' / leaf
|
||||
record = pin.read_file(path, 16384)
|
||||
require(sha(record[0]) == expected_sha, 'unchanged_original_failed_dac_acceptance')
|
||||
witness_records[path] = record
|
||||
namespace_path = CASE / 'peer-namespace-bootstrap-v1/result.json'
|
||||
namespace_record = pin.read_file(namespace_path, 16384)
|
||||
require(sha(namespace_record[0]) == PEER_ORIGIN['peer_namespace_result_sha256'], 'actual_peer_namespace_result')
|
||||
witness_records[namespace_path] = namespace_record
|
||||
witnesses = []
|
||||
for name in ('before', 'after'):
|
||||
link = result[name + '_witness']
|
||||
require(set(link) == {'filename', 'sha256'} and link['filename'] == name + '.json', 'fixed_quality_witness_link')
|
||||
data, state = pin.read_file(phase / link['filename'], 16384)
|
||||
require(sha(data) == link['sha256'], 'original_quality_witness_hash')
|
||||
witness = pin.parsed(data)
|
||||
require(set(witness) == set(binding) | {'witness'} and all(witness[key] == value for key, value in binding.items()),
|
||||
'original_quality_witness_binding')
|
||||
actual = witness['witness']
|
||||
require(set(actual) == {'observation', 'public_pin_sha256', 'public_pin_metadata', 'target_directories', 'peer_namespace'} and
|
||||
actual['observation'] == original.expected and actual['public_pin_sha256'] == pin_result['public_pin_sha256'] and
|
||||
actual['public_pin_metadata'] == pin_result['public_pin_metadata'], 'original_quality_source_pin_witness')
|
||||
directories = {name: {key: value[key] for key in ('dev', 'ino', 'uid', 'gid', 'mode')}
|
||||
for name, value in pin_result['targets'].items() if name != str(ETC / 'chrony-pin.json')}
|
||||
require(actual['target_directories'] == directories, 'original_quality_directory_witness')
|
||||
peer = actual['peer_namespace']
|
||||
require(type(peer) is dict and set(peer) == {'result_sha256', 'main_profile_sha256', 'local_profile_sha256',
|
||||
'main_profile_metadata', 'local_profile_metadata', 'parent_access_acl_hex', 'profile'} and
|
||||
peer['result_sha256'] == PEER_ORIGIN['peer_namespace_result_sha256'] and
|
||||
peer['main_profile_sha256'] == PEER_MAIN_SHA and
|
||||
peer['local_profile_sha256'] == PEER_ORIGIN['peer_namespace_local_profile_sha256'] and
|
||||
type(peer['profile']) is dict and set(peer['profile']) == {'chronyd_label', 'enforcing'} and
|
||||
peer['profile']['chronyd_label'] == '/usr/sbin/chronyd (enforce)' and peer['profile']['enforcing'] is True,
|
||||
'exact_peer_namespace_quality_witness')
|
||||
witnesses.append(actual)
|
||||
witness_records[phase / link['filename']] = (data, state)
|
||||
require(witnesses[0] == witnesses[1], 'original_quality_before_after_equal')
|
||||
sample = result['sample']
|
||||
keys = {'profile', 'clock_authority', 'signed_attestation', 'captured_utc_ns', 'server_error_ns', 'source_sync_age_ns',
|
||||
'server_boot_id', 'captured_monotonic_ns', 'sampled_boottime_ns', 'kernel_state'}
|
||||
require(type(sample) is dict and set(sample) == keys and sample['profile'] == 'rmm.native-source-quality.once.v1' and
|
||||
sample['clock_authority'] is False and sample['signed_attestation'] is False and
|
||||
sample['server_boot_id'] == original.expected['boot_id'] and
|
||||
all(type(sample[key]) is int for key in ('captured_utc_ns', 'server_error_ns', 'source_sync_age_ns',
|
||||
'captured_monotonic_ns', 'sampled_boottime_ns', 'kernel_state')) and
|
||||
0 < sample['captured_utc_ns'] <= (1 << 63) - 1 and 0 <= sample['server_error_ns'] <= 500_000_000 and
|
||||
0 <= sample['source_sync_age_ns'] <= 3_600_000_000_000 and 0 <= sample['kernel_state'] <= 4 and
|
||||
0 < sample['captured_monotonic_ns'] <= (1 << 64) - 1 and
|
||||
sample['captured_monotonic_ns'] <= sample['sampled_boottime_ns'] <= (1 << 64) - 1, 'actual_native_quality_sample_bounds')
|
||||
log_raw, log_state = pin.read_file(phase / 'probe.log', 16384)
|
||||
require(sha(log_raw) == result['probe_log_sha256'] and pin.parsed(log_raw) == sample, 'original_actual_quality_sample_log')
|
||||
return ({phase / 'result.json': (raw, proof), phase / 'probe.log': (log_raw, log_state), **witness_records},
|
||||
witnesses[0]['peer_namespace'])
|
||||
|
||||
|
||||
class PeerNamespaceProof:
|
||||
"""Only the fixed reviewed namespace's read-only ACL/MAC observations."""
|
||||
def __init__(self, pin, original, expected):
|
||||
self.pin, self.original, self.expected = pin, original, expected
|
||||
self.code = pin.read_file(PEER_CODE, 128 * 1024)
|
||||
require(sha(self.code[0]) == PEER_ORIGIN['peer_namespace_controller_sha256'], 'reviewed_peer_namespace_controller')
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_namespace_guard', loader=None))
|
||||
module.__file__ = str(PEER_CODE)
|
||||
exec(compile(self.code[0], str(PEER_CODE), 'exec'), module.__dict__)
|
||||
self.namespace = module
|
||||
require(module.MAIN_SHA == PEER_MAIN_SHA and sha(module.LOCAL_BYTES) == PEER_ORIGIN['peer_namespace_local_profile_sha256'] and
|
||||
module.expected_acl().hex() == expected['parent_access_acl_hex'], 'fixed_peer_namespace_contract')
|
||||
self.verify()
|
||||
|
||||
def verify(self):
|
||||
pin, namespace = self.pin, self.namespace
|
||||
actual = self.original.fresh()
|
||||
require(pin.read_file(PEER_CODE, 128 * 1024) == self.code, 'peer_namespace_controller_unchanged')
|
||||
main, main_state = pin.read_file(namespace.MAIN, 65536, 0o644)
|
||||
local, local_state = pin.read_file(namespace.LOCAL, 16384, 0o644)
|
||||
require(sha(main) == PEER_MAIN_SHA and sha(local) == PEER_ORIGIN['peer_namespace_local_profile_sha256'] and
|
||||
local == namespace.LOCAL_BYTES and main_state == self.expected['main_profile_metadata'] and
|
||||
local_state == self.expected['local_profile_metadata'], 'actual_held_peer_profiles_unchanged')
|
||||
parent = pin.directory(namespace.PARENT)
|
||||
try:
|
||||
require(namespace.acl(parent) == namespace.expected_acl() and
|
||||
namespace.acl(parent, 'system.posix_acl_default') is None, 'actual_exact_peer_parent_acl')
|
||||
finally:
|
||||
os.close(parent)
|
||||
require(namespace.profile_state(actual['daemon_pid']) == self.expected['profile'], 'actual_chronyd_profile_still_enforcing')
|
||||
self.original.fresh()
|
||||
|
||||
|
||||
# Closed system-manager load namespace, including control, attached and
|
||||
@@ -381,45 +488,39 @@ class Context:
|
||||
self.pin, self.pin_guard = pin, pin_guard
|
||||
self.retained_records = {}
|
||||
self.composition = None
|
||||
self.original = None
|
||||
# Closed before loading a new source generation, public-role getter,
|
||||
# entropy, phase directory, group or installation effect.
|
||||
require(type(QUALITY_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_RESULT_SHA),
|
||||
'actual_new_generation_quality_pass_not_bound')
|
||||
try:
|
||||
self.original, self.generation_guard = protected_generation(pin)
|
||||
require(self.original.artifacts['rmm-time-broker-linux'][1] ==
|
||||
{'bytes': BROKER_BYTES, 'sha256': BROKER_SHA, 'elf_machine': 183}, 'original_exact_broker_elf')
|
||||
self.quality_records = quality_proof(pin, self.original)
|
||||
self.original.namespace_verify()
|
||||
self.forbidden, self.roles = forbidden_keys(pin, self.original)
|
||||
self.fresh()
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
if self.composition is not None:
|
||||
self.composition.close()
|
||||
self.composition = None
|
||||
if self.original is not None:
|
||||
self.original.close()
|
||||
self.original = None
|
||||
operator, guard = pin.load_operator()
|
||||
self.original = pin.Original(CASE, operator, guard)
|
||||
require(self.original.artifacts['rmm-time-broker-linux'][1] ==
|
||||
{'bytes': BROKER_BYTES, 'sha256': BROKER_SHA, 'elf_machine': 183}, 'original_exact_broker_elf')
|
||||
require(not (CASE / 'pin/failure.json').exists(), 'original_pin_failed')
|
||||
self.pin_result = pin.read_file(CASE / 'pin/result.json')
|
||||
result = pin.parsed(self.pin_result[0])
|
||||
require(result['profile'] == pin.PROFILE and result['case'] == CASE_ID and
|
||||
result['operator_sha256'] == pin.OPERATOR_SHA and result['source_tar_sha256'] == self.original.source_sha and
|
||||
result['manifest_sha256'] == self.original.manifest_sha and result['runtime_boot_chrony_preserved'] is True and
|
||||
result['signer_created'] is False and result['services_started'] is False,
|
||||
'original_successful_public_pin')
|
||||
self.public_pin_result = result
|
||||
self.quality_records, peer_witness = quality_proof(pin, self.original, self.pin_result[0], result)
|
||||
self.peer_proof = PeerNamespaceProof(pin, self.original, peer_witness)
|
||||
self.forbidden, self.roles = forbidden_keys(pin, self.original)
|
||||
self.fresh()
|
||||
|
||||
def fresh(self):
|
||||
self.pin_guard()
|
||||
self.generation_guard()
|
||||
current = self.original.fresh()
|
||||
self.original.namespace_verify()
|
||||
self.peer_proof.verify()
|
||||
for path, record in {**self.quality_records, **self.retained_records}.items():
|
||||
require(self.pin.read_file(path, 65536) == record, 'original_actual_quality_proof_unchanged')
|
||||
require(self.pin.read_file(path, 16384) == record, 'original_actual_quality_proof_unchanged')
|
||||
require(self.pin.read_file(CASE / 'pin/result.json') == self.pin_result, 'original_pin_result_unchanged')
|
||||
raw, proof = self.pin.read_file(ETC / 'chrony-pin.json', 8192)
|
||||
require(raw == self.original.public_pin_raw == encoded(current) and
|
||||
proof == self.original.public_pin_metadata, 'new_generation_chrony_pin_unchanged')
|
||||
require(raw == encoded(current) and sha(raw) == self.public_pin_result['public_pin_sha256'] and
|
||||
proof == self.public_pin_result['public_pin_metadata'], 'original_chrony_pin_unchanged')
|
||||
for path in (ETC, Path('/run/rmm-time-source'), Path('/run/rmm-time-source/clients')):
|
||||
before = self.public_pin_result['targets'][str(path)]
|
||||
fd = self.pin.directory(path)
|
||||
try:
|
||||
require(self.pin.stable_directory(os.fstat(fd)) == self.original.target_directories[str(path)],
|
||||
require(self.pin.stable_directory(os.fstat(fd)) == {key: before[key] for key in ('dev', 'ino', 'uid', 'gid', 'mode')},
|
||||
'original_runtime_directory_identity')
|
||||
finally:
|
||||
os.close(fd)
|
||||
@@ -585,16 +686,10 @@ def phase(name, action, pin, pin_guard):
|
||||
context.fresh()
|
||||
pin.exclusive(phase_fd, 'intent.json', encoded({'profile': PROFILE, 'case': CASE_ID, 'phase': name,
|
||||
'controller_sha256': sha(Path(__file__).read_bytes()), 'pin_controller_sha256': PIN_SHA,
|
||||
'source_tar_sha256': context.original.source_sha, 'manifest_sha256': context.original.manifest_sha,
|
||||
'generation_case': GENERATION_CASE_ID, 'generation_controller_sha256': QUALITY_CONTROLLER_SHA,
|
||||
'quality_result_sha256': QUALITY_RESULT_SHA,
|
||||
'chrony_public_pin_sha256': sha(context.original.public_pin_raw)}))
|
||||
'source_tar_sha256': context.original.source_sha, 'manifest_sha256': context.original.manifest_sha}))
|
||||
result = action(context)
|
||||
context.fresh()
|
||||
receipt = {'profile': PROFILE, 'case': CASE_ID, 'phase': name, 'result': result,
|
||||
'generation_case': GENERATION_CASE_ID, 'generation_controller_sha256': QUALITY_CONTROLLER_SHA,
|
||||
'quality_result_sha256': QUALITY_RESULT_SHA,
|
||||
'chrony_public_pin_sha256': sha(context.original.public_pin_raw)}
|
||||
receipt = {'profile': PROFILE, 'case': CASE_ID, 'phase': name, 'result': result}
|
||||
pin.exclusive(phase_fd, 'result.json', encoded(receipt))
|
||||
print(encoded(receipt).decode('ascii'), end='')
|
||||
except Exception as error:
|
||||
@@ -606,8 +701,8 @@ def phase(name, action, pin, pin_guard):
|
||||
print(encoded(failure).decode('ascii'), end='')
|
||||
raise SystemExit(1)
|
||||
finally:
|
||||
if context is not None:
|
||||
context.close()
|
||||
if context is not None and context.composition is not None:
|
||||
context.composition.close()
|
||||
if phase_fd >= 0:
|
||||
os.close(phase_fd)
|
||||
os.close(case_fd)
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Once-only public UDS signature fixture; no private signer read or RMM authority."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
START_SHA = 'e1458cb3feecd3d3302f2fccaff4850cfc8c403ee3314563f5f641e7c8bdfc39'
|
||||
START_RESULT_SHA = '8fc6ed5193f9802b7686a93523730c7e805595415c8e887552ffcf4224968d4d'
|
||||
CONTAINER_IMAGE = 'sha256:e6f2cff35d0f309acf8433b4f05878ed77092602c5065cc81801177da0bb3a9c'
|
||||
PYTHON_IMAGE_QUALIFIED = True
|
||||
PYTHON_IMAGE_RECEIPT_SHA = '6431222d42559e79e3aff9e074d743431240bfd173591cbd52ad106921c19114'
|
||||
PUBLIC_PIN_SHA = 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'
|
||||
CASE = Path('/var/lib/rmm-time-source-bootstrap/5b358997-3abc-43db-945f-f41855b4e3c0')
|
||||
PHASE = 'broker-signature-acceptance-v1'
|
||||
PROFILE = 'rmm.server-time-broker.unix-signature-acceptance.v1'
|
||||
ENDPOINT = 'https://discovery.ease-technologies.de/agent/v1/time-attestation'
|
||||
CTX_KEYS = ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_generation','connection_generation','windows_boot_id')
|
||||
DOMAIN = b'RMM-TIME-ATTESTATION/v1\0'
|
||||
SPKI = bytes.fromhex('302a300506032b6570032100')
|
||||
CLIENT = r'''
|
||||
import json,os,socket,struct,sys,time,uuid
|
||||
x=json.load(sys.stdin);mode=x['mode']
|
||||
expected=0 if mode=='root' else 10001
|
||||
assert os.getuid()==os.geteuid()==expected and os.getgid()==os.getegid()==expected
|
||||
if mode!='root':
|
||||
c={k:x['context'][k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_generation','connection_generation','windows_boot_id')}
|
||||
c.update(verifier_incarnation=str(uuid.UUID(bytes=os.getrandom(16),version=4)),role='agent',helper_image_sha256=None,binding_schema=1)
|
||||
nonce=os.getrandom(32);assert len(nonce)==32
|
||||
request={'version':1,'endpoint':x['endpoint'],'nonce':nonce.hex(),'context':c}
|
||||
raw=json.dumps(request,ensure_ascii=False,separators=(',',':')).encode('utf-8');assert 1<=len(raw)<=8192
|
||||
s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);s.settimeout(1)
|
||||
started=time.monotonic_ns();s.connect('/run/rmm-time-source/broker.sock')
|
||||
peer=struct.unpack('3i',s.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))
|
||||
assert peer[1:]==(0,989) and (peer[0]==0 if mode=='container' else peer[0]==x['broker_pid'])
|
||||
if mode=='root':
|
||||
try:
|
||||
out=s.recv(1);assert out==b'';denial='eof'
|
||||
except ConnectionResetError:denial='reset'
|
||||
result={'mode':mode,'peer':peer,'received_bytes':0,'denial':denial}
|
||||
else:
|
||||
s.sendall(struct.pack('!I',len(raw))+raw)
|
||||
def exact(n):
|
||||
data=b''
|
||||
while len(data)<n:
|
||||
part=s.recv(n-len(data));assert part;data+=part
|
||||
return data
|
||||
length=struct.unpack('!I',exact(4))[0];assert 1<=length<=8192
|
||||
response=exact(length);assert s.recv(1)==b''
|
||||
result={'mode':mode,'peer':peer,'request':raw.decode('utf-8'),'response':response.decode('utf-8')}
|
||||
s.close();result.update(uid=os.geteuid(),gid=os.getegid(),pid=os.getpid(),pid_namespace_inode=os.stat('/proc/self/ns/pid').st_ino,elapsed_ns=time.monotonic_ns()-started)
|
||||
print(json.dumps(result,separators=(',',':')))
|
||||
'''
|
||||
|
||||
|
||||
def require(value,reason):
|
||||
if not value:raise RuntimeError(reason)
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return (json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=True)+'\n').encode('ascii')
|
||||
|
||||
|
||||
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def load_start():
|
||||
path=Path('/var/lib/rmm-time-source-operators')/START_SHA/'broker_start_acceptance.py'
|
||||
parent=os.open('/',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
||||
try:
|
||||
for name in path.parent.parts[1:]:
|
||||
info=os.fstat(parent);require(info.st_uid==0 and info.st_mode&0o022==0,'protected_start_source_ancestry')
|
||||
child=os.open(name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parent);os.close(parent);parent=child
|
||||
directory=os.fstat(parent);require(directory.st_uid==0 and directory.st_mode&0o022==0,'protected_start_source_parent')
|
||||
fd=os.open(path.name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=parent)
|
||||
with os.fdopen(fd,'rb') as stream:
|
||||
info=os.fstat(stream.fileno());require(stat.S_ISREG(info.st_mode) and info.st_uid==info.st_gid==0 and stat.S_IMODE(info.st_mode)==0o600 and info.st_nlink==1 and info.st_size<=131072,'root_start_source_file')
|
||||
raw=stream.read(131073);stamp=lambda x:tuple(getattr(x,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
||||
require(sha(raw)==START_SHA and len(raw)==info.st_size and stamp(info)==stamp(os.fstat(stream.fileno()))==stamp(os.stat(path.name,dir_fd=parent,follow_symlinks=False)),'exact_reviewed_start_source')
|
||||
finally:os.close(parent)
|
||||
module=importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_signature_start_proof',loader=None));module.__file__=str(path);exec(compile(raw,str(path),'exec'),module.__dict__)
|
||||
bootstrap,pin,guard=module.load_bootstrap();held=pin.read_file(path,131072)
|
||||
require(held[0]==raw,'same_held_start_source')
|
||||
return module,bootstrap,pin,lambda:(guard(),require(pin.read_file(path,131072)==held,'start_source_unchanged'))
|
||||
|
||||
|
||||
def fixed_inputs():
|
||||
require(type(START_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}',START_RESULT_SHA),'actual_start_not_bound')
|
||||
require(type(CONTAINER_IMAGE) is str and re.fullmatch('sha256:[0-9a-f]{64}',CONTAINER_IMAGE),'actual_cached_python_image_not_bound')
|
||||
require(PYTHON_IMAGE_QUALIFIED is True,'cached_arm_python_not_qualified')
|
||||
|
||||
|
||||
def request(raw,expected_context):
|
||||
value=json.loads(raw);require(list(value)==['version','endpoint','nonce','context'] and value['version']==1 and value['endpoint']==ENDPOINT and re.fullmatch('[0-9a-f]{64}',value['nonce']),'exact_request_order_nonce_endpoint')
|
||||
context=value['context'];require(list(context)==list(CTX_KEYS)+['verifier_incarnation','role','helper_image_sha256','binding_schema'] and all(context[k]==v for k,v in expected_context.items()) and context['role']=='agent' and context['helper_image_sha256'] is None and context['binding_schema']==1 and str(uuid.UUID(context['verifier_incarnation']))==context['verifier_incarnation'] and uuid.UUID(context['verifier_incarnation']).int>0,'exact_public_request_context')
|
||||
require(json.dumps(value,ensure_ascii=False,separators=(',',':'))==raw,'rust_canonical_request_bytes')
|
||||
return value
|
||||
|
||||
|
||||
def run_client(mode,pid,context):
|
||||
args=['/usr/bin/setpriv','--reuid=10001','--regid=10001','--clear-groups','--no-new-privs','/usr/bin/python3','-I','-c',CLIENT]
|
||||
if mode=='root':args=['/usr/bin/python3','-I','-c',CLIENT]
|
||||
if mode=='container':args=['/usr/bin/docker','run','-i','--rm','--network=none','--read-only','--cap-drop=ALL','--security-opt=no-new-privileges','--user=10001:10001','--pids-limit=16','--memory=128m','--mount=type=bind,src=/run/rmm-time-source,dst=/run/rmm-time-source,readonly','--entrypoint=/usr/bin/python3',CONTAINER_IMAGE,'-I','-c',CLIENT]
|
||||
result=subprocess.run(args,input=encoded(dict(mode=mode,context=context,endpoint=ENDPOINT,broker_pid=pid)),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20,check=False,env={'PATH':'/usr/bin:/bin','LC_ALL':'C'})
|
||||
require(result.returncode==0 and result.stderr==b'' and len(result.stdout)<=32768,'one_fixed_client_failed_no_retry')
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def verify_reply(proof,pin,phase,mode,value,public,boot,context):
|
||||
require(value['uid']==value['gid']==10001 and value['peer'][1:]==[0,989] and value['elapsed_ns']>0,'actual_client_identity_and_peer')
|
||||
raw=value['request'];rq=request(raw,context);signed=json.loads(value['response'])
|
||||
require(list(signed)==['payload','signature_hex'] and json.dumps(signed,ensure_ascii=False,separators=(',',':'))==value['response'] and type(signed['payload']) is str and re.fullmatch('[0-9a-f]{128}',signed['signature_hex']),'exact_signed_envelope')
|
||||
payload=json.loads(signed['payload'])
|
||||
require(list(payload)==['version','request_sha256','server_instance','server_boot_id','key_id','key_generation','captured_utc_ns','server_error_ns','source_sync_age_ns'] and json.dumps(payload,ensure_ascii=False,separators=(',',':'))==signed['payload'] and payload['version']==1 and payload['request_sha256']==sha(raw.encode()) and payload['server_instance']==public['server_instance'] and payload['server_boot_id']==boot and payload['key_id']==public['key_id'] and payload['key_generation']==public['key_generation'] and type(payload['captured_utc_ns']) is int and 0<payload['captured_utc_ns']<2**63 and type(payload['server_error_ns']) is int and 0<=payload['server_error_ns']<=500000000 and type(payload['source_sync_age_ns']) is int and 0<=payload['source_sync_age_ns']<=3600000000000,'bound_full_request_server_generation_boot_and_quality')
|
||||
save(pin,phase,mode+'.request.json',raw.encode());save(pin,phase,mode+'.response.json',value['response'].encode());save(pin,phase,mode+'.message.bin',DOMAIN+signed['payload'].encode());save(pin,phase,mode+'.signature.bin',bytes.fromhex(signed['signature_hex']))
|
||||
result=proof.bootstrap.command(pin,Path('/usr/bin/openssl'),['pkeyutl','-verify','-pubin','-inkey',str(CASE/PHASE/'public.der'),'-keyform','DER','-rawin','-in',str(CASE/PHASE/(mode+'.message.bin')),'-sigfile',str(CASE/PHASE/(mode+'.signature.bin'))])
|
||||
require(result.returncode==0,'actual_ed25519_public_signature_verification')
|
||||
return dict(request_sha256=payload['request_sha256'],nonce=rq['nonce'],verifier_incarnation=rq['context']['verifier_incarnation'],signature_verified=True,payload=payload,client=value)
|
||||
|
||||
|
||||
def save(pin,parent,name,raw):
|
||||
require(name in {'intent.json','before.json','after.json','result.json','failure.json','public.der'} or re.fullmatch('(host|container)\.(request.json|response.json|message.bin|signature.bin)',name),'closed_public_case_filename')
|
||||
data=raw if type(raw) is bytes else encoded(raw);require(len(data)<=65536,'bounded_public_evidence')
|
||||
fd=os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=parent)
|
||||
try:
|
||||
view=memoryview(data)
|
||||
while view:n=os.write(fd,view);require(n>0,'complete_public_evidence_write');view=view[n:]
|
||||
os.fsync(fd)
|
||||
finally:os.close(fd)
|
||||
os.fsync(parent)
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=('host-preflight','host-execute','host-read'));args=parser.parse_args()
|
||||
require(sys.flags.isolated==1 and os.geteuid()==0 and os.uname().machine=='aarch64','isolated_root_fixed_server_only');os.umask(0o077)
|
||||
fixed_inputs();module,bootstrap,pin,guard=load_start()
|
||||
if args.command=='host-read':
|
||||
records={}
|
||||
for name in ('intent.json','before.json','after.json','result.json','failure.json'):
|
||||
try:
|
||||
raw,meta=pin.read_file(CASE/PHASE/name,65536);records[name]=dict(sha256=sha(raw),metadata=meta,record=pin.parsed(raw))
|
||||
except FileNotFoundError:records[name]=None
|
||||
print(encoded(dict(profile=PROFILE,read_only=True,records=records)).decode(),end='');return
|
||||
case=pin.directory(CASE);phase=-1;proof=process=None
|
||||
try:
|
||||
pin.absence(case,PHASE);proof=module.InstalledProof(bootstrap,pin,guard)
|
||||
own=proof.context.original.hold(Path(__file__),131072);require(own.path.name=='broker_signature_acceptance.py' and own.path.parent.name==sha(own.raw),'held_exact_signature_fixture_source')
|
||||
start=proof.context.original.hold(CASE/module.PHASE/'result.json',65536,expected=START_RESULT_SHA);start_result=pin.parsed(start.raw)
|
||||
require(start_result['effective_unit_qualified'] is True and start_result['start_executed_once'] is True,'original_successful_start')
|
||||
phase_start=pin.directory(CASE/module.PHASE)
|
||||
try:pin.absence(phase_start,'failure.json')
|
||||
finally:os.close(phase_start)
|
||||
state=module.effective(module.typed_snapshot(proof),True);process=module.ProcessProof(proof,state)
|
||||
require(process.expected==start_result['process'] and module.socket_proof(proof,process)==start_result['socket'],'same_original_running_broker_and_listener')
|
||||
before=proof.fresh();require(sha(proof.public.raw)==PUBLIC_PIN_SHA,'actual_fixed_public_time_pin');public=pin.parsed(proof.public.raw);host_ns=os.stat('/proc/self/ns/pid').st_ino
|
||||
if args.command=='host-preflight':
|
||||
print(encoded(dict(profile=PROFILE,read_only=True,qualified_running=True,process=process.expected,socket=start_result['socket'],public_pin_sha256=PUBLIC_PIN_SHA,public_pin=public,signature_query_sent=False,evidence_written=False)).decode(),end='');return
|
||||
# Explicit Root decision: own codec-only CSPRNG fixture identities,
|
||||
# never an enrolled device, current DB generation, mTLS or clock proof.
|
||||
identity=lambda:str(uuid.UUID(bytes=os.getrandom(16),version=4))
|
||||
context=dict(tenant_id=identity(),asset_id=identity(),agent_id=identity(),enrollment_generation=1,assignment_generation=1,connection_generation=1,windows_boot_id=identity())
|
||||
os.mkdir(PHASE,0o700,dir_fd=case);os.fsync(case);phase=os.open(PHASE,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=case)
|
||||
bind=dict(profile=PROFILE,case=CASE.name,phase=PHASE,controller_sha256=sha(own.raw),start_controller_sha256=START_SHA,start_result_sha256=START_RESULT_SHA,public_pin_sha256=sha(proof.public.raw),container_image=CONTAINER_IMAGE,python_image_receipt_sha256=PYTHON_IMAGE_RECEIPT_SHA,context=context,context_authority='operator_fixture_csprng_only_not_enrolled_or_mtls')
|
||||
save(pin,phase,'intent.json',dict(bind,once=True,no_retry=True));save(pin,phase,'before.json',dict(bind,witness=before,process=process.expected,socket=start_result['socket']))
|
||||
save(pin,phase,'public.der',SPKI+bytes.fromhex(public['public_key_hex']))
|
||||
host=run_client('host',process.pid,context);require(host['peer'][0]==process.pid and host['pid_namespace_inode']==host_ns,'host_client_actual_peer_pid_namespace')
|
||||
positive=verify_reply(proof,pin,phase,'host',host,public,before['observation']['boot_id'],context)
|
||||
denied=run_client('root',process.pid,context);require(denied['uid']==denied['gid']==0 and denied['peer']==[process.pid,0,989] and denied['received_bytes']==0 and denied['denial'] in ('eof','reset'),'root_uid_denied_without_signed_bytes')
|
||||
container=run_client('container',process.pid,context);require(container['peer'][0]==0 and container['pid_namespace_inode']!=host_ns,'default_container_pid_namespace_sees_host_broker_pid_zero')
|
||||
isolated=verify_reply(proof,pin,phase,'container',container,public,before['observation']['boot_id'],context)
|
||||
require(positive['nonce']!=isolated['nonce'] and positive['verifier_incarnation']!=isolated['verifier_incarnation'],'separate_own_random_challenges')
|
||||
after=proof.fresh();require(before==after and process.verify(module.effective(module.typed_snapshot(proof),True))==start_result['process'] and module.socket_proof(proof,process)==start_result['socket'],'same_runtime_pin_generation_process_listener_after_three_clients')
|
||||
save(pin,phase,'after.json',dict(bind,witness=after,process=process.expected,socket=start_result['socket']))
|
||||
result=dict(bind,host=positive,root=denied,container=isolated,two_actual_signatures_verified=True,private_signer_read=False,clock_authority=False,mtls_identity_attested=False,sync_ready=False,rmm_jobs_created=False,corehistory_witness='external_root_before_after_receipts_required')
|
||||
save(pin,phase,'result.json',result);print(encoded(result).decode(),end='')
|
||||
except Exception:
|
||||
if phase>=0:save(pin,phase,'failure.json',dict(profile=PROFILE,failed=True,fixed_tag='signature_fixture_failed_original_read_only',no_retry_or_cleanup=True))
|
||||
raise
|
||||
finally:
|
||||
if process is not None:process.close()
|
||||
if proof is not None:proof.close()
|
||||
if phase>=0:os.close(phase)
|
||||
os.close(case)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception:
|
||||
print(encoded(dict(profile=PROFILE,failed=True,read_original_phase_only=True)).decode(),end='');raise SystemExit(1)
|
||||
@@ -1,449 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One fixed installed broker reload/start and process/socket observation only.
|
||||
|
||||
No enable/restart/stop/cleanup, Unix request, time signature or RMM job. Only
|
||||
host-read is permitted after uncertain effect; never repeat the start phase.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import select
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
|
||||
BOOTSTRAP_SHA = '2fdcbc951fe49f0a606dfd935d2e5b13d8680b7fb8c89209e7efb98b07896ea2'
|
||||
BOOTSTRAP = Path('/var/lib/rmm-time-source-operators') / BOOTSTRAP_SHA / 'broker_bootstrap.py'
|
||||
CASE_ID = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
||||
CASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE_ID
|
||||
PHASE = 'broker-start-acceptance-v1'
|
||||
PROFILE = 'rmm.server-time-broker.installed-start-acceptance.v1'
|
||||
UNIT_NAME = 'rmm-time-broker.service'
|
||||
UNIT = Path('/etc/systemd/system') / UNIT_NAME
|
||||
BINARY = Path('/usr/local/libexec/rmm-time-broker')
|
||||
SOCKET = Path('/run/rmm-time-source/broker.sock')
|
||||
UNIT_SHA = '4792bfb65763f5a5146044d2ba152acd0a876b66c29d8cc66c16a5250214af2c'
|
||||
BINARY_SHA = '5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201'
|
||||
RESULTS = {'broker-key':'fa81bde18a68c7c367ae7facf3914711072ba5238f0d10b5eba29c320efa3d75',
|
||||
'broker-group':'1f987cbe7e7558ecb1e4dac9542bda69d6f09343a40098c5be4817ac9ebfca45',
|
||||
'broker-install':'b52aa57971fcad5a9ff3780765f4712d4029d078aab71f94eaec6d805a642f71'}
|
||||
ABI_RECEIPT_SHA = '77c98ef563837e36c487227142258490d57b630b56b2c2f8db6474a51263aa0d'
|
||||
BUS_PATH = '/org/freedesktop/systemd1/unit/rmm_2dtime_2dbroker_2eservice'
|
||||
SERVICE_IFACE = 'org.freedesktop.systemd1.Service'
|
||||
UNIT_IFACE = 'org.freedesktop.systemd1.Unit'
|
||||
CAPS = 0x80002
|
||||
DEBUG_DENY = ['lookup_dcookie','perf_event_open','pidfd_getfd','process_vm_readv','process_vm_writev',
|
||||
'ptrace','rtas','s390_runtime_instr','sys_debug_setcontext']
|
||||
OTHER_EXEC = ('ExecCondition','ExecStartPre','ExecStartPost','ExecReload','ExecStop','ExecStopPost')
|
||||
RECORDS = ('intent.json','before.json','reload-intent.json','reload-exit.json','effective-before-start.json',
|
||||
'start-intent.json','start-exit.json','after.json','result.json','failure.json','reload.log','start.log')
|
||||
|
||||
|
||||
class Denied(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def require(value, reason):
|
||||
if not value:
|
||||
raise Denied(reason)
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return (json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=True)+'\n').encode('ascii')
|
||||
|
||||
|
||||
def bounded(path,maximum):
|
||||
with path.open('rb') as stream:raw = stream.read(maximum+1)
|
||||
require(len(raw) <= maximum,'bounded_fixed_kernel_observation')
|
||||
return raw
|
||||
|
||||
|
||||
def load_bootstrap():
|
||||
current = os.open('/',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
||||
try:
|
||||
for name in BOOTSTRAP.parent.parts[1:]:
|
||||
info = os.fstat(current)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0,'protected_bootstrap_ancestry')
|
||||
child = os.open(name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=current)
|
||||
os.close(current); current = child
|
||||
info = os.fstat(current)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0,'protected_bootstrap_parent')
|
||||
fd = os.open(BOOTSTRAP.name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=current)
|
||||
with os.fdopen(fd,'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
|
||||
stat.S_IMODE(before.st_mode) == 0o600 and before.st_nlink == 1 and before.st_size <= 131072,
|
||||
'reviewed_root_bootstrap_file')
|
||||
raw = stream.read(131073)
|
||||
proof = tuple(getattr(before,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
||||
actual = lambda x: tuple(getattr(x,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
||||
require(len(raw) == before.st_size and sha(raw) == BOOTSTRAP_SHA and
|
||||
proof == actual(os.fstat(stream.fileno())) == actual(os.stat(BOOTSTRAP.name,dir_fd=current,follow_symlinks=False)),
|
||||
'exact_bootstrap_bytes_and_identity')
|
||||
finally:
|
||||
os.close(current)
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_installed_broker_bootstrap',loader=None))
|
||||
module.__file__ = str(BOOTSTRAP)
|
||||
exec(compile(raw,str(BOOTSTRAP),'exec'),module.__dict__)
|
||||
pin,pin_guard = module.protected_code()
|
||||
held = pin.read_file(BOOTSTRAP,131072)
|
||||
require(held[0] == raw,'same_loaded_bootstrap_bytes')
|
||||
def guard():
|
||||
pin_guard()
|
||||
require(pin.read_file(BOOTSTRAP,131072) == held,'reviewed_bootstrap_unchanged')
|
||||
return module,pin,guard
|
||||
|
||||
|
||||
class InstalledProof:
|
||||
"""Actual qualified installation, never a bypass/adoption of UnitComposition."""
|
||||
def __init__(self,bootstrap,pin,guard):
|
||||
self.bootstrap,self.pin,self.guard = bootstrap,pin,guard
|
||||
self.load_paths = None
|
||||
self.context = None; self.signer_fd = -1; self.signer_parent = -1
|
||||
try:
|
||||
self.context = bootstrap.Context(pin,guard)
|
||||
own = self.context.original.hold(Path(__file__),131072)
|
||||
require(own.path.name == 'broker_start_acceptance.py' and own.path.parent.name == sha(own.raw),
|
||||
'exact_content_addressed_start_controller')
|
||||
self.results = {}
|
||||
for phase,digest in RESULTS.items():
|
||||
directory = pin.directory(CASE/phase)
|
||||
try: pin.absence(directory,'failure.json')
|
||||
finally: os.close(directory)
|
||||
held = self.context.original.hold(CASE/phase/'result.json',65536,expected=digest)
|
||||
value = pin.parsed(held.raw)
|
||||
require(value['profile'] == bootstrap.PROFILE and value['case'] == CASE_ID and value['phase'] == phase and
|
||||
value['generation_case'] == bootstrap.GENERATION_CASE_ID and
|
||||
value['generation_controller_sha256'] == bootstrap.QUALITY_CONTROLLER_SHA and
|
||||
value['quality_result_sha256'] == bootstrap.QUALITY_RESULT_SHA,
|
||||
'exact_successful_own_installation_origin')
|
||||
self.results[phase] = value['result']
|
||||
installed = self.results['broker-install']
|
||||
require(installed['binary_sha256'] == BINARY_SHA and installed['binary_bytes'] == 1067136 and
|
||||
installed['unit_sha256'] == UNIT_SHA and all(installed[k] is False for k in
|
||||
('daemon_reload','service_enabled','broker_started','time_signed')),
|
||||
'actual_installed_not_started_broker')
|
||||
require(sha(bootstrap.UNIT_RAW) == UNIT_SHA and len(bootstrap.UNIT_RAW) == 657,'reviewed_exact_unit_source')
|
||||
self.unit = self.context.original.hold(UNIT,8192,0o644,UNIT_SHA,installed['unit_metadata'])
|
||||
self.load_paths = tuple(installed['manager_unit_load_paths'])
|
||||
self.binary = self.context.original.hold(BINARY,2*1024*1024,0o500,BINARY_SHA,installed['binary_metadata'])
|
||||
key = self.results['broker-key']
|
||||
self.public = self.context.original.hold(bootstrap.PUBLIC,8192,expected=key['public_pin_sha256'],metadata=key['public_pin_metadata'])
|
||||
public = pin.parsed(self.public.raw)
|
||||
require(public == key['public_pin'] and public['algorithm'] == 'Ed25519' and
|
||||
public['public_key_hex'] not in self.context.forbidden,'retained_separate_public_time_key')
|
||||
self.signer_metadata = key['signer_metadata']
|
||||
self.signer_parent = pin.directory(bootstrap.SIGNER.parent)
|
||||
self.signer_fd = os.open(bootstrap.SIGNER.name,os.O_PATH|os.O_NOFOLLOW,dir_fd=self.signer_parent)
|
||||
# Metadata-only O_PATH: this controller never reads signing seeds.
|
||||
self.fresh()
|
||||
except BaseException:
|
||||
self.close(); raise
|
||||
|
||||
def composition(self):
|
||||
# A separate qualified installed proof permits only the original own
|
||||
# unit inode. Never instantiate/bypass UnitComposition's absence guard.
|
||||
require(self.bootstrap.manager_unit_paths(self.context) == self.load_paths,'same_original_manager_load_paths')
|
||||
roots = list(self.bootstrap.UNIT_ROOTS)
|
||||
alias = Path('/lib');alias_state = None
|
||||
if os.path.lexists(alias):
|
||||
alias_state = self.bootstrap.stamp(alias.lstat())
|
||||
if alias.is_symlink():
|
||||
require(alias.lstat().st_uid == 0 and os.readlink(alias) in ('usr/lib','/usr/lib'),'fixed_merged_usr_alias')
|
||||
else:
|
||||
extra = self.pin.directory(alias);os.close(extra);roots.append(alias/'systemd/system')
|
||||
else:
|
||||
require('/lib/systemd/system' not in self.load_paths,'missing_original_legacy_unit_load_root')
|
||||
for root in roots:
|
||||
try:fd = self.pin.directory(root)
|
||||
except FileNotFoundError:continue
|
||||
try:
|
||||
before = self.pin.stable_directory(os.fstat(fd))
|
||||
for leaf in self.bootstrap.UNIT_LEAVES:
|
||||
try:meta = self.pin.identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))
|
||||
except FileNotFoundError:continue
|
||||
require(root/leaf == UNIT and meta == self.unit.metadata,'unexpected_installed_unit_composition')
|
||||
names = os.listdir(fd);require(len(names) <= 8192,'bounded_installed_load_directory')
|
||||
for name in names:
|
||||
if stat.S_ISLNK(os.stat(name,dir_fd=fd,follow_symlinks=False).st_mode):
|
||||
require(Path(os.readlink(name,dir_fd=fd)).name != UNIT_NAME,'unexpected_installed_unit_alias')
|
||||
require(self.pin.stable_directory(os.fstat(fd)) == before,'same_installed_load_directory')
|
||||
finally:os.close(fd)
|
||||
if alias_state is not None:
|
||||
require(self.bootstrap.stamp(alias.lstat()) == alias_state,'same_merged_usr_alias')
|
||||
require(self.bootstrap.manager_unit_paths(self.context) == self.load_paths,'same_original_manager_load_paths')
|
||||
|
||||
def fresh(self):
|
||||
self.guard(); self.context.fresh(); self.composition()
|
||||
pin = self.pin
|
||||
require(pin.identity(os.fstat(self.signer_fd)) == self.signer_metadata ==
|
||||
pin.identity(os.stat(self.bootstrap.SIGNER.name,dir_fd=self.signer_parent,follow_symlinks=False)),
|
||||
'same_original_private_signer_metadata_without_read')
|
||||
fresh_parent = pin.directory(self.bootstrap.SIGNER.parent)
|
||||
try: require(pin.stable_directory(os.fstat(fresh_parent)) == pin.stable_directory(os.fstat(self.signer_parent)),
|
||||
'same_private_signer_parent')
|
||||
finally: os.close(fresh_parent)
|
||||
lookup = self.bootstrap.group_lookup
|
||||
require(lookup('rmm-time-gateway') == lookup(10001) == {'name':'rmm-time-gateway','gid':10001,'members':[]} and
|
||||
lookup('_chrony')['gid'] == 989 and lookup(989)['name'] == '_chrony','exact_existing_installed_groups')
|
||||
return self.context.original.witness()
|
||||
|
||||
def close(self):
|
||||
for name in ('signer_fd','signer_parent'):
|
||||
value = getattr(self,name)
|
||||
if value >= 0: os.close(value); setattr(self,name,-1)
|
||||
if self.context is not None: self.context.close(); self.context = None
|
||||
|
||||
|
||||
def typed(proof,interface,name,signature):
|
||||
raw = proof.context.original.operator.run(['/usr/bin/busctl','--system','--json=short','get-property',
|
||||
'org.freedesktop.systemd1',BUS_PATH,interface,name],timeout=3,limit=32768)
|
||||
value = proof.pin.parsed(raw)
|
||||
require(type(value) is dict and set(value) == {'type','data'} and value['type'] == signature,
|
||||
'exact_typed_loaded_property')
|
||||
return value['data']
|
||||
|
||||
|
||||
def typed_snapshot(proof):
|
||||
# Actual Root-read ABI: systemd259.5 Ubuntu, receipt77c98e. No invented zeros.
|
||||
specs = {'User':'s','Group':'s','SupplementaryGroups':'as','Type':'s','Restart':'s','NRestarts':'u',
|
||||
'CapabilityBoundingSet':'t','AmbientCapabilities':'t','NoNewPrivileges':'b','ProtectSystem':'s','ProtectHome':'s',
|
||||
'PrivateTmp':'b','PrivateDevices':'b','RestrictAddressFamilies':'(bas)','IPAddressDeny':'a(iayu)',
|
||||
'IPAddressAllow':'a(iayu)','SystemCallFilter':'(bas)','ReadWritePaths':'as','UMask':'u','LimitCORE':'t',
|
||||
'MainPID':'u','ControlPID':'u','ControlGroup':'s','ExecStartEx':'a(sasasttttuii)'}
|
||||
value = {name:typed(proof,SERVICE_IFACE,name,signature) for name,signature in specs.items()}
|
||||
for name in OTHER_EXEC:
|
||||
value[name] = typed(proof,SERVICE_IFACE,name,'a(sasbttttuii)')
|
||||
value[name+'Ex'] = typed(proof,SERVICE_IFACE,name+'Ex','a(sasasttttuii)')
|
||||
for name,signature in {'Id':'s','LoadState':'s','ActiveState':'s','SubState':'s','FragmentPath':'s',
|
||||
'DropInPaths':'as','UnitFileState':'s','NeedDaemonReload':'b','Job':'(uo)','InvocationID':'ay'}.items():
|
||||
value[name] = typed(proof,UNIT_IFACE,name,signature)
|
||||
return value
|
||||
|
||||
|
||||
def effective(value,running=False):
|
||||
require(value['Id'] == UNIT_NAME and value['LoadState'] == 'loaded' and value['FragmentPath'] == str(UNIT) and
|
||||
value['DropInPaths'] == [] and value['UnitFileState'] == 'static' and value['NeedDaemonReload'] is False and
|
||||
value['Job'] == [0,'/'],'exact_loaded_fragment_no_dropins_enable_or_pending_job')
|
||||
require(value['Type'] == 'exec' and value['Restart'] == 'no' and type(value['NRestarts']) is int and value['NRestarts'] == 0 and
|
||||
value['User'] == 'root' and value['Group'] == '_chrony' and value['SupplementaryGroups'] == ['rmm-time-gateway'],
|
||||
'exact_effective_identity_type_and_no_restart')
|
||||
require(type(value['CapabilityBoundingSet']) is int and value['CapabilityBoundingSet'] == CAPS and
|
||||
type(value['AmbientCapabilities']) is int and value['AmbientCapabilities'] == 0 and
|
||||
all(value[k] is True for k in ('NoNewPrivileges','PrivateTmp','PrivateDevices')) and
|
||||
value['ProtectHome'] == 'yes' and value['ProtectSystem'] == 'strict' and
|
||||
value['RestrictAddressFamilies'] == [True,['AF_UNIX']] and value['IPAddressAllow'] == [] and
|
||||
value['IPAddressDeny'] == [[2,[0]*4,0],[10,[0]*16,0]] and value['SystemCallFilter'] == [False,DEBUG_DENY] and
|
||||
value['ReadWritePaths'] == ['/run/rmm-time-source'] and value['UMask'] == 0o77 and value['LimitCORE'] == 0,
|
||||
'exact_effective_caps_network_filesystem_and_syscall_limits')
|
||||
rows = value['ExecStartEx']
|
||||
require(type(rows) is list and len(rows) == 1 and type(rows[0]) is list and len(rows[0]) == 10 and
|
||||
rows[0][:3] == [str(BINARY),[str(BINARY)],[]] and
|
||||
all(type(v) is int and 0 <= v < 2**64 for v in rows[0][3:7]) and
|
||||
type(rows[0][7]) is int and 0 <= rows[0][7] < 2**32 and
|
||||
all(type(v) is int and -(2**31) <= v < 2**31 for v in rows[0][8:]) and
|
||||
all(value[name] == value[name+'Ex'] == [] for name in OTHER_EXEC),
|
||||
'single_exact_argv_without_flags_or_other_exec_commands')
|
||||
require(type(value['MainPID']) is int and type(value['ControlPID']) is int and value['ControlPID'] == 0,
|
||||
'actual_service_process_properties')
|
||||
require(type(value['InvocationID']) is list and
|
||||
all(type(x) is int and 0 <= x <= 255 for x in value['InvocationID']),'typed_actual_invocation_id')
|
||||
if running:
|
||||
require(value['ActiveState'] == 'active' and value['SubState'] == 'running' and value['MainPID'] > 1 and
|
||||
value['ControlGroup'] == '/system.slice/'+UNIT_NAME and
|
||||
len(value['InvocationID']) == 16 and any(value['InvocationID']),
|
||||
'one_running_broker_generation')
|
||||
else:
|
||||
require(value['ActiveState'] == 'inactive' and value['SubState'] == 'dead' and value['MainPID'] == 0 and
|
||||
value['InvocationID'] == [],
|
||||
'installed_broker_initially_inactive')
|
||||
return value
|
||||
|
||||
|
||||
class ProcessProof:
|
||||
def __init__(self,proof,state):
|
||||
self.proof,self.pid = proof,state['MainPID']; self.pidfd = -1; self.image_fd = -1
|
||||
try:
|
||||
self.pidfd = os.pidfd_open(self.pid)
|
||||
self.image_fd = os.open('/proc/'+str(self.pid)+'/exe',os.O_RDONLY|os.O_CLOEXEC)
|
||||
self.expected = None
|
||||
self.verify(state)
|
||||
except BaseException:
|
||||
self.close(); raise
|
||||
|
||||
def verify(self,state):
|
||||
effective(state,True); require(state['MainPID'] == self.pid,'same_started_broker_pid')
|
||||
poll = select.poll();poll.register(self.pidfd,select.POLLIN)
|
||||
require(not poll.poll(0),'held_started_broker_alive')
|
||||
proc = Path('/proc')/str(self.pid)
|
||||
before = (proc/'stat').read_text().rsplit(') ',1)[1].split(); birth = int(before[19])
|
||||
fields = {}
|
||||
for line in (proc/'status').read_text().splitlines():
|
||||
key,sep,data = line.partition(':')
|
||||
if key in ('Uid','Gid','Groups','CapEff','CapBnd','CapPrm','CapAmb','NoNewPrivs','Seccomp'):
|
||||
require(sep and key not in fields,'unique_native_process_status');fields[key] = data.split()
|
||||
require(set(fields) == {'Uid','Gid','Groups','CapEff','CapBnd','CapPrm','CapAmb','NoNewPrivs','Seccomp'} and
|
||||
fields['Uid'] == ['0']*4 and fields['Gid'] == ['989']*4 and
|
||||
set(map(int,fields['Groups'])) <= {0,989,10001} and 10001 in set(map(int,fields['Groups'])) and
|
||||
all(len(fields[k]) == 1 and int(fields[k][0],16) == CAPS for k in ('CapEff','CapBnd','CapPrm')) and
|
||||
fields['CapAmb'] == ['0000000000000000'] and fields['NoNewPrivs'] == ['1'] and fields['Seccomp'] == ['2'],
|
||||
'actual_broker_credentials_capabilities_nnp_seccomp')
|
||||
meta = self.proof.pin.identity(os.fstat(self.image_fd))
|
||||
require(meta == self.proof.binary.metadata == self.proof.pin.identity((proc/'exe').stat()),
|
||||
'held_actual_broker_image_is_exact_installed_inode')
|
||||
for name in ('user','pid','cgroup'):
|
||||
a,b = (proc/'ns'/name).stat(),(Path('/proc/1/ns')/name).stat()
|
||||
require((a.st_dev,a.st_ino) == (b.st_dev,b.st_ino),'broker_actual_host_namespaces')
|
||||
mounts = bounded(proc/'mountinfo',1024*1024)
|
||||
roots = [line.split() for line in mounts.decode('ascii').splitlines() if len(line.split()) >= 7 and line.split()[4] == '/']
|
||||
require(len(roots) == 1 and 'ro' in roots[0][5].split(','),'actual_protected_system_root_readonly')
|
||||
cgroup = (proc/'cgroup').read_text().splitlines()
|
||||
require(cgroup == ['0::/system.slice/'+UNIT_NAME],'broker_single_expected_cgroup')
|
||||
members = (Path('/sys/fs/cgroup/system.slice')/UNIT_NAME/'cgroup.procs').read_text().split()
|
||||
require(members == [str(self.pid)],'only_original_broker_cgroup_process')
|
||||
require(int((proc/'stat').read_text().rsplit(') ',1)[1].split()[19]) == birth and not poll.poll(0),
|
||||
'same_alive_broker_birth_after_observation')
|
||||
result = dict(pid=self.pid,birth_ticks=birth,image_sha256=BINARY_SHA,image_metadata=meta,
|
||||
invocation_id=state['InvocationID'],uid=0,gid=989,groups=sorted(map(int,fields['Groups'])),
|
||||
cap_effective=CAPS,cap_bounding=CAPS,no_new_privileges=True,seccomp_mode=2,
|
||||
host_namespaces=True,root_readonly=True,cgroup=state['ControlGroup'])
|
||||
require(self.expected is None or self.expected == result,'same_original_started_broker_generation')
|
||||
self.expected = result
|
||||
return result
|
||||
|
||||
def close(self):
|
||||
for name in ('image_fd','pidfd'):
|
||||
value = getattr(self,name)
|
||||
if value >= 0:os.close(value);setattr(self,name,-1)
|
||||
|
||||
|
||||
def socket_proof(proof,process):
|
||||
parent = proof.pin.directory(SOCKET.parent)
|
||||
try:
|
||||
before = proof.pin.stable_directory(os.fstat(parent))
|
||||
meta = proof.pin.identity(os.stat(SOCKET.name,dir_fd=parent,follow_symlinks=False))
|
||||
require(stat.S_ISSOCK(meta['mode']) and stat.S_IMODE(meta['mode']) == 0o660 and
|
||||
meta['uid'] == 0 and meta['gid'] == 10001 and meta['nlink'] == 1,'exact_new_broker_socket_inode')
|
||||
raw = bounded(Path('/proc/net/unix'),2*1024*1024)
|
||||
lines = [line.split() for line in raw.decode('ascii').splitlines()[1:] if len(line.split()) == 8 and line.split()[7] == str(SOCKET)]
|
||||
require(len(lines) == 1 and lines[0][3:6] == ['00010000','0001','01'] and re.fullmatch('[1-9][0-9]*',lines[0][6]),
|
||||
'one_actual_listening_unix_stream_socket')
|
||||
kernel_inode = int(lines[0][6]);fds = Path('/proc')/str(process.pid)/'fd';names = list(fds.iterdir())
|
||||
require(len(names) <= 256,'bounded_owned_broker_descriptors')
|
||||
holders = [int(path.name) for path in names if os.readlink(path) == 'socket:['+str(kernel_inode)+']']
|
||||
require(len(holders) == 1,'actual_original_broker_holds_listener')
|
||||
require(proof.pin.identity(os.stat(SOCKET.name,dir_fd=parent,follow_symlinks=False)) == meta and
|
||||
proof.pin.stable_directory(os.fstat(parent)) == before,'same_broker_socket_and_parent_after_observation')
|
||||
return dict(metadata=meta,kernel_inode=kernel_inode,broker_fd=holders[0])
|
||||
finally:
|
||||
os.close(parent)
|
||||
|
||||
|
||||
def save(pin,fd,name,value):
|
||||
require(name in RECORDS and name.endswith('.json'),'fixed_own_phase_record')
|
||||
raw = encoded(value);require(len(raw) <= 65536,'bounded_own_phase_record')
|
||||
file = os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=fd)
|
||||
try:
|
||||
view = memoryview(raw)
|
||||
while view:
|
||||
count = os.write(file,view);require(count > 0,'complete_create_only_record_write');view = view[count:]
|
||||
os.fsync(file)
|
||||
finally:os.close(file)
|
||||
os.fsync(fd)
|
||||
|
||||
|
||||
def binding():
|
||||
return dict(profile=PROFILE,original_case=CASE_ID,phase=PHASE,controller_sha256=sha(Path(__file__).read_bytes()),
|
||||
bootstrap_controller_sha256=BOOTSTRAP_SHA,installation_result_sha256=RESULTS['broker-install'],
|
||||
typed_abi_receipt_sha256=ABI_RECEIPT_SHA,unit_sha256=UNIT_SHA,binary_sha256=BINARY_SHA)
|
||||
|
||||
|
||||
def host_start(bootstrap,pin,guard,preflight=False):
|
||||
case = pin.directory(CASE);phase = -1;proof = process = None
|
||||
try:
|
||||
pin.absence(case,PHASE)
|
||||
proof = InstalledProof(bootstrap,pin,guard)
|
||||
require(not os.path.lexists(SOCKET),'broker_socket_initially_absent_no_adopt')
|
||||
before = proof.fresh()
|
||||
# Read-only property observation may load the installed unit; no reload/start.
|
||||
state = typed_snapshot(proof)
|
||||
effective(state,False)
|
||||
if preflight:
|
||||
print(encoded(dict(binding(),read_only=True,before=before,effective_unit=state,broker_started=False)).decode(),end='');return
|
||||
os.mkdir(PHASE,0o700,dir_fd=case);os.fsync(case)
|
||||
phase = os.open(PHASE,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=case)
|
||||
save(pin,phase,'intent.json',dict(binding(),once=True,no_retry=True,daemon_reload_once=True,start_once=True))
|
||||
save(pin,phase,'before.json',dict(binding(),witness=before,effective_unit=state))
|
||||
proof.fresh()
|
||||
save(pin,phase,'reload-intent.json',dict(binding(),argv=['/usr/bin/systemctl','daemon-reload'],once=True))
|
||||
code = proof.context.original.operator.long_command(['/usr/bin/systemctl','daemon-reload'],CASE/PHASE/'reload.log',10)
|
||||
save(pin,phase,'reload-exit.json',dict(binding(),exit_code=code));require(code == 0,'one_reload_failed_read_original_only')
|
||||
proof.fresh();state = effective(typed_snapshot(proof),False)
|
||||
require(not os.path.lexists(SOCKET),'no_socket_before_single_start')
|
||||
save(pin,phase,'effective-before-start.json',dict(binding(),effective_unit=state))
|
||||
save(pin,phase,'start-intent.json',dict(binding(),argv=['/usr/bin/systemctl','start','--',UNIT_NAME],once=True))
|
||||
code = proof.context.original.operator.long_command(['/usr/bin/systemctl','start','--',UNIT_NAME],CASE/PHASE/'start.log',15)
|
||||
save(pin,phase,'start-exit.json',dict(binding(),exit_code=code));require(code == 0,'one_start_failed_no_retry_or_cleanup')
|
||||
state = effective(typed_snapshot(proof),True);process = ProcessProof(proof,state)
|
||||
deadline = time.monotonic()+5
|
||||
while not os.path.lexists(SOCKET):
|
||||
require(time.monotonic() < deadline,'broker_socket_not_ready_read_original_only')
|
||||
process.verify(effective(typed_snapshot(proof),True));time.sleep(0.05)
|
||||
socket = socket_proof(proof,process)
|
||||
after = proof.fresh();final_state = effective(typed_snapshot(proof),True);actual_process = process.verify(final_state)
|
||||
require(before == after and socket_proof(proof,process) == socket,'runtime_generation_pin_configuration_socket_preserved')
|
||||
save(pin,phase,'after.json',dict(binding(),witness=after,effective_unit=final_state,process=actual_process,socket=socket))
|
||||
result = dict(binding(),daemon_reload_executed=True,start_executed_once=True,effective_unit_qualified=True,
|
||||
process=actual_process,socket=socket,source_runtime_generation_pin_preserved=True,
|
||||
signer_seed_read_by_controller=False,service_enabled=False,restart_executed=False,
|
||||
unix_request_sent=False,signed_attestation=False,http_deployed=False,rmm_jobs_created=False,
|
||||
corehistory_witness='external_root_before_after_receipts_required')
|
||||
save(pin,phase,'result.json',result);print(encoded(result).decode(),end='')
|
||||
except Exception as error:
|
||||
if phase >= 0:
|
||||
tag = str(error) if isinstance(error,Denied) and re.fullmatch('[a-z0-9_]{1,128}',str(error)) else 'unexpected_broker_start_exception'
|
||||
save(pin,phase,'failure.json',dict(binding(),fixed_tag=tag,failed=True,read_original_phase_only=True,
|
||||
no_retry_restart_stop_cleanup_or_adopt=True))
|
||||
raise
|
||||
finally:
|
||||
if process is not None:process.close()
|
||||
if proof is not None:proof.close()
|
||||
if phase >= 0:os.close(phase)
|
||||
os.close(case)
|
||||
|
||||
|
||||
def host_read(pin):
|
||||
records = {}
|
||||
for name in RECORDS:
|
||||
try:
|
||||
raw,metadata = pin.read_file(CASE/PHASE/name,65536)
|
||||
records[name] = dict(sha256=sha(raw),metadata=metadata,
|
||||
record=raw.decode('ascii') if name.endswith('.log') else pin.parsed(raw))
|
||||
except FileNotFoundError:records[name] = None
|
||||
print(encoded(dict(binding(),read_only=True,records=records,no_service_control=True)).decode(),end='')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=('host-preflight','host-start','host-read'))
|
||||
args = parser.parse_args()
|
||||
require(sys.flags.isolated == 1 and os.geteuid() == 0 and os.uname().sysname == 'Linux' and os.uname().machine == 'aarch64',
|
||||
'isolated_root_server_arm64_only')
|
||||
os.umask(0o077)
|
||||
bootstrap,pin,guard = load_bootstrap()
|
||||
if args.command == 'host-read':host_read(pin)
|
||||
else:host_start(bootstrap,pin,guard,args.command == 'host-preflight')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:main()
|
||||
except Exception:
|
||||
print(encoded(dict(profile=PROFILE,phase=PHASE,failed=True,read_original_phase_only=True)).decode(),end='')
|
||||
raise SystemExit(1)
|
||||
@@ -1,329 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Only the unentered fixed gateway backend effects of original fb87; no installed-effect replay."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
OLD_SHA = 'e14aeabfd7d3a8ab298985706dc26014e0ad540a1c3ef40cf57e1a65b77b7f3b'
|
||||
OLD_SOURCE = Path('/var/lib/rmm-time-source-operators') / OLD_SHA / 'gateway_deploy.py'
|
||||
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
|
||||
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
|
||||
PROFILE = 'rmm.server-time-gateway.backend-continuation.v1'
|
||||
PHASE = 'continue-backend-v1'
|
||||
DIAGNOSTIC_RECEIPT_SHA = 'a06256380d2febeddb506ffe17a614325b25c25464f45b4d022c82f644a0fc0f'
|
||||
RECORDS = ('intent.json','before.json','tag-intent.json','tag-exit.json','tag.log',
|
||||
'migrate-intent.json','migrate-exit.json','migrate.log','recreate-intent.json','recreate-exit.json',
|
||||
'recreate.log','after.json','result.json','failure.json')
|
||||
|
||||
class GuardDenied(RuntimeError):pass
|
||||
|
||||
def require(ok,reason):
|
||||
if not ok:raise GuardDenied(reason)
|
||||
|
||||
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
ORIGINAL_RECORDS = {'before.json': {'metadata': {'ctime_ns': 1794745703017552725,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417059,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703017552725,
|
||||
'nlink': 1,
|
||||
'size': 14614,
|
||||
'uid': 0},
|
||||
'sha256': '7d3b172db67321a49f103e2893a445259eda6e14fdb98ff3aa91c50eb41793a1'},
|
||||
'failure.json': {'metadata': {'ctime_ns': 1794745703413559883,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417066,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703413559883,
|
||||
'nlink': 1,
|
||||
'size': 229,
|
||||
'uid': 0},
|
||||
'sha256': '5d0fe5d630394ea4d7d6554526c585cac473ae181baf1895d869573940ba4fd5'},
|
||||
'intent.json': {'metadata': {'ctime_ns': 1794745703014552671,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417058,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703014552671,
|
||||
'nlink': 1,
|
||||
'size': 1621,
|
||||
'uid': 0},
|
||||
'sha256': '579a74c0f997b9c0b8fe2899929a42f3a009fd86ef6f62b11bfb2733bf9a7496'},
|
||||
'overlay-installed.json': {'metadata': {'ctime_ns': 1794745703320558202,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417063,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703320558202,
|
||||
'nlink': 1,
|
||||
'size': 1684,
|
||||
'uid': 0},
|
||||
'sha256': 'fa5b871d5bc259d9a2fdeedeb3a259ee56fe8f064f9588cda4eae8ec28133551'},
|
||||
'overlay-intent.json': {'metadata': {'ctime_ns': 1794745703313558076,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417062,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703313558076,
|
||||
'nlink': 1,
|
||||
'size': 1602,
|
||||
'uid': 0},
|
||||
'sha256': 'baad163ee43a3570ddec5cbc73ddc2ac7a1273c8f3fbb2f0c99752348e605cbc'},
|
||||
'reservation.json': {'metadata': {'ctime_ns': 1794745703310558021,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417061,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703310558021,
|
||||
'nlink': 1,
|
||||
'size': 1592,
|
||||
'uid': 0},
|
||||
'sha256': '5b1cd41a9ea91e1833c572f57c07bd32082e8f7170843d688c93fe269d3d9300'},
|
||||
'upgrade-tool-installed.json': {'metadata': {'ctime_ns': 1794745703332558419,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417065,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703332558419,
|
||||
'nlink': 1,
|
||||
'size': 1686,
|
||||
'uid': 0},
|
||||
'sha256': '5e976330fc1fa838432a3ed404bd0d999087becc5933a91e33df0339f590a47d'},
|
||||
'upgrade-tool-intent.json': {'metadata': {'ctime_ns': 1794745703325558293,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 417064,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794745703325558293,
|
||||
'nlink': 1,
|
||||
'size': 1593,
|
||||
'uid': 0},
|
||||
'sha256': '1a9a689b6c3241ca7ce7c6c156f073937a854b6b5d37d6f9a3cfc199a9c4645c'}}
|
||||
ORIGINAL_MISSING = ('after.json', 'migrate-exit.json', 'migrate-intent.json', 'migrate.log', 'old-upgrade-tool.bin', 'recreate-exit.json', 'recreate-intent.json', 'recreate.log', 'result.json', 'tag-exit.json', 'tag-intent.json', 'tag.log')
|
||||
|
||||
def load_pin_controller():
|
||||
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
for part in PIN_CONTROLLER.parent.parts[1:]:
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry')
|
||||
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = next_fd
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_parent')
|
||||
file_fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
with os.fdopen(file_fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
|
||||
before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and
|
||||
before.st_size <= 128 * 1024, 'reviewed_root_controller_file')
|
||||
raw = stream.read(128 * 1024 + 1)
|
||||
stable = lambda s: tuple(getattr(s, 'st_' + k) for k in
|
||||
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns'))
|
||||
require(stable(before) == stable(os.fstat(stream.fileno())) ==
|
||||
stable(os.stat(PIN_CONTROLLER.name, dir_fd=fd, follow_symlinks=False)) and
|
||||
len(raw) == before.st_size and sha(raw) == PIN_CONTROLLER_SHA, 'exact_pin_controller_bytes')
|
||||
finally:
|
||||
os.close(fd)
|
||||
pin = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_pin_guard', loader=None))
|
||||
pin.__file__ = str(PIN_CONTROLLER)
|
||||
exec(compile(raw, str(PIN_CONTROLLER), 'exec'), pin.__dict__)
|
||||
held = pin.read_file(PIN_CONTROLLER, 128 * 1024)
|
||||
require(held[0] == raw, 'same_loaded_pin_controller')
|
||||
return pin, lambda: require(pin.read_file(PIN_CONTROLLER, 128 * 1024) == held, 'pin_controller_unchanged')
|
||||
|
||||
|
||||
def canonical_containers(value):
|
||||
require(type(value) is dict and set(value)=={'api','gateway','postgres'},'exact_three_role_container_observation')
|
||||
result={}
|
||||
for role,row in value.items():
|
||||
require(type(row) is list and len(row)==12 and type(row[4]) is list,'fixed_docker_metadata_shape')
|
||||
destinations=[]
|
||||
for mount in row[4]:
|
||||
require(type(mount) is dict and type(mount.get('Destination')) is str
|
||||
and mount['Destination'].startswith('/'),'known_absolute_mount_destination')
|
||||
destinations.append(mount['Destination'])
|
||||
require(len(destinations)==len(set(destinations)),'unique_docker_mount_destinations')
|
||||
result[role]=list(row)
|
||||
result[role][4]=sorted(row[4],key=lambda mount:mount['Destination'])
|
||||
return result
|
||||
|
||||
|
||||
def stable_chrony(binding):
|
||||
value=json.loads(json.dumps(binding))
|
||||
# Exactly the two incidental directory-entry timestamps excluded by the
|
||||
# original pin.observation_key. Every process/image/socket field remains.
|
||||
del value['directory_metadata']['mtime_ns']
|
||||
del value['directory_metadata']['ctime_ns']
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command',choices=('host-preflight','host-continue','host-read'))
|
||||
args=parser.parse_args()
|
||||
require(sys.flags.isolated==1 and os.geteuid()==os.getegid()==0 and os.uname().machine=='aarch64',
|
||||
'isolated_root_cloud_arm64_only')
|
||||
require(not any(name in os.environ for name in ('DOCKER_HOST','DOCKER_CONTEXT','COMPOSE_PROJECT_NAME','COMPOSE_FILE','COMPOSE_PROFILES')),
|
||||
'fixed_local_docker_compose_context')
|
||||
os.umask(0o077)
|
||||
pin,pin_guard=load_pin_controller()
|
||||
raw,old_meta=pin.read_file(OLD_SOURCE,131072);require(sha(raw)==OLD_SHA,'exact_original_gateway_controller')
|
||||
old=importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_retained_gateway_deploy',loader=None))
|
||||
old.__file__=str(OLD_SOURCE);exec(compile(raw,str(OLD_SOURCE),'exec'),old.__dict__)
|
||||
here=old.CASE/PHASE
|
||||
if args.command=='host-read':
|
||||
records={}
|
||||
for name in RECORDS:
|
||||
try:
|
||||
data,metadata=pin.read_file(here/name,8*1024*1024 if name.endswith('.log') else 1024*1024)
|
||||
records[name]=dict(sha256=sha(data),metadata=metadata,record=pin.parsed(data) if name.endswith('.json') else None)
|
||||
except FileNotFoundError:records[name]=None
|
||||
print(pin.encoded(dict(profile=PROFILE,case=old.CASE_ID,phase=PHASE,read_only=True,records=records)).decode(),end='');return
|
||||
operator,operator_guard=pin.load_operator()
|
||||
own=pin.read_file(Path(__file__),131072)
|
||||
require(Path(__file__).name=='gateway_continue.py' and Path(__file__).parent.name==sha(own[0]),'fixed_continuation_source')
|
||||
original={}
|
||||
for name,expected in ORIGINAL_RECORDS.items():
|
||||
retained=pin.read_file(old.CASE/name,1024*1024)
|
||||
require(sha(retained[0])==expected['sha256'] and retained[1]==expected['metadata'],'exact_retained_original_phase_record')
|
||||
original[name]=retained
|
||||
original_fd=pin.directory(old.CASE);phase=-1;broker=None
|
||||
try:
|
||||
for name in ORIGINAL_MISSING:pin.absence(original_fd,name)
|
||||
pin.absence(original_fd,PHASE)
|
||||
failure=pin.parsed(original['failure.json'][0])
|
||||
require(failure['fixed_tag']=='last_original_runtime_and_migrations_cas'
|
||||
and failure['read_original_case_only'] is True,'proven_original_failure_before_backend_effects')
|
||||
before_record=pin.parsed(original['before.json'][0]);baseline=before_record['witness']
|
||||
require(before_record['controller_sha256']==OLD_SHA and before_record['case']==old.CASE_ID
|
||||
and before_record['image_id']==old.IMAGE and before_record['stage']==old.STAGE_ID,'same_original_fixed_gateway_plan')
|
||||
reservation=pin.read_file(old.STAGE/'time-gateway-deploy-intent.json',65536)
|
||||
require(reservation[0]==original['reservation.json'][0],'same_original_stage_reservation_no_generic_retry')
|
||||
installed_overlay=pin.read_file(old.ROOT/'deploy/server.time-broker.compose.yaml',4096,0o644)
|
||||
installed_tool=pin.read_file(old.ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)
|
||||
require(sha(installed_overlay[0])==old.OVERLAY_SHA and installed_overlay[1]==pin.parsed(original['overlay-installed.json'][0])['metadata']
|
||||
and sha(installed_tool[0])==old.UPGRADE_SHA and installed_tool[1]==pin.parsed(original['upgrade-tool-installed.json'][0])['metadata'],
|
||||
'only_verify_original_installed_effects_exact_bytes_and_inodes')
|
||||
source=pin.read_file(old.STAGE/'source.json',1024*1024);built=pin.read_file(old.STAGE/'build-result.json',65536)
|
||||
compose=pin.read_file(old.ROOT/'deploy/server.compose.yaml',8192,0o644)
|
||||
require(sha(source[0])==old.SOURCE_RECORD_SHA and sha(built[0])==old.BUILD_RESULT_SHA
|
||||
and sha(compose[0])==old.COMPOSE_SHA,'unchanged_original_qualified_source_build_compose')
|
||||
source_value=pin.parsed(source[0])
|
||||
require(all(sha(pin.read_file(old.ROOT/name,2*1024*1024,0o644)[0])==digest for name,digest in source_value['files'].items())
|
||||
and len(source_value['files'])==209,'same_original_published_source_files')
|
||||
signature=pin.read_file(old.BROKER_START.parent/'broker-signature-acceptance-v1/result.json',65536)
|
||||
require(sha(signature[0])==old.BROKER_SIGNATURE_RESULT_SHA,'same_original_actual_positive_signature_proof')
|
||||
public=pin.read_file(Path('/etc/rmm-time-source/time-public-key.json'),8192)
|
||||
require(sha(public[0])==old.TIME_PUBLIC_PIN_SHA,'same_actual_public_time_pin')
|
||||
broker=old.BrokerRuntime(pin,operator)
|
||||
cmd=['docker','compose','--env-file',str(old.ROOT/'devstate/.env'),'-f',str(old.ROOT/'deploy/server.compose.yaml'),
|
||||
'-f',str(old.ROOT/'deploy/server.time-broker.compose.yaml')]
|
||||
expected=canonical_containers(baseline['containers'])
|
||||
def common():
|
||||
pin_guard();operator_guard();broker.verify()
|
||||
require(pin.read_file(OLD_SOURCE,131072)==(raw,old_meta) and pin.read_file(Path(__file__),131072)==own,'retained_reviewed_controller_sources')
|
||||
for name,retained in original.items():require(pin.read_file(old.CASE/name,1024*1024)==retained,'original_failed_phase_records_unchanged')
|
||||
for name in ORIGINAL_MISSING:pin.absence(original_fd,name)
|
||||
require(pin.read_file(old.STAGE/'time-gateway-deploy-intent.json',65536)==reservation
|
||||
and pin.read_file(old.STAGE/'source.json',1024*1024)==source and pin.read_file(old.STAGE/'build-result.json',65536)==built
|
||||
and pin.read_file(old.ROOT/'deploy/server.compose.yaml',8192,0o644)==compose,'same_original_reservation_build_and_compose')
|
||||
require(pin.read_file(old.ROOT/'deploy/server.time-broker.compose.yaml',4096,0o644)==installed_overlay
|
||||
and pin.read_file(old.ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)==installed_tool,'installed_overlay_tool_never_repeated_or_replaced')
|
||||
require(old.file_tree(old.ROOT/'web/dist',True)==baseline['web']
|
||||
and {name:old.file_tree(Path(name)) for name in baseline['key_metadata']}==baseline['key_metadata'],
|
||||
'same_original_ui_pki_key_policy_metadata')
|
||||
require(pin.read_file(old.BROKER_START.parent/'broker-signature-acceptance-v1/result.json',65536)==signature
|
||||
and pin.read_file(Path('/etc/rmm-time-source/time-public-key.json'),8192)==public,'original_signature_and_time_key_unchanged')
|
||||
# ecb.preflight deliberately requires old Runtime6f. Reuse its
|
||||
# complete independent Chrony getter without changing that guard.
|
||||
current=operator.chrony_observation();previous=baseline['actual']
|
||||
boot=operator.regular(Path('/proc/sys/kernel/random/boot_id'),128).decode().strip()
|
||||
builder=json.loads(operator.run(['docker','image','inspect','--format',
|
||||
'[{{json .Id}},{{json .Architecture}},{{json .Os}}]',operator.BUILDER]))
|
||||
require(boot==previous['boot_id'] and dict(zip(('Id','Architecture','Os'),builder,strict=True))==previous['builder']
|
||||
and current['pin']==previous['chrony_observation']
|
||||
and current['fixed_images']['daemon']==previous['chrony_image_metadata'],
|
||||
'same_original_actual_boot_chrony_builder_image')
|
||||
require(stable_chrony(current)==stable_chrony(previous['chrony_binding']),
|
||||
'same_original_actual_chrony_process_cgroup_socket')
|
||||
return current
|
||||
common()
|
||||
require(canonical_containers(old.containers(operator))==expected
|
||||
and old.migrations(operator,cmd)==baseline['migrations']==list(range(1,15)),
|
||||
'only_nondeterministic_mount_order_changed_before_backend_continuation')
|
||||
require(operator.run(['docker','image','inspect','rust-discovery-server:local','--format','{{.Id}}']).decode().strip()==old.OLD_IMAGE,
|
||||
'retained_original_runtime_tag_cas')
|
||||
require(json.loads(operator.run(['docker','image','inspect',old.IMAGE,'--format','[{{json .Id}},{{json .Architecture}},{{json .Os}}]']))
|
||||
==[old.IMAGE,'arm64','linux'],'same_existing_qualified_native_image')
|
||||
binding=dict(profile=PROFILE,case=old.CASE_ID,phase=PHASE,controller_sha256=sha(own[0]),original_controller_sha256=OLD_SHA,
|
||||
original_before_sha256=ORIGINAL_RECORDS['before.json']['sha256'],original_failure_sha256=ORIGINAL_RECORDS['failure.json']['sha256'],
|
||||
mount_order_diagnostic_receipt_sha256=DIAGNOSTIC_RECEIPT_SHA,image_id=old.IMAGE,stage=old.STAGE_ID,
|
||||
installed_overlay_sha256=old.OVERLAY_SHA,installed_tool_sha256=old.UPGRADE_SHA)
|
||||
if args.command=='host-preflight':
|
||||
print(pin.encoded(dict(binding,read_only=True,backend_unentered=True,canonical_containers=expected,migrations=baseline['migrations'])).decode(),end='');return
|
||||
os.mkdir(PHASE,0o700,dir_fd=original_fd);os.fsync(original_fd);phase=pin.directory(here)
|
||||
save=lambda name,value:old.create(pin,phase,name,value)
|
||||
save('intent.json',dict(binding,once=True,no_repeat_installed_effects=True,no_retry=True))
|
||||
save('before.json',dict(binding,containers=expected,migrations=baseline['migrations'],broker=broker.verify()))
|
||||
def effect(name,argv,timeout):
|
||||
common();save(name+'-intent.json',dict(binding,argv=argv,once=True))
|
||||
code=operator.long_command(argv,here/(name+'.log'),timeout)
|
||||
save(name+'-exit.json',dict(binding,exit_code=code));require(code==0,'backend_effect_failed_original_continuation_read_only')
|
||||
require(canonical_containers(old.containers(operator))==expected and old.migrations(operator,cmd)==list(range(1,15)),
|
||||
'exact_original_runtime_and_schema_before_first_backend_effect')
|
||||
require(operator.run(['docker','image','inspect','rust-discovery-server:local','--format','{{.Id}}']).decode().strip()==old.OLD_IMAGE,'last_runtime_tag_cas')
|
||||
effect('tag',['docker','tag',old.IMAGE,'rust-discovery-server:local'],10)
|
||||
require(operator.run(['docker','image','inspect','rust-discovery-server:local','--format','{{.Id}}']).decode().strip()==old.IMAGE,'qualified_runtime_tag_after_once')
|
||||
effect('migrate',cmd+['run','--rm','--no-deps','migrate'],25)
|
||||
require(canonical_containers(old.containers(operator))==expected and old.migrations(operator,cmd)==list(range(1,16)),
|
||||
'only_migration_fifteen_before_recreate')
|
||||
effect('recreate',cmd+['up','-d','--no-deps','--force-recreate','--no-build','api','gateway'],25)
|
||||
after=canonical_containers(old.containers(operator))
|
||||
require(after['postgres']==expected['postgres'],'original_postgres_container_volume_generation_unchanged')
|
||||
for role in ('api','gateway'):
|
||||
previous,current=expected[role],after[role]
|
||||
require(current[0]!=previous[0] and current[1]==old.IMAGE and current[2:4]==previous[2:4]
|
||||
and current[5:9]==previous[5:9],'only_qualified_role_image_generation_changed')
|
||||
mounts=current[4]
|
||||
if role=='gateway':
|
||||
added=[mount for mount in mounts if mount.get('Destination')=='/run/rmm-time-source']
|
||||
require(len(added)==1 and added[0]['Source']=='/run/rmm-time-source' and added[0]['Type']=='bind'
|
||||
and added[0]['RW'] is False,'one_actual_readonly_gateway_time_mount')
|
||||
mounts=[mount for mount in mounts if mount.get('Destination')!='/run/rmm-time-source']
|
||||
require(mounts==previous[4],'all_original_mount_semantics_retained_no_api_time_mount')
|
||||
require(old.migrations(operator,cmd)==list(range(1,16)),'actual_additive_schema_through_fifteen')
|
||||
actual_chrony=common()
|
||||
save('after.json',dict(binding,containers=after,migrations=list(range(1,16)),broker=broker.verify(),chrony=actual_chrony))
|
||||
save('result.json',dict(binding,deployed=True,installed_effects_repeated=False,source_rebuilt=False,ui_rewritten=False,
|
||||
existing_pki_keys_policy_pg_container_preserved=True,broker_chrony_not_restarted=True,
|
||||
gateway_only_readonly_broker_mount=True,
|
||||
rmm_jobs_created=False,approvals_created=False,immutable_corehistory_witness='external_root_before_after_required'))
|
||||
print(pin.encoded(dict(binding,deployed=True)).decode(),end='')
|
||||
except Exception as error:
|
||||
if phase>=0:
|
||||
tag=str(error) if isinstance(error,GuardDenied) and 0<len(str(error))<=128 and all(c in 'abcdefghijklmnopqrstuvwxyz0123456789_' for c in str(error)) else 'unexpected_gateway_continuation_exception'
|
||||
old.create(pin,phase,'failure.json',dict(profile=PROFILE,failed=True,fixed_tag=tag,read_original_continuation_only=True))
|
||||
raise
|
||||
finally:
|
||||
if broker is not None:broker.close()
|
||||
for fd in (phase,original_fd):
|
||||
if fd>=0:os.close(fd)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:
|
||||
tag=str(error) if isinstance(error,GuardDenied) and 0<len(str(error))<=128 and all(c in 'abcdefghijklmnopqrstuvwxyz0123456789_' for c in str(error)) else 'unexpected_gateway_continuation_exception'
|
||||
print(json.dumps(dict(profile=PROFILE,failed=True,fixed_tag=tag,read_original_continuation_only=True)))
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -1,388 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fixed qualified422 gateway deployment. Source-only until actual broker proof is pinned.
|
||||
|
||||
One owned deployment case; no build, UI rewrite, reset, enrollment or approval.
|
||||
After a failed/lost reply only host-read of this same case is permitted.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import types
|
||||
|
||||
ROOT = Path('/opt/rust-discovery')
|
||||
CASE_ID = 'fb87aa88-2b67-4cff-9c90-4cd713380889'
|
||||
CASE = ROOT / 'devstate' / ('time-gateway-deploy-' + CASE_ID)
|
||||
STAGE_ID = 'd11a6fb7-cfdd-41b2-87c5-b48a2cfd2e27'
|
||||
STAGE = ROOT / 'devstate' / ('source-upgrade-' + STAGE_ID)
|
||||
PROFILE = 'rmm.server-time-gateway.fixed-deploy.v1'
|
||||
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
|
||||
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
|
||||
IMAGE = 'sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611'
|
||||
OLD_IMAGE = 'sha256:6f8383f7c762ac77ed1013c94eeafa2b76838c00aec358a375f5847645ea87ec'
|
||||
SOURCE_SHA = '4419f229599d827a63b69ded3c57b3a3fe4066a10d431368f68a2e415f77b3da'
|
||||
SOURCE_RECORD_SHA = '521bd003500e1dc51b5ec430900aa0c2e17f9ec050b7fc077f0cbbdf58ba7c0f'
|
||||
BUILD_RESULT_SHA = 'b8c0f61d054548753767c378e29019bd60f997980c2d407f8fd6e7b763047fdc'
|
||||
BUILD_LOG_SHA = 'f820345ef15268b47f2487222dcc2a80e9d8849ad9be005f7097fb7dd4232a8f'
|
||||
COMPOSE_SHA = 'd2044b0ee6d584f360990635bec149511d5a0623ec562976541900d751998818'
|
||||
UI_SHA = '95d6f9058cc713c6af36fbd22ccc60678f081765a853b53d19ac6f0d219804f8'
|
||||
POLICY_SHA = 'cf15cbb68b590475df6def28e7dcffb7d88e0ca2d2555a06174fb654eeff05f4'
|
||||
OVERLAY_SHA = 'dbd08faea8f58c032562d822f4191c719f9a6828b00d6c368fc2596155a9a314'
|
||||
UPGRADE_SHA = '2ed358fa20d74bbad20da728c1ef469e0b9613e5d53f41513402a01684c8fd62'
|
||||
CLOUD_READ_RECEIPT_SHA = '438958c318a47b95d717a73f701ebd5e7287b08d4dd066870f62287d91f54a1a'
|
||||
BROKER_START_CONTROLLER_SHA = 'e1458cb3feecd3d3302f2fccaff4850cfc8c403ee3314563f5f641e7c8bdfc39'
|
||||
BROKER_START_RESULT_SHA = '8fc6ed5193f9802b7686a93523730c7e805595415c8e887552ffcf4224968d4d'
|
||||
BROKER_START_READ_RECEIPT_SHA = '731527c0e30aaaddf386f414ffcdd11333000b9897b856cb994da1eccd255d54'
|
||||
BROKER_SIGNATURE_CONTROLLER_SHA = 'a8afe8a2167f91e743e8c976b58d9f5227fa64914ad492ffc489b0dc98392585'
|
||||
BROKER_SIGNATURE_RESULT_SHA = '38ed1a3079f20438fe07a57f1bfa5a37348bdec9fc7780d7822ca3d6967e5ea1'
|
||||
BROKER_SIGNATURE_READ_RECEIPT_SHA = '4b442a9022f1ee56f8e851e25ad323d630b220cf47aa8169b83b9c4412c50b8d'
|
||||
TIME_PUBLIC_PIN_SHA = 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'
|
||||
BROKER_START = Path('/var/lib/rmm-time-source-bootstrap/5b358997-3abc-43db-945f-f41855b4e3c0/broker-start-acceptance-v1')
|
||||
OLD_IDS = {'api':'307c24bbc3a1249d598f0361780b7f742023dd65772f96e943c1b6af5685b4e9',
|
||||
'gateway':'bbf4ce19c77c3f48eb90f3b9a1c3b9ef86eb1fd2f8cd3ad107a9ea6704d9cc6d',
|
||||
'postgres':'3ce274d1794aa189309b24147d63a67ae8f420663bd021628fbe8bb9ed9ec4dc'}
|
||||
WEB_FILES = ('assets/index-BALnnpV2.js','assets/index-Be1zm1OZ.css','assets/index-BmiTugvc.js',
|
||||
'assets/index-BvPcFQTr.js','assets/index-CTgvl2jr.js','assets/index-DJcsgK_5.js','index.html')
|
||||
RECORDS = ('intent.json','before.json','overlay-intent.json','overlay-installed.json',
|
||||
'upgrade-tool-intent.json','upgrade-tool-installed.json','old-upgrade-tool.bin','reservation.json',
|
||||
'tag-intent.json','tag-exit.json','tag.log','migrate-intent.json','migrate-exit.json','migrate.log',
|
||||
'recreate-intent.json','recreate-exit.json','recreate.log','after.json','result.json','failure.json')
|
||||
|
||||
class GuardDenied(RuntimeError):
|
||||
pass
|
||||
|
||||
def require(ok,tag):
|
||||
if not ok:raise GuardDenied(tag)
|
||||
|
||||
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
def load_pin_controller():
|
||||
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
for part in PIN_CONTROLLER.parent.parts[1:]:
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry')
|
||||
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = next_fd
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_parent')
|
||||
file_fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
with os.fdopen(file_fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
|
||||
before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and
|
||||
before.st_size <= 128 * 1024, 'reviewed_root_controller_file')
|
||||
raw = stream.read(128 * 1024 + 1)
|
||||
stable = lambda s: tuple(getattr(s, 'st_' + k) for k in
|
||||
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns'))
|
||||
require(stable(before) == stable(os.fstat(stream.fileno())) ==
|
||||
stable(os.stat(PIN_CONTROLLER.name, dir_fd=fd, follow_symlinks=False)) and
|
||||
len(raw) == before.st_size and sha(raw) == PIN_CONTROLLER_SHA, 'exact_pin_controller_bytes')
|
||||
finally:
|
||||
os.close(fd)
|
||||
pin = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_pin_guard', loader=None))
|
||||
pin.__file__ = str(PIN_CONTROLLER)
|
||||
exec(compile(raw, str(PIN_CONTROLLER), 'exec'), pin.__dict__)
|
||||
held = pin.read_file(PIN_CONTROLLER, 128 * 1024)
|
||||
require(held[0] == raw, 'same_loaded_pin_controller')
|
||||
return pin, lambda: require(pin.read_file(PIN_CONTROLLER, 128 * 1024) == held, 'pin_controller_unchanged')
|
||||
|
||||
|
||||
def loaded(pin,path,expected):
|
||||
raw,metadata = pin.read_file(path,131072)
|
||||
require(sha(raw) == expected,'exact_protected_deploy_dependency')
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_fixed_gateway_dependency',loader=None))
|
||||
module.__file__ = str(path)
|
||||
exec(compile(raw,str(path),'exec'),module.__dict__)
|
||||
return module,lambda:require(pin.read_file(path,131072) == (raw,metadata),'deploy_dependency_unchanged')
|
||||
|
||||
|
||||
def create(pin,parent,name,value):
|
||||
raw = value if type(value) is bytes else pin.encoded(value)
|
||||
require(len(raw) <= 1024*1024,'bounded_private_deploy_record')
|
||||
fd = os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=parent)
|
||||
try:
|
||||
view = memoryview(raw)
|
||||
while view:
|
||||
count = os.write(fd,view);require(count>0,'complete_deploy_record');view=view[count:]
|
||||
os.fsync(fd)
|
||||
finally:os.close(fd)
|
||||
os.fsync(parent)
|
||||
|
||||
|
||||
def containers(operator):
|
||||
result = {}
|
||||
template = '[{{json .Id}},{{json .Image}},{{json .Config.User}},{{json .HostConfig.PortBindings}},{{json .Mounts}},{{json .HostConfig.ReadonlyRootfs}},{{json .HostConfig.CapDrop}},{{json .HostConfig.SecurityOpt}},{{json .State.Running}},{{json .State.Pid}},{{json .State.StartedAt}},{{json .RestartCount}}]'
|
||||
for role in ('api','gateway','postgres'):
|
||||
result[role] = json.loads(operator.run(['docker','inspect','rust-discovery-server-'+role+'-1',
|
||||
'--format',template],limit=65536))
|
||||
for role,port in (('api','18443'),('gateway','18444')):
|
||||
row = result[role]
|
||||
require(len(row)==12 and row[2]=='10001:10001' and row[3]=={'18443/tcp':[{'HostIp':'127.0.0.1','HostPort':port}]}
|
||||
and row[5] is True and row[6]==['ALL'] and row[7]==['no-new-privileges:true']
|
||||
and row[8] is True and type(row[9]) is int and row[9]>1 and row[11]==0,'same_unprivileged_loopback_server_role')
|
||||
pg=result['postgres']
|
||||
require(pg[0]==OLD_IDS['postgres'] and pg[1]=='sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3'
|
||||
and pg[3] in ({},None) and pg[8] is True
|
||||
and any(mount.get('Type')=='volume' and mount.get('Name')=='rust-discovery-server_pgdata'
|
||||
and mount.get('Destination')=='/var/lib/postgresql/data' for mount in pg[4]),'same_existing_private_postgres_container_volume')
|
||||
return result
|
||||
|
||||
|
||||
def file_tree(path,public=False):
|
||||
result={}
|
||||
for item in [path,*sorted(path.rglob('*'))]:
|
||||
info=item.lstat()
|
||||
require(not item.is_symlink() and (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode))
|
||||
and info.st_uid in (0,10001) and not info.st_mode&0o022,'protected_retained_ui_pki_key_path')
|
||||
value={key:getattr(info,'st_'+key) for key in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns')}
|
||||
if stat.S_ISREG(info.st_mode):
|
||||
require(info.st_nlink==1,'single_link_retained_public_or_key_file')
|
||||
if public:
|
||||
require(info.st_size<=2*1024*1024,'bounded_public_web_asset')
|
||||
value['sha256']=sha(item.read_bytes())
|
||||
require(all(getattr(item.lstat(),'st_'+key)==value[key] for key in value if key!='sha256'),'stable_public_web_asset')
|
||||
result[str(item)]=value
|
||||
return result
|
||||
|
||||
|
||||
def migrations(operator,cmd):
|
||||
query = "BEGIN READ ONLY; SELECT COALESCE(json_agg(version ORDER BY version),'[]'::json) FROM _sqlx_migrations WHERE success; COMMIT;"
|
||||
raw = operator.run(cmd+['exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1',
|
||||
'-U','postgres','-d','rmm','-c',query],timeout=10,limit=8192)
|
||||
value = json.loads(raw)
|
||||
require(type(value) is list and all(type(item) is int for item in value),'actual_successful_migration_versions')
|
||||
return value
|
||||
|
||||
|
||||
class BrokerRuntime:
|
||||
def __init__(self,pin,operator):
|
||||
self.process=None
|
||||
module_path=Path('/var/lib/rmm-time-source-operators')/BROKER_START_CONTROLLER_SHA/'broker_start_acceptance.py'
|
||||
self.module,self.guard=loaded(pin,module_path,BROKER_START_CONTROLLER_SHA)
|
||||
self.record=pin.read_file(BROKER_START/'result.json',65536)
|
||||
require(sha(self.record[0])==BROKER_START_RESULT_SHA,'actual_original_successful_broker_start')
|
||||
self.result=pin.parsed(self.record[0])
|
||||
require(self.result['controller_sha256']==BROKER_START_CONTROLLER_SHA
|
||||
and self.result['start_executed_once'] is True and self.result['effective_unit_qualified'] is True
|
||||
and self.result['unix_request_sent'] is False and self.result['signed_attestation'] is False,
|
||||
'actual_started_broker_not_time_signature_authority')
|
||||
raw,metadata=pin.read_file(self.module.BINARY,2*1024*1024,0o500)
|
||||
require(sha(raw)==self.module.BINARY_SHA and metadata==self.result['process']['image_metadata'],
|
||||
'same_actual_started_broker_binary_inode')
|
||||
self.proof=types.SimpleNamespace(pin=pin,binary=types.SimpleNamespace(metadata=metadata),
|
||||
context=types.SimpleNamespace(original=types.SimpleNamespace(operator=operator)))
|
||||
state=self.module.effective(self.module.typed_snapshot(self.proof),True)
|
||||
self.process=self.module.ProcessProof(self.proof,state)
|
||||
self.before=self.verify()
|
||||
|
||||
def verify(self):
|
||||
self.guard()
|
||||
require(self.proof.pin.read_file(BROKER_START/'result.json',65536)==self.record,'broker_start_record_unchanged')
|
||||
state=self.module.effective(self.module.typed_snapshot(self.proof),True)
|
||||
process=self.process.verify(state)
|
||||
socket=self.module.socket_proof(self.proof,self.process)
|
||||
require(process==self.result['process'] and socket==self.result['socket'],'same_actual_started_broker_process_and_listener')
|
||||
return dict(process=process,socket=socket,start_result_sha256=BROKER_START_RESULT_SHA)
|
||||
|
||||
def close(self):
|
||||
if self.process is not None:self.process.close()
|
||||
|
||||
|
||||
def host_read(pin):
|
||||
records={}
|
||||
for name in RECORDS:
|
||||
try:
|
||||
raw,metadata=pin.read_file(CASE/name,8*1024*1024 if name.endswith('.log') else 1024*1024)
|
||||
records[name]=dict(sha256=sha(raw),metadata=metadata,record=pin.parsed(raw) if name.endswith('.json') else None)
|
||||
except FileNotFoundError:records[name]=None
|
||||
print(pin.encoded(dict(profile=PROFILE,case=CASE_ID,read_only=True,records=records,no_effects=True)).decode(),end='')
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command',choices=('host-preflight','host-deploy','host-read'))
|
||||
args=parser.parse_args()
|
||||
require(sys.flags.isolated==1 and os.geteuid()==0 and os.getegid()==0 and os.uname().machine=='aarch64','isolated_root_cloud_arm64_only')
|
||||
require(not any(name in os.environ for name in ('DOCKER_HOST','DOCKER_CONTEXT','COMPOSE_PROJECT_NAME','COMPOSE_FILE','COMPOSE_PROFILES')),
|
||||
'fixed_local_docker_compose_context')
|
||||
os.umask(0o077);pin,pin_guard=load_pin_controller()
|
||||
if args.command=='host-read':host_read(pin);return
|
||||
operator,operator_guard=pin.load_operator()
|
||||
require(type(BROKER_SIGNATURE_RESULT_SHA) is str and len(BROKER_SIGNATURE_RESULT_SHA)==64
|
||||
and type(BROKER_SIGNATURE_READ_RECEIPT_SHA) is str and len(BROKER_SIGNATURE_READ_RECEIPT_SHA)==64,
|
||||
'actual_signature_pass_and_read_must_be_pinned')
|
||||
signature_path=BROKER_START.parent/'broker-signature-acceptance-v1/result.json'
|
||||
signature_controller_path=Path('/var/lib/rmm-time-source-operators')/BROKER_SIGNATURE_CONTROLLER_SHA/'broker_signature_acceptance.py'
|
||||
signature_controller=pin.read_file(signature_controller_path,131072)
|
||||
require(sha(signature_controller[0])==BROKER_SIGNATURE_CONTROLLER_SHA,'actual_reviewed_signature_controller_source')
|
||||
signature_record=pin.read_file(signature_path,65536)
|
||||
require(sha(signature_record[0])==BROKER_SIGNATURE_RESULT_SHA,'actual_positive_broker_signature_result')
|
||||
signature_value=pin.parsed(signature_record[0])
|
||||
require(signature_value['profile']=='rmm.server-time-broker.unix-signature-acceptance.v1'
|
||||
and signature_value['controller_sha256']==BROKER_SIGNATURE_CONTROLLER_SHA
|
||||
and signature_value['start_result_sha256']==BROKER_START_RESULT_SHA
|
||||
and signature_value['public_pin_sha256']==TIME_PUBLIC_PIN_SHA
|
||||
and signature_value['two_actual_signatures_verified'] is True
|
||||
and signature_value['private_signer_read'] is False and signature_value['clock_authority'] is False,
|
||||
'actual_non_authoritative_signature_acceptance')
|
||||
signature_phase=pin.directory(signature_path.parent)
|
||||
try:pin.absence(signature_phase,'failure.json')
|
||||
finally:os.close(signature_phase)
|
||||
time_public=pin.read_file(Path('/etc/rmm-time-source/time-public-key.json'),8192)
|
||||
require(sha(time_public[0])==TIME_PUBLIC_PIN_SHA,'same_separate_public_time_key_c31')
|
||||
own=pin.read_file(Path(__file__),131072);own_dir=Path(__file__).parent
|
||||
require(own_dir.name==sha(own[0]) and Path(__file__).name=='gateway_deploy.py','fixed_protected_gateway_deploy_controller')
|
||||
overlay=pin.read_file(own_dir/'server.time-broker.compose.yaml',4096)
|
||||
upgrade=pin.read_file(own_dir/'cloud_server_upgrade.py',131072)
|
||||
require(len(overlay[0])==199 and sha(overlay[0])==OVERLAY_SHA and sha(upgrade[0])==UPGRADE_SHA,'fixed_public_overlay_upgrade_tool_inputs')
|
||||
source=pin.read_file(STAGE/'source.json',1024*1024);built=pin.read_file(STAGE/'build-result.json',65536)
|
||||
require(sha(source[0])==SOURCE_RECORD_SHA and sha(built[0])==BUILD_RESULT_SHA,'exact_qualified_original_arm_build_records')
|
||||
source_value,built_value=pin.parsed(source[0]),pin.parsed(built[0])
|
||||
require(source_value['source_sha256']==SOURCE_SHA and source_value['old_image']==OLD_IMAGE
|
||||
and built_value=={'exit_code':0,'image_id':IMAGE},'qualified_422_source_build_not_moving_main')
|
||||
require(sha(pin.read_file(STAGE/'build.log',16*1024*1024)[0])==BUILD_LOG_SHA,'actual_qualified_build_log')
|
||||
require(all(sha(pin.read_file(ROOT/name,2*1024*1024,0o644)[0])==digest for name,digest in source_value['files'].items()),
|
||||
'unchanged_published_209_source_files')
|
||||
require(len(source_value['files'])==209,'exact_qualified_source_file_set')
|
||||
require(json.loads(operator.run(['docker','image','inspect',IMAGE,'--format','[{{json .Id}},{{json .Architecture}},{{json .Os}}]']))
|
||||
==[IMAGE,'arm64','linux'],'qualified_existing_native_image_no_build')
|
||||
compose=pin.read_file(ROOT/'deploy/server.compose.yaml',8192,0o644)
|
||||
require(sha(compose[0])==COMPOSE_SHA,'same_actual_server_compose')
|
||||
cmd=['docker','compose','--env-file',str(ROOT/'devstate/.env'),'-f',str(ROOT/'deploy/server.compose.yaml')]
|
||||
broker=BrokerRuntime(pin,operator);phase=deploy_fd=stage_fd=-1
|
||||
try:
|
||||
before_containers=containers(operator)
|
||||
require(all(before_containers[role][0]==OLD_IDS[role] and before_containers[role][1]==OLD_IMAGE for role in ('api','gateway')),
|
||||
'exact_original_6f_role_containers')
|
||||
require(operator.run(['docker','image','inspect','rust-discovery-server:local','--format','{{.Id}}']).decode().strip()==OLD_IMAGE,
|
||||
'old_runtime_tag_cas')
|
||||
before_actual=operator.preflight()
|
||||
web=file_tree(ROOT/'web/dist',True)
|
||||
require(sorted(str(Path(name).relative_to(ROOT/'web/dist')) for name in web if stat.S_ISREG(web[name]['mode']))==list(WEB_FILES)
|
||||
and web[str(ROOT/'web/dist/index.html')]['sha256']==UI_SHA,'all_original_web_assets_and_index_cas')
|
||||
keys={str(path):file_tree(path) for path in (ROOT/'devstate/pki',ROOT/'devstate/api-pki',ROOT/'devstate/jobs',Path('/etc/rmm-time-source'),ROOT/'devstate/.env',ROOT/'devstate/root-policy/policy.json')}
|
||||
policy_info=(ROOT/'devstate/root-policy/policy.json').lstat()
|
||||
require(policy_info.st_uid==policy_info.st_gid==10001 and stat.S_IMODE(policy_info.st_mode)==0o600
|
||||
and sha((ROOT/'devstate/root-policy/policy.json').read_bytes())==POLICY_SHA,'same_closed_root_policy_bytes')
|
||||
before_migrations=migrations(operator,cmd)
|
||||
require(before_migrations==list(range(1,15)),'actual_existing_migrations_one_through_fourteen')
|
||||
deploy_fd=pin.directory(ROOT/'deploy');stage_fd=pin.directory(STAGE)
|
||||
pin.absence(deploy_fd,'server.time-broker.compose.yaml')
|
||||
pin.absence(stage_fd,'time-gateway-deploy-intent.json');pin.absence(stage_fd,'deploy-result.json')
|
||||
try:old_upgrade=pin.read_file(ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)
|
||||
except FileNotFoundError:old_upgrade=None
|
||||
binding=dict(profile=PROFILE,case=CASE_ID,stage=STAGE_ID,controller_sha256=sha(own[0]),image_id=IMAGE,
|
||||
old_image=OLD_IMAGE,source_sha256=SOURCE_SHA,source_record_sha256=SOURCE_RECORD_SHA,build_result_sha256=BUILD_RESULT_SHA,
|
||||
overlay_sha256=OVERLAY_SHA,upgrade_tool_sha256=UPGRADE_SHA,broker_start_result_sha256=BROKER_START_RESULT_SHA,
|
||||
broker_start_read_receipt_sha256=BROKER_START_READ_RECEIPT_SHA,cloud_read_receipt_sha256=CLOUD_READ_RECEIPT_SHA,
|
||||
broker_signature_result_sha256=BROKER_SIGNATURE_RESULT_SHA,
|
||||
broker_signature_controller_sha256=BROKER_SIGNATURE_CONTROLLER_SHA,
|
||||
broker_signature_read_receipt_sha256=BROKER_SIGNATURE_READ_RECEIPT_SHA,time_public_pin_sha256=TIME_PUBLIC_PIN_SHA)
|
||||
baseline=dict(containers=before_containers,actual=before_actual,web=web,key_metadata=keys,migrations=before_migrations,broker=broker.before)
|
||||
if args.command=='host-preflight':
|
||||
print(pin.encoded(dict(binding,read_only=True,before=baseline,overlay_initially_absent=True,no_build=True,no_ui_write=True)).decode(),end='');return
|
||||
parent=pin.directory(CASE.parent)
|
||||
try:pin.absence(parent,CASE.name);os.mkdir(CASE.name,0o700,dir_fd=parent);os.fsync(parent)
|
||||
finally:os.close(parent)
|
||||
phase=pin.directory(CASE)
|
||||
save=lambda name,value:create(pin,phase,name,value)
|
||||
save('intent.json',dict(binding,once=True,no_retry=True,no_build=True,no_ui_write=True,migration_version=15))
|
||||
save('before.json',dict(binding,witness=baseline))
|
||||
def common():
|
||||
pin_guard();operator_guard();broker.verify()
|
||||
require(pin.read_file(signature_path,65536)==signature_record
|
||||
and pin.read_file(signature_controller_path,131072)==signature_controller
|
||||
and pin.read_file(Path('/etc/rmm-time-source/time-public-key.json'),8192)==time_public,
|
||||
'signature_pass_and_public_time_key_unchanged')
|
||||
require(pin.read_file(Path(__file__),131072)==own and pin.read_file(own_dir/'server.time-broker.compose.yaml',4096)==overlay
|
||||
and pin.read_file(own_dir/'cloud_server_upgrade.py',131072)==upgrade,'retained_exact_controller_public_inputs')
|
||||
require(pin.read_file(STAGE/'source.json',1024*1024)==source and pin.read_file(STAGE/'build-result.json',65536)==built
|
||||
and pin.read_file(ROOT/'deploy/server.compose.yaml',8192,0o644)==compose,'retained_build_records_and_base_compose')
|
||||
require(file_tree(ROOT/'web/dist',True)==web
|
||||
and {str(path):file_tree(path) for path in (ROOT/'devstate/pki',ROOT/'devstate/api-pki',ROOT/'devstate/jobs',Path('/etc/rmm-time-source'),ROOT/'devstate/.env',ROOT/'devstate/root-policy/policy.json')}==keys,
|
||||
'original_web_pki_keys_and_public_time_pins_preserved')
|
||||
common()
|
||||
reservation=dict(binding,original_case_only=True,no_generic_deploy_retry=True)
|
||||
create(pin,stage_fd,'time-gateway-deploy-intent.json',reservation);save('reservation.json',reservation)
|
||||
save('overlay-intent.json',dict(binding,path='deploy/server.time-broker.compose.yaml',create_only=True))
|
||||
temp='.time-broker-'+CASE_ID+'.new';fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o644,dir_fd=deploy_fd)
|
||||
with os.fdopen(fd,'wb') as out:out.write(overlay[0]);out.flush();os.fchmod(out.fileno(),0o644);os.fsync(out.fileno())
|
||||
pin.absence(deploy_fd,'server.time-broker.compose.yaml')
|
||||
os.link(temp,'server.time-broker.compose.yaml',src_dir_fd=deploy_fd,dst_dir_fd=deploy_fd,follow_symlinks=False)
|
||||
os.unlink(temp,dir_fd=deploy_fd);os.fsync(deploy_fd)
|
||||
installed_overlay=pin.read_file(ROOT/'deploy/server.time-broker.compose.yaml',4096,0o644)
|
||||
require(installed_overlay[0]==overlay[0],'exact_created_gateway_only_overlay');save('overlay-installed.json',dict(binding,metadata=installed_overlay[1]))
|
||||
if old_upgrade is not None:save('old-upgrade-tool.bin',old_upgrade[0])
|
||||
save('upgrade-tool-intent.json',dict(binding,path='deploy/cloud_server_upgrade.py',old_sha256=sha(old_upgrade[0]) if old_upgrade else None))
|
||||
temp='.cloud-upgrade-'+CASE_ID+'.new';fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o644,dir_fd=deploy_fd)
|
||||
with os.fdopen(fd,'wb') as out:out.write(upgrade[0]);out.flush();os.fchmod(out.fileno(),0o644);os.fsync(out.fileno())
|
||||
if old_upgrade is None:pin.absence(deploy_fd,'cloud_server_upgrade.py')
|
||||
else:require(pin.read_file(ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)==old_upgrade,'old_upgrade_tool_cas')
|
||||
os.replace(temp,'cloud_server_upgrade.py',src_dir_fd=deploy_fd,dst_dir_fd=deploy_fd);os.fsync(deploy_fd)
|
||||
installed_upgrade=pin.read_file(ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)
|
||||
require(installed_upgrade[0]==upgrade[0],'exact_persistent_optional_overlay_deploy_tool')
|
||||
save('upgrade-tool-installed.json',dict(binding,metadata=installed_upgrade[1]))
|
||||
final_cmd=cmd+['-f',str(ROOT/'deploy/server.time-broker.compose.yaml')]
|
||||
def effect(name,argv,timeout):
|
||||
common()
|
||||
require(pin.read_file(ROOT/'deploy/server.time-broker.compose.yaml',4096,0o644)==installed_overlay
|
||||
and pin.read_file(ROOT/'deploy/cloud_server_upgrade.py',131072,0o644)==installed_upgrade,'same_installed_overlay_and_upgrade_tool')
|
||||
save(name+'-intent.json',dict(binding,argv=argv,once=True))
|
||||
code=operator.long_command(argv,CASE/(name+'.log'),timeout)
|
||||
save(name+'-exit.json',dict(binding,exit_code=code));require(code==0,'fixed_deploy_command_failed_original_read_only')
|
||||
require(containers(operator)==before_containers and migrations(operator,cmd)==before_migrations,'last_original_runtime_and_migrations_cas')
|
||||
effect('tag',['docker','tag',IMAGE,'rust-discovery-server:local'],10)
|
||||
require(operator.run(['docker','image','inspect','rust-discovery-server:local','--format','{{.Id}}']).decode().strip()==IMAGE,'new_fixed_runtime_tag')
|
||||
effect('migrate',final_cmd+['run','--rm','--no-deps','migrate'],25)
|
||||
effect('recreate',final_cmd+['up','-d','--no-deps','--force-recreate','--no-build','api','gateway'],25)
|
||||
after_containers=containers(operator);after_actual=operator.preflight();after_migrations=migrations(operator,final_cmd)
|
||||
require(after_containers['postgres']==before_containers['postgres'],'same_postgres_container_identity_mounts_runtime')
|
||||
for role in ('api','gateway'):
|
||||
old,new=before_containers[role],after_containers[role]
|
||||
require(new[0]!=old[0] and new[1]==IMAGE and new[2:4]==old[2:4] and new[5:9]==old[5:9],
|
||||
'only_qualified_server_role_image_and_process_generation_changed')
|
||||
expected=list(old[4])
|
||||
if role=='gateway':
|
||||
require(any(mount.get('Source')=='/run/rmm-time-source' and mount.get('Destination')=='/run/rmm-time-source'
|
||||
and mount.get('Type')=='bind' and mount.get('RW') is False for mount in new[4]),'actual_gateway_only_readonly_broker_mount')
|
||||
filtered=[mount for mount in new[4] if mount.get('Destination')!='/run/rmm-time-source']
|
||||
else:filtered=new[4]
|
||||
require(sorted(filtered,key=lambda item:item['Destination'])==sorted(expected,key=lambda item:item['Destination']),
|
||||
'all_existing_role_mounts_preserved_no_api_time_mount')
|
||||
for key in ('builder','boot_id','chrony_observation','chrony_image_metadata'):
|
||||
require(before_actual[key]==after_actual[key],'same_boot_chrony_generation_image_builder')
|
||||
old_chrony=pin.observation_key(before_actual)['chrony_binding'];new_chrony=pin.observation_key(after_actual)['chrony_binding']
|
||||
require(old_chrony==new_chrony,'same_actual_chrony_process_cgroup_socket_binding')
|
||||
require(after_migrations==list(range(1,16)),'actual_successful_additive_migrations_through_fifteen')
|
||||
common()
|
||||
save('after.json',dict(binding,witness=dict(containers=after_containers,actual=after_actual,migrations=after_migrations,broker=broker.verify())))
|
||||
save('result.json',dict(binding,deployed=True,migrations=list(range(1,16)),web_assets_bytes_and_inodes_preserved=True,
|
||||
pki_keys_pg_container_volume_preserved=True,
|
||||
immutable_corehistory_witness='external_root_before_after_receipts_required',gateway_only_readonly_broker_mount=True,
|
||||
approvals_created=False,rmm_jobs_created=False,source_rebuilt=False,time_signed=False))
|
||||
print(pin.encoded(dict(binding,deployed=True,no_ui_write=True,no_build=True)).decode(),end='')
|
||||
except Exception as error:
|
||||
if phase>=0:
|
||||
tag=str(error) if isinstance(error,GuardDenied) and 0<len(str(error))<=128 and all(c in 'abcdefghijklmnopqrstuvwxyz0123456789_' for c in str(error)) else 'unexpected_fixed_gateway_deploy_exception'
|
||||
create(pin,phase,'failure.json',dict(profile=PROFILE,case=CASE_ID,fixed_tag=tag,failed=True,read_original_case_only=True,no_automatic_rollback=True))
|
||||
raise
|
||||
finally:
|
||||
broker.close()
|
||||
for fd in (phase,deploy_fd,stage_fd):
|
||||
if fd>=0:os.close(fd)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:
|
||||
tag=str(error) if isinstance(error,GuardDenied) and 0<len(str(error))<=128 and all(c in 'abcdefghijklmnopqrstuvwxyz0123456789_' for c in str(error)) else 'unexpected_fixed_gateway_deploy_exception'
|
||||
print(json.dumps(dict(profile=PROFILE,case=CASE_ID,failed=True,fixed_tag=tag,read_original_case_only=True)))
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -1,638 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One native source sample for the fixed proven Chrony generation; no restart/key/clock authority.
|
||||
|
||||
SharedGenerationProof is read-only. Historical build records and current c9
|
||||
process identity are checked separately; pin.Original is never instantiated.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
CASE_ID = 'c9a94f94-eecd-4c66-933d-c45c1a79c7a8'
|
||||
QUALITY_PHASE = 'probe-native-source-v1'
|
||||
BASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE_ID
|
||||
OLD = Path('/var/lib/rmm-time-source-bootstrap/5b358997-3abc-43db-945f-f41855b4e3c0')
|
||||
PROFILE = 'rmm.server-time-source.native-generation-acceptance.v1'
|
||||
UNIT = 'rmm-time-source-probe-native-' + CASE_ID + '.service'
|
||||
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
|
||||
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
|
||||
GENERATION_CONTROLLER_SHA = 'd5d56b38e6e36609b2eca294133758eed83a4e559c1ff05a8a62e085fdf8b9f5'
|
||||
GENERATION_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / GENERATION_CONTROLLER_SHA / 'chrony_generation_bootstrap.py'
|
||||
GENERATION_RESULT_SHA = 'd648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4'
|
||||
GENERATION_RECEIPT_SHA = '1173ef78f9ca704afafbf4dbe92e8c654ec47d53f4e9f05fd99be2685991ce59'
|
||||
GENERATION_READ_RECEIPT_SHA = '58970ef8e89af86b68fdbbf2cb5119210bcb37cec603feb23b4f6030b0b36623'
|
||||
PUBLIC_PIN_SHA = '395f170aabf9fd01c24cd7d7939a313befdd147e98343ccd383bca861cbf2c4e'
|
||||
SOURCE_SHA = '0da5ed0d52d3e621ef6a23cbc065f9d7c93e5683547e0a02ae3c8da8a83884a5'
|
||||
MANIFEST_SHA = 'bdf7839f832e2ea0cf230a0bd8a8fbff5d4a72d8fb7ba8208e0d252bad4b56ee'
|
||||
BUILD_RECORDS = {'preflight':'719adce7210742aea8d54b775613fae1eb7665c0b16d57730e1ade4e934348a3',
|
||||
'stage':'a12a138ea1583eb7d4328049f3d118d82085cd90aa472d02e5beac506b706ed8',
|
||||
'build':'58eaf0118f8f8573debfa21a295019a224b916cfc5b1a88edda426ec06bed2b5'}
|
||||
ARTIFACT = dict(bytes=848632,sha256='216b4d6a0f29ef47576f5ccc469954623141e55d7b43bd73175c1d956363bbbd',elf_machine=183)
|
||||
BROKER_ARTIFACT = dict(bytes=1067136,sha256='5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201',elf_machine=183)
|
||||
IMAGE = OLD / 'build/artifacts/operator_probe'
|
||||
PROBE_RECORDS = ('intent.json','before.json','start-intent.json','execution.json','after.json','result.json','failure.json','probe.log')
|
||||
SAMPLE_KEYS = {'profile','clock_authority','signed_attestation','captured_utc_ns','server_error_ns',
|
||||
'source_sync_age_ns','server_boot_id','captured_monotonic_ns','sampled_boottime_ns','kernel_state'}
|
||||
GENERATION_RECORDS = {'after-restart.json': {'metadata': {'ctime_ns': 1794739438793733913,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800469,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438793733913,
|
||||
'nlink': 1,
|
||||
'size': 4993,
|
||||
'uid': 0},
|
||||
'sha256': 'effd51775f9de314c8e99fdb785484737f9d315b685bb4b82fb042b11c48020d'},
|
||||
'after.json': {'metadata': {'ctime_ns': 1794739446181998648,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800478,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739446181998648,
|
||||
'nlink': 1,
|
||||
'size': 9456,
|
||||
'uid': 0},
|
||||
'sha256': '473c3c094a5f2ef950120c33ea4f2785362fa88898e21c8b22c50b456cdd932c'},
|
||||
'before.json': {'metadata': {'ctime_ns': 1794739438218723541,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800464,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438218723541,
|
||||
'nlink': 1,
|
||||
'size': 9449,
|
||||
'uid': 0},
|
||||
'sha256': '8a7488dbbef32b12d6c90d82f735308bb5ce88798d875a2ec7ae5ac4abfa623f'},
|
||||
'cas-intent.json': {'metadata': {'ctime_ns': 1794739445652017023,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800476,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739445652017023,
|
||||
'nlink': 1,
|
||||
'size': 1578,
|
||||
'uid': 0},
|
||||
'sha256': '55e77453996b29e4f9fc5ad9bde90d92302b81315072c98c9dbfb4db83b09630'},
|
||||
'intent.json': {'metadata': {'ctime_ns': 1794739438216723505,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800463,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438216723505,
|
||||
'nlink': 1,
|
||||
'size': 1353,
|
||||
'uid': 0},
|
||||
'sha256': '3c83287081e9b5f2c53c8957322ae5304f5ef17c92b2ac03f5394511dce08a59'},
|
||||
'new-public-pin.bin': {'metadata': {'ctime_ns': 1794739445916009070,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800477,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739445916009070,
|
||||
'nlink': 1,
|
||||
'size': 195,
|
||||
'uid': 0},
|
||||
'sha256': '395f170aabf9fd01c24cd7d7939a313befdd147e98343ccd383bca861cbf2c4e'},
|
||||
'old-public-pin.bin': {'metadata': {'ctime_ns': 1794739438220723577,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800465,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438220723577,
|
||||
'nlink': 1,
|
||||
'size': 194,
|
||||
'uid': 0},
|
||||
'sha256': '203f63f150026d345614ca53e641f248397166fbdeb1f28318fc5d7763317e0a'},
|
||||
'readiness-01.json': {'metadata': {'ctime_ns': 1794739439400744838,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800470,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739439400744838,
|
||||
'nlink': 1,
|
||||
'size': 1772,
|
||||
'uid': 0},
|
||||
'sha256': '9c0680cd15e453d479eaf8badfdc43b04598f7f0edda1221fde8a51168f443c6'},
|
||||
'readiness-02.json': {'metadata': {'ctime_ns': 1794739440991773473,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800471,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739440991773473,
|
||||
'nlink': 1,
|
||||
'size': 1772,
|
||||
'uid': 0},
|
||||
'sha256': '6b76ba69cd7f8adc8d31fd1283b9a8c0b775a61b861ab6e35df6ac5551a01313'},
|
||||
'readiness-03.json': {'metadata': {'ctime_ns': 1794739442592802289,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800472,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739442592802289,
|
||||
'nlink': 1,
|
||||
'size': 1771,
|
||||
'uid': 0},
|
||||
'sha256': '730b422dc3b9cbb8992838c2eb5e32a3d5aa9b8e3aa00324b721a614a69168c9'},
|
||||
'readiness-04.json': {'metadata': {'ctime_ns': 1794739444128865316,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800473,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739444128865316,
|
||||
'nlink': 1,
|
||||
'size': 1771,
|
||||
'uid': 0},
|
||||
'sha256': '038768187254e33b408a50dfb66467d41f0fe5bcaea2fe639d7abbebb7ed583e'},
|
||||
'readiness-05.json': {'metadata': {'ctime_ns': 1794739445645016897,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800474,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739445645016897,
|
||||
'nlink': 1,
|
||||
'size': 1758,
|
||||
'uid': 0},
|
||||
'sha256': '2440b67a720a6bdf33dde0ffb89f7b0736044126c1f6d7826fc84ba2f3aaff30'},
|
||||
'readiness.json': {'metadata': {'ctime_ns': 1794739445648016951,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800475,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739445648016951,
|
||||
'nlink': 1,
|
||||
'size': 1721,
|
||||
'uid': 0},
|
||||
'sha256': 'a19ace502cd44835fb941afa011b53f4d0e4bd9b05ecdcd38a2758c5089c1c03'},
|
||||
'restart-exit.json': {'metadata': {'ctime_ns': 1794739438591730278,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800468,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438591730278,
|
||||
'nlink': 1,
|
||||
'size': 1254,
|
||||
'uid': 0},
|
||||
'sha256': '6be145a67464f1bea7e8e77aed800118d9d8244bbd7ec0f4d00ed61e3452745f'},
|
||||
'restart-intent.json': {'metadata': {'ctime_ns': 1794739438495728549,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800466,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438495728549,
|
||||
'nlink': 1,
|
||||
'size': 1302,
|
||||
'uid': 0},
|
||||
'sha256': 'f993b2617821058736699812e4ac69e73fae92ab3f19e586ba922a63937408b9'},
|
||||
'restart.log': {'metadata': {'ctime_ns': 1794739438497728585,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800467,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739438497728585,
|
||||
'nlink': 1,
|
||||
'size': 0,
|
||||
'uid': 0},
|
||||
'sha256': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'},
|
||||
'result.json': {'metadata': {'ctime_ns': 1794739446183998570,
|
||||
'dev': 2049,
|
||||
'gid': 0,
|
||||
'ino': 800479,
|
||||
'mode': 33152,
|
||||
'mtime_ns': 1794739446183998570,
|
||||
'nlink': 1,
|
||||
'size': 1972,
|
||||
'uid': 0},
|
||||
'sha256': 'd648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4'}}
|
||||
GENERATION_MISSING = ('failure.json', 'readiness-06.json', 'readiness-07.json', 'readiness-08.json', 'readiness-09.json', 'readiness-10.json', 'readiness-11.json', 'readiness-12.json', 'readiness-13.json', 'readiness-14.json', 'readiness-15.json', 'readiness-16.json', 'readiness-17.json', 'readiness-18.json', 'readiness-19.json', 'readiness-20.json', 'readiness-21.json', 'readiness-22.json', 'readiness-23.json', 'readiness-24.json', 'readiness-25.json')
|
||||
|
||||
class GuardDenied(RuntimeError):
|
||||
pass
|
||||
|
||||
def require(ok,reason):
|
||||
if not ok:
|
||||
raise GuardDenied(reason)
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
def load_pin_controller():
|
||||
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
for part in PIN_CONTROLLER.parent.parts[1:]:
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry')
|
||||
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = next_fd
|
||||
info = os.fstat(fd)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_parent')
|
||||
file_fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
|
||||
with os.fdopen(file_fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
|
||||
before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and
|
||||
before.st_size <= 128 * 1024, 'reviewed_root_controller_file')
|
||||
raw = stream.read(128 * 1024 + 1)
|
||||
stable = lambda s: tuple(getattr(s, 'st_' + k) for k in
|
||||
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns'))
|
||||
require(stable(before) == stable(os.fstat(stream.fileno())) ==
|
||||
stable(os.stat(PIN_CONTROLLER.name, dir_fd=fd, follow_symlinks=False)) and
|
||||
len(raw) == before.st_size and sha(raw) == PIN_CONTROLLER_SHA, 'exact_pin_controller_bytes')
|
||||
finally:
|
||||
os.close(fd)
|
||||
pin = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_pin_guard', loader=None))
|
||||
pin.__file__ = str(PIN_CONTROLLER)
|
||||
exec(compile(raw, str(PIN_CONTROLLER), 'exec'), pin.__dict__)
|
||||
held = pin.read_file(PIN_CONTROLLER, 128 * 1024)
|
||||
require(held[0] == raw, 'same_loaded_pin_controller')
|
||||
return pin, lambda: require(pin.read_file(PIN_CONTROLLER, 128 * 1024) == held, 'pin_controller_unchanged')
|
||||
|
||||
|
||||
class HeldFile:
|
||||
def __init__(self, pin, path, maximum=65536, mode=0o600, expected=None, metadata=None):
|
||||
self.pin, self.path, self.maximum = pin, path, maximum
|
||||
self.parent = self.fd = -1
|
||||
try:
|
||||
self.parent = pin.directory(path.parent)
|
||||
self.parent_identity = pin.stable_directory(os.fstat(self.parent))
|
||||
self.fd = os.open(path.name, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW, dir_fd=self.parent)
|
||||
self.metadata = pin.identity(os.fstat(self.fd))
|
||||
require(stat.S_ISREG(self.metadata['mode']) and self.metadata['uid'] == self.metadata['gid'] == 0
|
||||
and self.metadata['nlink'] == 1 and stat.S_IMODE(self.metadata['mode']) == mode
|
||||
and 0 <= self.metadata['size'] <= maximum, 'protected_bounded_original_held_file')
|
||||
self.raw = os.pread(self.fd, maximum + 1, 0)
|
||||
require(len(self.raw) == self.metadata['size'] and (expected is None or sha(self.raw) == expected)
|
||||
and (metadata is None or self.metadata == metadata), 'exact_frozen_held_file_bytes_and_metadata')
|
||||
self.fresh()
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def fresh(self):
|
||||
require(self.fd >= 0 and self.pin.identity(os.fstat(self.fd)) == self.metadata
|
||||
and os.pread(self.fd, self.maximum + 1, 0) == self.raw
|
||||
and self.pin.identity(os.stat(self.path.name, dir_fd=self.parent, follow_symlinks=False)) == self.metadata,
|
||||
'same_held_original_file_and_named_inode')
|
||||
parent = self.pin.directory(self.path.parent)
|
||||
try:
|
||||
require(self.pin.stable_directory(os.fstat(parent)) == self.parent_identity
|
||||
== self.pin.stable_directory(os.fstat(self.parent)), 'same_protected_held_file_parent')
|
||||
finally:
|
||||
os.close(parent)
|
||||
return self.raw, dict(self.metadata)
|
||||
|
||||
def close(self):
|
||||
for name in ('fd', 'parent'):
|
||||
fd = getattr(self, name)
|
||||
if fd >= 0:
|
||||
os.close(fd)
|
||||
setattr(self, name, -1)
|
||||
|
||||
|
||||
class QualifiedBuild:
|
||||
"""Historical build/source verification only: never compares an old PID to the host."""
|
||||
def __init__(self, proof):
|
||||
self.proof, self.source_sha, self.manifest_sha = proof, SOURCE_SHA, MANIFEST_SHA
|
||||
pin, operator = proof.pin, proof.operator
|
||||
records = {name: pin.parsed(proof.hold(OLD / name / 'result.json', expected=digest).raw)
|
||||
for name, digest in BUILD_RECORDS.items()}
|
||||
preflight, stage, build = (records[name] for name in ('preflight', 'stage', 'build'))
|
||||
self.historical_expected = pin.observation_key(preflight)
|
||||
require(build['exit_code'] == 0 and build['runtime_metadata_equal'] is True
|
||||
and build['native_source_quality_tested'] is False
|
||||
and build['artifacts'] == {'examples/operator_probe': ARTIFACT, 'rmm-time-broker-linux': BROKER_ARTIFACT}
|
||||
and pin.observation_key(preflight) == pin.observation_key(build['before']) == pin.observation_key(build['after']),
|
||||
'successful_frozen_historical_build_not_current_process_authority')
|
||||
proof.hold(OLD / 'source.tar', 2 * 1024 * 1024, expected=SOURCE_SHA)
|
||||
manifest = pin.parsed(proof.hold(OLD / 'workspace/manifest.json', expected=MANIFEST_SHA).raw)
|
||||
require(stage['manifest_sha256'] == build['staged_manifest_sha256'] == MANIFEST_SHA
|
||||
and stage['source_tar_sha256'] == SOURCE_SHA and manifest['operator_sha256'] == pin.OPERATOR_SHA
|
||||
and manifest['package_files'] == stage['package_files']
|
||||
and manifest['public_commit'] == stage['public_commit'], 'historical_source_manifest_stage_build_binding')
|
||||
pin.source_items(manifest['source_files'])
|
||||
pin.source_items(manifest['package_files'])
|
||||
source = [item for item in manifest['source_files'] if item['path'] == 'crates/time-source-linux/src/native.rs']
|
||||
require(len(source) == 1 and source[0]['sha256'] == pin.PROVIDER_SHA, 'unchanged_original_named_provider')
|
||||
self.artifacts = {}
|
||||
for name, expected in build['artifacts'].items():
|
||||
path = OLD / 'build/artifacts' / Path(name).name
|
||||
held = proof.hold(path, 32 * 1024 * 1024, 0o500, expected['sha256'])
|
||||
require(len(held.raw) == expected['bytes'] and held.raw[:6] == b'\x7fELF\x02\x01'
|
||||
and struct.unpack('<H', held.raw[18:20])[0] == 183, 'original_root_500_aarch64_artifact')
|
||||
self.artifacts[name] = (path, dict(expected), dict(held.metadata))
|
||||
self.fresh()
|
||||
|
||||
def fresh(self):
|
||||
require(self.proof.operator.verify_workspace(OLD)['manifest_sha256'] == MANIFEST_SHA,
|
||||
'unchanged_original_complete_workspace_source')
|
||||
|
||||
|
||||
class SharedGenerationProof:
|
||||
"""Read-only public source/generation proof. Does not inspect signer key contents."""
|
||||
def __init__(self, pin):
|
||||
self.pin, self._held, self._quality = pin, {}, {}
|
||||
self._case_fd = -1
|
||||
try:
|
||||
self.hold(PIN_CONTROLLER, 128 * 1024, expected=PIN_CONTROLLER_SHA)
|
||||
self.operator, self.operator_guard = pin.load_operator()
|
||||
self.hold(pin.OPERATOR, 128 * 1024, expected=pin.OPERATOR_SHA)
|
||||
code = self.hold(GENERATION_CONTROLLER, 128 * 1024, expected=GENERATION_CONTROLLER_SHA)
|
||||
self.generation = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_fixed_generation_reader', loader=None))
|
||||
self.generation.__file__ = str(GENERATION_CONTROLLER)
|
||||
exec(compile(code.raw, str(GENERATION_CONTROLLER), 'exec'), self.generation.__dict__)
|
||||
self._case_fd = pin.directory(BASE)
|
||||
require(stat.S_IMODE(os.fstat(self._case_fd).st_mode) == 0o700
|
||||
and set(GENERATION_RECORDS).isdisjoint(GENERATION_MISSING)
|
||||
and set(GENERATION_RECORDS) | set(GENERATION_MISSING) == set(self.generation.RECORDS),
|
||||
'complete_exact_private_generation_record_set')
|
||||
for name, expected in GENERATION_RECORDS.items():
|
||||
self.hold(BASE / name, 65536, expected=expected['sha256'], metadata=expected['metadata'])
|
||||
self.result = pin.parsed(self._held[BASE / 'result.json'].raw)
|
||||
require(sha(self._held[BASE / 'result.json'].raw) == GENERATION_RESULT_SHA,
|
||||
'fixed_actual_generation_result_hash')
|
||||
self.after = pin.parsed(self._held[BASE / 'after.json'].raw)
|
||||
self.before = pin.parsed(self._held[BASE / 'before.json'].raw)
|
||||
require(self.result['case'] == CASE_ID and self.result['controller_sha256'] == GENERATION_CONTROLLER_SHA
|
||||
and self.result['new_generation_pinned'] is True and self.result['restart_exit_code'] == 0
|
||||
and self.result['runtime_boot_configuration_images_preserved'] is True
|
||||
and all(self.result[key] is False for key in ('source_quality_qualified','native_source_sampled',
|
||||
'signer_created','signed_attestation','broker_started')),
|
||||
'actual_successful_non_quality_generation_change')
|
||||
self.generation.generation(self.before['actual'], self.after['actual'])
|
||||
pin_record = self.hold(pin.ETC / 'chrony-pin.json', 256, expected=PUBLIC_PIN_SHA,
|
||||
metadata=self.result['new_public_pin_metadata'])
|
||||
self.public_pin_raw, self.public_pin_metadata = pin_record.raw, dict(pin_record.metadata)
|
||||
require(len(self.public_pin_raw) == 195 and self.public_pin_raw == self._held[BASE / 'new-public-pin.bin'].raw
|
||||
== pin.encoded(self.result['new_chrony_observation'])
|
||||
and self.after['public_pin_sha256'] == PUBLIC_PIN_SHA
|
||||
and self.after['public_pin_metadata'] == self.public_pin_metadata
|
||||
and pin.parsed(self._held[BASE / 'cas-intent.json'].raw)['actual_new_observation']
|
||||
== self.result['new_chrony_observation'] == self.after['actual']['chrony_observation'],
|
||||
'actual_new_public_pin_cas_after_record_binding')
|
||||
self.expected = pin.observation_key(self.after['actual'])
|
||||
self.build = QualifiedBuild(self)
|
||||
require(pin.observation_key(self.before['actual']) == self.build.historical_expected,
|
||||
'generation_change_starts_at_exact_historical_build_generation')
|
||||
self.artifacts, self.source_sha, self.manifest_sha = self.build.artifacts, SOURCE_SHA, MANIFEST_SHA
|
||||
original_pin = pin.parsed(self.hold(OLD / 'pin/result.json', expected=
|
||||
'd0a9ac7b46bdf4247c420f01d959c41d6620f7081c40629016d6866828884c4b').raw)
|
||||
self.target_directories = {name: {key: original_pin['targets'][name][key]
|
||||
for key in ('dev','ino','uid','gid','mode')} for name in
|
||||
(str(pin.ETC), str(pin.RUN), str(pin.RUN / 'clients'))}
|
||||
self.fresh()
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def hold(self, path, maximum=65536, mode=0o600, expected=None, metadata=None):
|
||||
if path not in self._held:
|
||||
self._held[path] = HeldFile(self.pin, path, maximum, mode, expected, metadata)
|
||||
held = self._held[path]
|
||||
require((expected is None or sha(held.raw) == expected)
|
||||
and (metadata is None or held.metadata == metadata), 'consistent_same_original_held_record')
|
||||
return held
|
||||
|
||||
@property
|
||||
def records(self):
|
||||
return {path: (held.raw, dict(held.metadata)) for path, held in self._held.items()}
|
||||
|
||||
def namespace_verify(self):
|
||||
current = self.generation.namespace(self.pin, self.result['new_chrony_observation']['daemon_pid'])
|
||||
require(current == self.after['namespace'], 'same_actual_new_generation_namespace')
|
||||
return current
|
||||
|
||||
def fresh(self):
|
||||
self.operator_guard()
|
||||
for held in self._held.values():
|
||||
held.fresh()
|
||||
for name in GENERATION_MISSING:
|
||||
self.pin.absence(self._case_fd, name)
|
||||
self.build.fresh()
|
||||
current = self.operator.preflight()
|
||||
require(self.pin.observation_key(current) == self.expected
|
||||
== self.pin.observation_key(self.after['actual']), 'current_exact_new_generation_runtime_boot')
|
||||
require(self.generation.configuration(self.pin, self.operator) == self.after['configuration'],
|
||||
'current_original_configuration_and_typed_unit')
|
||||
self.namespace_verify()
|
||||
for name, expected in self.target_directories.items():
|
||||
fd = self.pin.directory(Path(name))
|
||||
try:
|
||||
require(self.pin.stable_directory(os.fstat(fd)) == expected
|
||||
and self.generation.acl(fd, 'system.posix_acl_default') is None,
|
||||
'same_source_target_directory_identity_default_acl')
|
||||
if name == str(self.pin.ETC):
|
||||
require(self.generation.acl(fd, 'system.posix_acl_access') is None,
|
||||
'same_protected_pin_parent_access_acl')
|
||||
finally:
|
||||
os.close(fd)
|
||||
require(current['chrony_observation'] == self.pin.parsed(self.public_pin_raw), 'actual_new_pin_six_fields')
|
||||
return dict(current['chrony_observation'])
|
||||
|
||||
def witness(self):
|
||||
self.fresh()
|
||||
return dict(observation=self.expected, public_pin_sha256=PUBLIC_PIN_SHA,
|
||||
public_pin_metadata=self.public_pin_metadata, target_directories=self.target_directories,
|
||||
configuration=self.after['configuration'], namespace=self.after['namespace'],
|
||||
generation_result_sha256=GENERATION_RESULT_SHA,
|
||||
generation_after_sha256=GENERATION_RECORDS['after.json']['sha256'],
|
||||
build_result_sha256=BUILD_RECORDS['build'])
|
||||
|
||||
def binding(self):
|
||||
own = self.hold(Path(__file__), 128 * 1024)
|
||||
require(own.path.name == 'new_generation_probe.py' and own.path.parent.name == sha(own.raw),
|
||||
'fixed_content_addressed_native_probe_controller')
|
||||
return dict(profile=PROFILE, case=CASE_ID, original_case=OLD.name, phase=QUALITY_PHASE, unit=UNIT,
|
||||
controller_sha256=sha(own.raw), operator_sha256=self.pin.OPERATOR_SHA,
|
||||
pin_controller_sha256=PIN_CONTROLLER_SHA, generation_controller_sha256=GENERATION_CONTROLLER_SHA,
|
||||
generation_result_sha256=GENERATION_RESULT_SHA, generation_receipt_sha256=GENERATION_RECEIPT_SHA,
|
||||
generation_read_receipt_sha256=GENERATION_READ_RECEIPT_SHA, public_pin_sha256=PUBLIC_PIN_SHA,
|
||||
source_tar_sha256=SOURCE_SHA, manifest_sha256=MANIFEST_SHA,
|
||||
build_result_sha256=BUILD_RECORDS['build'], artifact=ARTIFACT)
|
||||
|
||||
def quality_proof(self, expected_result_sha256):
|
||||
require(type(expected_result_sha256) is str and len(expected_result_sha256) == 64
|
||||
and all(value in '0123456789abcdef' for value in expected_result_sha256), 'explicit_actual_quality_result_hash')
|
||||
result_file = self.hold(BASE / QUALITY_PHASE / 'result.json', expected=expected_result_sha256)
|
||||
result = self.pin.parsed(result_file.raw)
|
||||
binding = self.binding()
|
||||
extras = {'before_witness','after_witness','exit_code','sample','probe_log_sha256','source_quality_qualified',
|
||||
'runtime_boot_pin_source_preserved','clock_authority','signed_attestation','signer_created',
|
||||
'broker_started','http_deployed','no_rmm_jobs'}
|
||||
require(set(result) == set(binding) | extras and all(result[key] == value for key, value in binding.items())
|
||||
and type(result['exit_code']) is int and result['exit_code'] == 0
|
||||
and result['source_quality_qualified'] is True and result['runtime_boot_pin_source_preserved'] is True
|
||||
and result['no_rmm_jobs'] is True
|
||||
and all(result[key] is False for key in ('clock_authority','signed_attestation','signer_created',
|
||||
'broker_started','http_deployed')), 'exact_actual_positive_native_quality_result')
|
||||
log = self.hold(BASE / QUALITY_PHASE / 'probe.log', 16384, expected=result['probe_log_sha256'])
|
||||
require(self.pin.parsed(log.raw) == result['sample'], 'actual_native_log_sample_matches_result')
|
||||
sample_quality(result['sample'], self.expected['boot_id'])
|
||||
paths = {result_file.path, log.path}
|
||||
expected_witness = self.witness()
|
||||
for name in ('before','after'):
|
||||
link = result[name + '_witness']
|
||||
require(type(link) is dict and set(link) == {'filename','sha256'} and link['filename'] == name + '.json',
|
||||
'exact_native_quality_witness_filename')
|
||||
held = self.hold(BASE / QUALITY_PHASE / link['filename'], expected=link['sha256'])
|
||||
value = self.pin.parsed(held.raw)
|
||||
require(set(value) == set(binding) | {'witness'}
|
||||
and all(value[key] == item for key, item in binding.items())
|
||||
and value['witness'] == expected_witness, 'same_actual_quality_witness_binding')
|
||||
paths.add(held.path)
|
||||
phase = self.pin.directory(BASE / QUALITY_PHASE)
|
||||
try:
|
||||
self.pin.absence(phase, 'failure.json')
|
||||
finally:
|
||||
os.close(phase)
|
||||
return {path: (self._held[path].raw, dict(self._held[path].metadata)) for path in paths}
|
||||
|
||||
def close(self):
|
||||
for held in self._held.values():
|
||||
held.close()
|
||||
if self._case_fd >= 0:
|
||||
os.close(self._case_fd)
|
||||
self._case_fd = -1
|
||||
|
||||
|
||||
def sample_quality(sample, boot):
|
||||
require(type(sample) is dict and set(sample) == SAMPLE_KEYS
|
||||
and sample['profile'] == 'rmm.native-source-quality.once.v1'
|
||||
and sample['clock_authority'] is False and sample['signed_attestation'] is False
|
||||
and sample['server_boot_id'] == boot and str(uuid.UUID(boot)) == boot,
|
||||
'exact_non_authoritative_native_sample_schema_and_boot')
|
||||
for key, upper in (('captured_utc_ns', 2**63 - 1), ('server_error_ns', 500_000_000),
|
||||
('source_sync_age_ns', 3_600_000_000_000), ('captured_monotonic_ns', 2**64 - 1),
|
||||
('sampled_boottime_ns', 2**64 - 1), ('kernel_state', 4)):
|
||||
require(type(sample[key]) is int and 0 <= sample[key] <= upper, 'bounded_numeric_quality_sample')
|
||||
require(sample['captured_utc_ns'] > 0 and sample['captured_monotonic_ns'] > 0
|
||||
and sample['sampled_boottime_ns'] >= sample['captured_monotonic_ns'], 'positive_native_time_domains')
|
||||
|
||||
|
||||
def probe_args():
|
||||
return ['systemd-run', '--quiet', '--wait', '--pipe', '--collect', '--unit=' + UNIT,
|
||||
'--property=Type=exec', '--property=User=root', '--property=Group=989',
|
||||
'--property=SupplementaryGroups=', '--property=NoNewPrivileges=yes',
|
||||
'--property=CapabilityBoundingSet=CAP_SYS_PTRACE CAP_DAC_OVERRIDE', '--property=AmbientCapabilities=',
|
||||
'--property=ProtectSystem=strict', '--property=ProtectHome=yes', '--property=PrivateTmp=yes',
|
||||
'--property=PrivateDevices=yes', '--property=RestrictAddressFamilies=AF_UNIX',
|
||||
'--property=IPAddressDeny=any',
|
||||
'--property=SystemCallFilter=~@debug ptrace process_vm_readv process_vm_writev',
|
||||
'--property=RuntimeMaxSec=3s', '--property=ReadWritePaths=/run/rmm-time-source/clients', str(IMAGE)]
|
||||
|
||||
|
||||
def save(pin, parent, name, value):
|
||||
require(name in PROBE_RECORDS and name.endswith('.json'), 'fixed_probe_record_leaf')
|
||||
raw = pin.encoded(value)
|
||||
require(len(raw) <= 65536, 'bounded_probe_record')
|
||||
fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
||||
try:
|
||||
view = memoryview(raw)
|
||||
while view:
|
||||
written = os.write(fd, view)
|
||||
require(written > 0, 'complete_create_once_probe_record')
|
||||
view = view[written:]
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
os.fsync(parent)
|
||||
|
||||
|
||||
def host_read(pin):
|
||||
# No ecb/d5 import, subprocess, NSS, preflight, sample or retry.
|
||||
records = {}
|
||||
for name in PROBE_RECORDS:
|
||||
try:
|
||||
raw, metadata = pin.read_file(BASE / QUALITY_PHASE / name, 65536)
|
||||
records[name] = dict(sha256=sha(raw), metadata=metadata,
|
||||
record=raw.decode('ascii') if name == 'probe.log' else pin.parsed(raw))
|
||||
except FileNotFoundError:
|
||||
records[name] = None
|
||||
print(pin.encoded(dict(case=CASE_ID, original_case=OLD.name, phase=QUALITY_PHASE,
|
||||
read_only=True, records=records)).decode(), end='')
|
||||
|
||||
|
||||
def host_probe(pin):
|
||||
proof = None
|
||||
phase = -1
|
||||
case = pin.directory(BASE)
|
||||
try:
|
||||
pin.absence(case, QUALITY_PHASE)
|
||||
proof = SharedGenerationProof(pin)
|
||||
binding = proof.binding()
|
||||
require(proof.artifacts['examples/operator_probe'][:2] == (IMAGE, ARTIFACT), 'fixed_original_single_native_probe')
|
||||
def fresh():
|
||||
value = proof.witness()
|
||||
proof.generation.no_broker(proof.operator)
|
||||
return value
|
||||
before = fresh()
|
||||
os.mkdir(QUALITY_PHASE, 0o700, dir_fd=case)
|
||||
os.fsync(case)
|
||||
phase = os.open(QUALITY_PHASE, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case)
|
||||
save(pin, phase, 'intent.json', dict(binding, once=True, no_retry=True, sample_limit=1))
|
||||
save(pin, phase, 'before.json', dict(binding, witness=before))
|
||||
require(fresh() == before, 'same_proven_generation_before_one_native_sample')
|
||||
save(pin, phase, 'start-intent.json', dict(binding, argv=probe_args(), once=True))
|
||||
code = proof.operator.long_command(probe_args(), BASE / QUALITY_PHASE / 'probe.log', 10)
|
||||
log, _ = pin.read_file(BASE / QUALITY_PHASE / 'probe.log', 16384)
|
||||
save(pin, phase, 'execution.json', dict(binding, exit_code=code, probe_log_sha256=sha(log)))
|
||||
after = fresh()
|
||||
require(before == after, 'new_generation_runtime_boot_pin_source_preserved')
|
||||
save(pin, phase, 'after.json', dict(binding, witness=after))
|
||||
sample = pin.parsed(log) if code == 0 else None
|
||||
if code == 0:
|
||||
sample_quality(sample, proof.expected['boot_id'])
|
||||
links = {name + '_witness': dict(filename=name + '.json',
|
||||
sha256=sha(pin.read_file(BASE / QUALITY_PHASE / (name + '.json'), 65536)[0])) for name in ('before','after')}
|
||||
result = dict(binding, **links, exit_code=code, sample=sample, probe_log_sha256=sha(log),
|
||||
source_quality_qualified=code == 0, runtime_boot_pin_source_preserved=True,
|
||||
clock_authority=False, signed_attestation=False, signer_created=False, broker_started=False,
|
||||
http_deployed=False, no_rmm_jobs=True)
|
||||
save(pin, phase, 'result.json', result)
|
||||
if code == 0:
|
||||
proof.quality_proof(sha(pin.read_file(BASE / QUALITY_PHASE / 'result.json', 65536)[0]))
|
||||
print(pin.encoded(result).decode(), end='')
|
||||
except Exception as error:
|
||||
if phase >= 0:
|
||||
tag = str(error) if isinstance(error, GuardDenied) and str(error).isascii() and len(str(error)) <= 128 \
|
||||
and all(value in 'abcdefghijklmnopqrstuvwxyz0123456789_' for value in str(error)) else 'unexpected_native_probe_exception'
|
||||
save(pin, phase, 'failure.json', dict(profile=PROFILE, case=CASE_ID, phase=QUALITY_PHASE,
|
||||
fixed_tag=tag, failed=True, read_original_phase_only=True))
|
||||
raise
|
||||
finally:
|
||||
if proof is not None:
|
||||
proof.close()
|
||||
if phase >= 0:
|
||||
os.close(phase)
|
||||
os.close(case)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=('host-probe','host-read'))
|
||||
args = parser.parse_args()
|
||||
require(sys.flags.isolated == 1 and os.geteuid() == 0 and os.uname().sysname == 'Linux'
|
||||
and os.uname().machine == 'aarch64', 'isolated_root_server_arm64_only')
|
||||
os.umask(0o077)
|
||||
pin, guard = load_pin_controller()
|
||||
guard()
|
||||
if args.command == 'host-read':
|
||||
host_read(pin)
|
||||
else:
|
||||
host_probe(pin)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
print(json.dumps(dict(profile=PROFILE, case=CASE_ID, phase=QUALITY_PHASE,
|
||||
failed=True, read_original_phase_only=True)))
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -1,334 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Frozen ten-worker list, executing exactly two process-census guards only; no 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/agent-updater-worker/reader-census-final-da31051b-269f-4fb5-947d-94c8ad162c2a'
|
||||
STATE = ROOT / 'devstate/updater-reader-census-linux'
|
||||
PROFILE = 'rmm.updater.two-process-census-guards.v1'
|
||||
RECEIPT_SHA = '9020992e888d0b22e71db88cab78f255e273be2a4a7856d43616b387c36c74ae'
|
||||
INPUTS_SHA = '382714b09349e448441345abbac6d99c0d523e98bdabaa78290b400768bac8f7'
|
||||
BINARY_SHA = 'e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304'
|
||||
BINARY_BYTES = 7888096
|
||||
CENSUS_SOURCES = {'crates/updater-worker/src/census.rs': {'bytes': 17766, 'sha256': '5bee7f835c3b3c1f7e3a6afeeb1dc1fde780f1a6ca0d09a1bc85d897249e053c'}, 'crates/updater-worker/src/census_process.rs': {'bytes': 25024, 'sha256': 'f94b3032cee983fb01bfeb97a1cfc497fddcfd1e6f00e055d87269cc3f5dad5e'}, 'crates/updater-worker/src/reader_registry.rs': {'bytes': 29064, 'sha256': 'fc013cde406f4dac96a35df3852738b0ff84d912c4eeba401609b0d2b239d1b1'}}
|
||||
ALL_TESTS = ['agent_startup::tests::existing_agent_lock_blocks_aliases_and_rejects_samebyte_inode_substitution', 'census_process::tests::actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths', 'census_process::tests::private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe', 'history::tests::completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes', 'history::tests::public_record_builder_binds_actual_original_key_and_exact_health_head', 'reader_registry::tests::timer_without_process_interface_is_typed_but_missing_service_pid_or_pending_job_denies', 'record::tests::same_byte_inode_substitution_and_foreign_current_block_without_resume', 'record::tests::separate_record_renames_preserve_original_inode_and_both_raw_archives', 'retained::tests::reopen_preserves_original_stamps_and_rejects_replaced_state_without_reading_keys', 'trust::tests::separately_signed_baseline_at_floor_is_historical_only_and_candidate_stays_strict']
|
||||
TESTS = ['census_process::tests::actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths', 'census_process::tests::private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe']
|
||||
TEST_FILTER = 'census_process::tests::'
|
||||
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 <= 8 * 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_tests'] == ALL_TESTS
|
||||
and value['test_filter'] == TEST_FILTER
|
||||
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) == 71 and source == value['source_files'], 'exact frozen 71 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')
|
||||
support.require({item['path']: dict(bytes=item['bytes'], sha256=item['sha256']) for item in source
|
||||
if item['path'] in CENSUS_SOURCES} == CENSUS_SOURCES, 'exact census and registry source snapshot')
|
||||
binary = folder / 'worker-census-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',
|
||||
'/var/lib/rmm-agent-remote/agent.lock'):
|
||||
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 process-census fixtures')
|
||||
require(p['profile'] == 'rmm.updater.two-process-census-guards.v1'
|
||||
and p['binary_sha256'] == 'e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304'
|
||||
and p['test_filter'] == 'census_process::tests::'
|
||||
and len(p['all_tests']) == 10 and len(p['tests']) == 2
|
||||
and [name for name in p['all_tests'] if name.startswith(p['test_filter'])] == p['tests'],
|
||||
'closed two-test census scope before remote case creation')
|
||||
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case')
|
||||
folder = Path('/var/tmp') / ('rmm-updater-reader-census-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')
|
||||
intent = json.loads((folder / 'intent.json').read_bytes())
|
||||
require(all(intent.get(key) == value for key,value in p.items() if key != 'action'), 'same original read binding')
|
||||
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 process-census unit 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']) == 10517464, 'bounded binary transfer')
|
||||
raw = base64.b64decode(p['binary_b64'], validate=True)
|
||||
require(len(raw) == 7888096 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed worker test binary; only the closed census filter may run')
|
||||
binary = folder / 'worker-census-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) == 10 and all(line.endswith(': test') for line in lines) and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['all_tests'], 'exact ten names before selecting only two census tests')
|
||||
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
|
||||
code, stdout, stderr = run(command + [p['test_filter'], '--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'2 passed; 0 failed; 0 ignored; 0 measured; 8 filtered out' in stdout
|
||||
and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'two selected native census guards, eight filtered and retained target state')
|
||||
receipt = dict(id=ident, profile=p['profile'], passed=2, ignored=0, filtered=8, listed=10, execution_uid=0, tests=p['tests'],
|
||||
all_tests=p['all_tests'], test_filter=p['test_filter'],
|
||||
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) == 71
|
||||
and receipt['input_count'] == 71 and receipt['tests'] == dict(passed=10,failed=0,ignored=0,filtered=0,complete_names=ALL_TESTS)
|
||||
and receipt['checks'] == dict(fmt=0,check=0,clippy=0,build=0,list=0,unit=0)
|
||||
and receipt['native_apply_run'] is False and receipt['target_calls'] is False,
|
||||
'reviewed ten-worker qualification, only two census tests selected')
|
||||
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
|
||||
copy_exact(receipt_path, folder / 'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size)
|
||||
copy_exact(QUALIFICATION / 'inputs.json', folder / 'inputs.json', INPUTS_SHA, (QUALIFICATION / 'inputs.json').stat().st_size)
|
||||
paths = set()
|
||||
for item in original:
|
||||
path = Path(item['path'])
|
||||
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique fixed frozen input')
|
||||
paths.add(str(path)); copy_exact(QUALIFICATION / 'source' / path, folder / 'source' / path, item['sha256'], item['bytes'])
|
||||
binary = QUALIFICATION / 'qualified-worker-tests'
|
||||
support.require(receipt['binary'] == dict(filename='qualified-worker-tests', bytes=BINARY_BYTES,
|
||||
sha256=BINARY_SHA, mode='0500', nlink=1), 'fixed original linked artifact')
|
||||
copy_exact(binary, folder / 'worker-census-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_tests=ALL_TESTS, test_filter=TEST_FILTER, 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_tests=ALL_TESTS, test_filter=TEST_FILTER, 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 / 'worker-census-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['result']['source_receipt_sha256'] == RECEIPT_SHA
|
||||
and response['result']['binary_sha256'] == BINARY_SHA and response['result']['tests'] == TESTS
|
||||
and response['result']['passed'] == 2 and response['result']['ignored'] == 0 and response['result']['filtered'] == 8
|
||||
and response['result']['listed'] == 10 and response['result']['all_tests'] == ALL_TESTS
|
||||
and response['result']['test_filter'] == TEST_FILTER
|
||||
and response['result']['before'] == response['result']['after']
|
||||
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()
|
||||
@@ -4,11 +4,6 @@ Stand 2026-11-13, Spezifikation 1.15. Windows-11-Gast und Notebook-Host sind
|
||||
verschiedene Geräte. Auf dem Notebook laufen ausschließlich Entwicklungstools;
|
||||
der Client verwendet den endgültigen Cloudserver `discovery.ease-technologies.de`.
|
||||
|
||||
Neuer Quellenstand 2026-11-15: [passive Zertifikatserneuerung](../../docs/windows-certificate-renewal.md)
|
||||
mit geschützter Keydatei und atomarer Versionswahl ist implementiert; native
|
||||
Windows-Renewal-/Abbruch-/DACLabnahme und Freigabe der permanenten Identität
|
||||
bleiben offen. Frühere Transportabnahmen darunter bleiben historische Belege.
|
||||
|
||||
## Aktueller Dienst dauerhaft auf Auto — 2026-11-13
|
||||
|
||||
Nach dem bestandenen Fallbacktest wurde die bestehende VM im separaten Fall
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][DateTimeOffset]$PreviousExpiry,
|
||||
[Parameter(Mandatory)][DateTimeOffset]$Until,
|
||||
[switch]$ResumeInterrupted
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$utcNow = [DateTimeOffset]::UtcNow
|
||||
if ($PreviousExpiry -ge $utcNow -or $Until -le $utcNow -or $Until -gt $utcNow.AddHours(4)) {
|
||||
throw 'Expected an expired previous window and a new deadline within four hours.'
|
||||
}
|
||||
$dir = 'C:\ProgramData\RmmDevAccess'
|
||||
$configPath = Join-Path $dir 'bootstrap-public.json'
|
||||
$raw = [IO.File]::ReadAllText($configPath)
|
||||
$cfg = $raw | ConvertFrom-Json
|
||||
$user = Get-LocalUser -Name 'rmm-dev'
|
||||
$task = Get-ScheduledTask -TaskPath '\' -TaskName 'RmmDevReverseTunnel'
|
||||
$expectedState = if ($ResumeInterrupted) { 'Disabled' } else { 'Ready' }
|
||||
$expectedExpiry = if ($ResumeInterrupted) { $Until } else { $PreviousExpiry }
|
||||
$mismatches = @(
|
||||
if ($task.State -ne $expectedState) { "task state $($task.State) (expected $expectedState)" }
|
||||
if (!$user.Enabled) { 'rmm-dev is disabled' }
|
||||
if (!$user.AccountExpires) {
|
||||
'rmm-dev has no account expiry'
|
||||
} elseif ($user.AccountExpires.ToUniversalTime() -ne $expectedExpiry.UtcDateTime) {
|
||||
"account expiry $($user.AccountExpires.ToUniversalTime().ToString('o')) (expected $($expectedExpiry.UtcDateTime.ToString('o')))"
|
||||
}
|
||||
if ([DateTimeOffset]::Parse($cfg.expires_at) -ne $expectedExpiry) {
|
||||
"configuration expiry $($cfg.expires_at) (expected $($expectedExpiry.UtcDateTime.ToString('o')))"
|
||||
}
|
||||
if ($cfg.server -cne 'discovery.ease-technologies.de') { 'configured server differs' }
|
||||
$sshdState = (Get-Service -Name sshd).Status
|
||||
if ($sshdState -ne 'Running') { "sshd state $sshdState (expected Running)" }
|
||||
)
|
||||
if ($mismatches.Count -gt 0) {
|
||||
throw ('Maintenance window preflight failed: ' + ($mismatches -join ', '))
|
||||
}
|
||||
$pinned = (Get-Content -LiteralPath (Join-Path $dir 'known_hosts') -Raw).Trim()
|
||||
if ($pinned -cne ('discovery.ease-technologies.de ' + $cfg.server_host_key)) {
|
||||
throw 'Unexpected SSH host pin.'
|
||||
}
|
||||
$listeners = @(Get-NetTCPConnection -State Listen -LocalPort 22222)
|
||||
if ($listeners.Count -ne 1 -or $listeners[0].LocalAddress -ne '127.0.0.1') {
|
||||
throw 'Expected only the original loopback SSH listener.'
|
||||
}
|
||||
$backup = Join-Path $dir ('console-window-' + [guid]::NewGuid().ToString() + '.bak')
|
||||
$originalRaw = $raw
|
||||
if ($ResumeInterrupted) {
|
||||
$owners = @(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='pwsh.exe' OR Name='ssh.exe'" | Where-Object {
|
||||
$_.ProcessId -ne $PID -and ($_.CommandLine -match '(?:rmm-window-[0-9a-f-]+|Open-ConsoleMaintenanceWindow)\.ps1' -or
|
||||
($_.Name -eq 'ssh.exe' -and $_.CommandLine -match '127\.0\.0\.1:22240:127\.0\.0\.1:22222'))
|
||||
})
|
||||
if ($owners.Count) { throw 'An existing maintenance console or forwarding process is still active. End the original console with Ctrl+C first.' }
|
||||
$copies = @(Get-ChildItem -LiteralPath $dir -Filter 'console-window-*.bak' -File -Force)
|
||||
if ($copies.Count -ne 1 -or $copies[0].Name -notmatch '^console-window-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\.bak$' -or
|
||||
($copies[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -or $copies[0].Length -gt 32768) {
|
||||
throw 'Expected one original maintenance-window backup.'
|
||||
}
|
||||
$backup = $copies[0].FullName
|
||||
if (Test-Path -LiteralPath ($backup + '.closed')) { throw 'Backup already closed.' }
|
||||
$originalRaw = [IO.File]::ReadAllText($backup)
|
||||
$original = $originalRaw | ConvertFrom-Json
|
||||
if ([DateTimeOffset]::Parse($original.expires_at) -ne $PreviousExpiry) { throw 'Backup expiry differs.' }
|
||||
$original.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
||||
if (($original | ConvertTo-Json -Compress) -cne $raw) { throw 'Backup does not reconstruct the current public configuration.' }
|
||||
}
|
||||
$candidate = $backup + '.new'
|
||||
$sshArgs = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
|
||||
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
|
||||
'-o',('UserKnownHostsFile=' + $dir + '\known_hosts'),'-o','ExitOnForwardFailure=yes',
|
||||
'-o','ConnectTimeout=10','-o','ServerAliveInterval=15','-o','ServerAliveCountMax=2',
|
||||
'-i',($dir + '\tunnel_ed25519'),'-R','127.0.0.1:22240:127.0.0.1:22222',
|
||||
'rmm-win-tunnel@discovery.ease-technologies.de')
|
||||
$ssh = $null
|
||||
$disabled = $false
|
||||
$accountChanged = $false
|
||||
try {
|
||||
if (!$ResumeInterrupted) {
|
||||
$cfg.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
||||
[IO.File]::WriteAllText($candidate, ($cfg | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
||||
Disable-ScheduledTask -InputObject $task | Out-Null
|
||||
$disabled = $true
|
||||
}
|
||||
if ((Get-ScheduledTask -TaskPath '\' -TaskName $task.TaskName).State -ne 'Disabled' -or
|
||||
[IO.File]::ReadAllText($configPath) -cne $raw) { throw 'Existing bootstrap changed.' }
|
||||
if ($ResumeInterrupted) {
|
||||
$disabled = $true
|
||||
} else {
|
||||
[IO.File]::Replace($candidate, $configPath, $backup)
|
||||
Set-LocalUser -SID $user.SID -AccountExpires $Until.LocalDateTime
|
||||
}
|
||||
$accountChanged = $true
|
||||
if ((Get-LocalUser -SID $user.SID).AccountExpires.ToUniversalTime() -ne $Until.UtcDateTime) {
|
||||
throw 'Unexpected account expiry after renewal.'
|
||||
}
|
||||
$ssh = Start-Process -FilePath "$env:WINDIR\System32\OpenSSH\ssh.exe" -ArgumentList $sshArgs -PassThru -NoNewWindow
|
||||
if ($ssh.WaitForExit(1500)) { throw "SSH exited with code $($ssh.ExitCode)." }
|
||||
Write-Host "Tunnelfenster gestartet bis $($Until.LocalDateTime). Zum Beenden Strg+C druecken."
|
||||
while ([DateTimeOffset]::UtcNow -lt $Until) {
|
||||
if ($ssh.WaitForExit(500)) { throw "SSH exited with code $($ssh.ExitCode)." }
|
||||
}
|
||||
} finally {
|
||||
if ($null -ne $ssh) {
|
||||
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
|
||||
}
|
||||
if ($accountChanged) { Set-LocalUser -SID $user.SID -AccountExpires $PreviousExpiry.LocalDateTime }
|
||||
if ($disabled -and (Test-Path -LiteralPath $backup)) { [IO.File]::Replace($backup, $configPath, ($backup + '.closed')) }
|
||||
if ($disabled -and [IO.File]::ReadAllText($configPath) -ceq $originalRaw) { Enable-ScheduledTask -InputObject $task | Out-Null }
|
||||
if (!$ResumeInterrupted -and (Test-Path -LiteralPath $candidate)) { Remove-Item -LiteralPath $candidate }
|
||||
}
|
||||
@@ -230,9 +230,3 @@ Use those same arguments with `-Mode Build -ExpectedPreflight <actual-receipt>`.
|
||||
Populate the isolated public Cargo cache explicitly before an offline build;
|
||||
there is no automatic fetch/retry in the builder. Native setup, native MIDL/ABI,
|
||||
unit execution and deployment results are still outstanding until actually run.
|
||||
|
||||
On November 15, 2026 a read-only check on the running Windows test VM found
|
||||
both CBS and Windows Update restart markers, 96 GiB free on C:, no vswhere
|
||||
at its standard installer path, and no rustc on the development user's PATH.
|
||||
No installer was launched. This check does not determine why the markers are
|
||||
present. Receipt `04a56e7d8a8bf00a110558344248fbb0ca0c2234c5c1ea6e347306bcc84d5c55`.
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read two public service observations; never request time or alter the guest."""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import system_pipe_upgrade as access_bridge
|
||||
import time_route_context as context_reader
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
|
||||
STATE = ROOT / 'devstate/windows-passive-time-closeout'
|
||||
FIELDS = {'schema_version', 'agent_pid', 'observed_at', 'role', 'windows_boot_id',
|
||||
'connection_generation', 'verifier_incarnation', 'request_sha256', 'response_sha256'}
|
||||
FILES = {'agent': 'agent-time-sample.json', 'system_helper': 'helper-time-sample.json'}
|
||||
HEX = re.compile(r'[0-9a-f]{64}')
|
||||
SECOND_NS = 1_000_000_000
|
||||
|
||||
# No report is requested from a service. The only content reads on the guest
|
||||
# are these two public JSONs and public executable hashes. CIM/process queries
|
||||
# obtain current boot/SCM/image/birth metadata without starting another binary.
|
||||
SCRIPT = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
|
||||
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
|
||||
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
|
||||
function Check($path,[bool]$directory){
|
||||
$i=Get-Item -LiteralPath $path -Force
|
||||
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
|
||||
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
|
||||
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
||||
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
|
||||
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
|
||||
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
|
||||
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
|
||||
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
|
||||
}
|
||||
Add-Type -TypeDefinition @'
|
||||
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
|
||||
public static class RmmPassiveTimeRead {
|
||||
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
|
||||
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
||||
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
|
||||
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
||||
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
|
||||
}
|
||||
'@
|
||||
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function Runtime($role){
|
||||
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
|
||||
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
|
||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
|
||||
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
|
||||
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
|
||||
if($s.PathName-cne$expected){throw 'Current fixed service command'}
|
||||
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
|
||||
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
|
||||
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
|
||||
}
|
||||
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
|
||||
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
|
||||
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
|
||||
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
|
||||
$path=Join-Path $state $name
|
||||
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
|
||||
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
||||
try{
|
||||
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
|
||||
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
|
||||
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
|
||||
$after=New-Object RmmPassiveTimeRead+Info
|
||||
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
|
||||
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
|
||||
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
|
||||
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
|
||||
}finally{$stream.Dispose()}
|
||||
}
|
||||
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
|
||||
$directoryAfter=Check $state $true
|
||||
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
|
||||
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def need(value, tag):
|
||||
if not value:
|
||||
raise ValueError(tag)
|
||||
|
||||
|
||||
def strict(pairs):
|
||||
value = {}
|
||||
for key, item in pairs:
|
||||
need(key not in value, 'DUPLICATE_PUBLIC_FIELD')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def stamp(value):
|
||||
need(type(value) is str, 'UTC_TIMESTAMP_REQUIRED')
|
||||
match = re.fullmatch(r'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z', value)
|
||||
need(match is not None, 'UTC_TIMESTAMP_REQUIRED')
|
||||
base = dt.datetime.strptime(match[1], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=dt.timezone.utc)
|
||||
elapsed = base - dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
|
||||
return (elapsed.days * 86400 + elapsed.seconds) * SECOND_NS + int((match[2] or '').ljust(9, '0'))
|
||||
|
||||
|
||||
def utc_ns(value):
|
||||
return stamp(value.astimezone(dt.timezone.utc).isoformat().replace('+00:00', 'Z'))
|
||||
|
||||
|
||||
def canonical_uuid(value):
|
||||
need(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int > 0, 'UUID_REQUIRED')
|
||||
return value
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def save(folder, name, value):
|
||||
fd = os.open(folder / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def windows_boot(ticks):
|
||||
need(type(ticks) is str and ticks.isascii() and ticks.isdigit() and 17 <= len(ticks) <= 19, 'BOOT_TICKS')
|
||||
raw = bytearray(hashlib.sha256(('rmm.windows.boot.cim.ticks.v1:' + ticks).encode()).digest()[:16])
|
||||
raw[6] = (raw[6] & 15) | 0x80
|
||||
raw[8] = (raw[8] & 63) | 0x80
|
||||
return str(uuid.UUID(bytes=bytes(raw)))
|
||||
|
||||
|
||||
def filetime(value):
|
||||
need(type(value) is str and value.isascii() and value.isdigit(), 'FILETIME_REQUIRED')
|
||||
return (int(value) - 116444736000000000) * 100
|
||||
|
||||
|
||||
def validate(native, server, since, observed_now):
|
||||
need(native['read_only'] is True and server['sql_read_only'] is True and server['secrets_read'] is False, 'READ_ONLY_WITNESSES')
|
||||
current = server['installation']
|
||||
caps = current['capabilities']
|
||||
need(type(caps) is list and len(caps) == 3 and set(caps) == {'windows.base/1', 'heartbeat/1', 'agent.update/1'}, 'PASSIVE_SERVER_CAPABILITIES')
|
||||
boot = windows_boot(native['boot_ticks'])
|
||||
need(current['windows_boot_id'] == boot, 'CURRENT_SERVER_WINDOWS_BOOT')
|
||||
generation = current['connection_generation']
|
||||
need(type(generation) is int and generation > 0, 'CURRENT_POSITIVE_GENERATION')
|
||||
now = stamp(native['observed_at'])
|
||||
need(abs(now - utc_ns(observed_now)) <= 10 * SECOND_NS, 'CURRENT_WINDOWS_UTC')
|
||||
records = []
|
||||
for role, filename in FILES.items():
|
||||
wrapped = native['reports'][filename]
|
||||
need(wrapped is not None, 'PUBLIC_SERVICE_SAMPLE_MISSING')
|
||||
raw = base64.b64decode(wrapped['raw_base64'], validate=True)
|
||||
need(len(raw) <= 8192 and hashlib.sha256(raw).hexdigest() == wrapped['sha256'], 'PUBLIC_SAMPLE_RAW_HASH')
|
||||
record = json.loads(raw, object_pairs_hook=strict)
|
||||
need(set(record) == FIELDS and type(record['schema_version']) is int and record['schema_version'] == 1, 'PUBLIC_SAMPLE_SCHEMA')
|
||||
need(record['role'] == role and type(record['agent_pid']) is int and record['agent_pid'] == native['runtime']['agent']['pid'], 'SAMPLE_PROCESS_ROLE')
|
||||
need(record['windows_boot_id'] == boot and type(record['connection_generation']) is int and record['connection_generation'] == generation, 'SAMPLE_BOOT_GENERATION')
|
||||
canonical_uuid(record['verifier_incarnation'])
|
||||
for field in ('request_sha256', 'response_sha256'):
|
||||
need(type(record[field]) is str and HEX.fullmatch(record[field]) is not None, 'SAMPLE_HASH_FORMAT')
|
||||
observed = stamp(record['observed_at'])
|
||||
modified = filetime(wrapped['metadata']['last_write_filetime'])
|
||||
birth = filetime(native['runtime']['agent']['birth_filetime'])
|
||||
need(since <= observed <= now + 2 * SECOND_NS and birth <= observed, 'SAMPLE_CURRENT_INSTALL_WINDOW')
|
||||
need(0 <= now - modified <= 180 * SECOND_NS and 0 <= now - observed <= 180 * SECOND_NS, 'SAMPLE_FILE_AGE')
|
||||
need(-2 * SECOND_NS <= modified - observed <= 90 * SECOND_NS, 'SAMPLE_PUBLICATION_DELAY')
|
||||
need(wrapped['metadata']['dacl_checked'] is True, 'SAMPLE_PROTECTED_METADATA')
|
||||
records.append(record)
|
||||
for field in ('verifier_incarnation', 'request_sha256', 'response_sha256'):
|
||||
need(records[0][field] != records[1][field], 'INDEPENDENT_ROLE_' + field.upper())
|
||||
return records
|
||||
|
||||
|
||||
def collect(args):
|
||||
need(HEX.fullmatch(args.agent_sha256) and HEX.fullmatch(args.helper_sha256), 'QUALIFIED_RUNTIME_HASHES_REQUIRED')
|
||||
since = stamp(args.profile_after)
|
||||
need(0 <= utc_ns(dt.datetime.now(dt.timezone.utc)) - since <= 600 * SECOND_NS, 'RECENT_PROFILE_INSTALL_WINDOW')
|
||||
STATE.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
ident = str(uuid.uuid4())
|
||||
folder = STATE / ident
|
||||
folder.mkdir(mode=0o700)
|
||||
save(folder, 'intent.json', dict(id=ident, operator_sha256=sha(__file__), source_commit='cc821246ccd98ee6d3dc5c1b12c7303d3010e8a7',
|
||||
read_only=True, agent_sha256=args.agent_sha256, helper_sha256=args.helper_sha256, profile_after=args.profile_after,
|
||||
wait_seconds=180, in_progress_read_budget_seconds=105, sample_max_age_seconds=180, no_requests_to_services=True))
|
||||
access_bridge.STATE.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
access = access_bridge.Access(ACCESS_ROOT)
|
||||
deadline = time.monotonic() + 180
|
||||
attempt = 0
|
||||
last = 'PUBLIC_SERVICE_SAMPLE_MISSING'
|
||||
while time.monotonic() < deadline:
|
||||
attempt += 1
|
||||
before = context_reader.rpc(access, dict(id=ident, deployment_result_sha256=context_reader.DEPLOYMENT_RESULT_SHA, image=context_reader.IMAGE), folder)
|
||||
native = access.powershell(SCRIPT, dict(id=ident, agent_sha256=args.agent_sha256, helper_sha256=args.helper_sha256), timeout=45)
|
||||
save(folder, f'{attempt:02d}-native.json', native) # persist before assertions
|
||||
after = context_reader.rpc(access, dict(id=ident, deployment_result_sha256=context_reader.DEPLOYMENT_RESULT_SHA, image=context_reader.IMAGE), folder)
|
||||
save(folder, f'{attempt:02d}-server.json', dict(before=before, after=after))
|
||||
try:
|
||||
need(before == after, 'SERVER_CONTEXT_CHANGED_DURING_READ')
|
||||
records = validate(native, after, since, dt.datetime.now(dt.timezone.utc))
|
||||
except ValueError as error:
|
||||
last = str(error)
|
||||
save(folder, f'{attempt:02d}-not-accepted.json', dict(reason=last, read_only=True))
|
||||
if last not in ('PUBLIC_SERVICE_SAMPLE_MISSING', 'SAMPLE_BOOT_GENERATION', 'SAMPLE_PROCESS_ROLE', 'SAMPLE_CURRENT_INSTALL_WINDOW', 'SAMPLE_FILE_AGE', 'SERVER_CONTEXT_CHANGED_DURING_READ'):
|
||||
raise
|
||||
time.sleep(min(5, max(0, deadline-time.monotonic())))
|
||||
continue
|
||||
links = {name: sha(folder/name) for name in ('intent.json', f'{attempt:02d}-native.json', f'{attempt:02d}-server.json')}
|
||||
save(folder, 'receipt.json', dict(id=ident, operator_sha256=sha(__file__), verified=True, read_only=True,
|
||||
historical_role_samples_only=True, current_job_clock_proven=False, records=records, links=links))
|
||||
print(json.dumps(dict(id=ident, verified=True, read_only=True, receipt_sha256=sha(folder/'receipt.json'))))
|
||||
return
|
||||
save(folder, 'incomplete.json', dict(id=ident, verified=False, read_only=True, reason=last, no_diagnostic_triggered=True))
|
||||
print(json.dumps(dict(id=ident, verified=False, reason=last, read_only=True)))
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def guards():
|
||||
forbidden = ('Start-Service', 'Stop-Service', 'Restart-Service', 'Remove-Item', 'WriteAll', 'WriteNew', 'TimeBegin', 'TimeComplete', '--native-probe', 'Snapshot', 'Execute')
|
||||
need(all(item not in SCRIPT for item in forbidden), 'READ_ONLY_SOURCE_ONLY')
|
||||
need(all(name in SCRIPT for name in FILES.values()), 'TWO_FIXED_REPORT_NAMES')
|
||||
print('PASS local source guards; no target call')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('guards', 'collect'))
|
||||
parser.add_argument('--agent-sha256')
|
||||
parser.add_argument('--helper-sha256')
|
||||
parser.add_argument('--profile-after')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'guards':
|
||||
guards()
|
||||
else:
|
||||
need(all((args.agent_sha256, args.helper_sha256, args.profile_after)), 'ROOT_ACTUAL_PROFILE_AND_RUNTIME_REQUIRED')
|
||||
guards()
|
||||
collect(args)
|
||||
@@ -1,16 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare the preserving passive Windows pair with fixed actual route evidence.
|
||||
"""Local-only preparation of a new preserving passive Windows code-pair controller.
|
||||
|
||||
Preparation reads only the public expires_at from the current protected access
|
||||
configuration. Before effects the guest must match that same expiration in its
|
||||
existing account and bootstrap-public configuration, with a full first-stop
|
||||
budget and a smaller remaining budget at the second stop. No account/tunnel
|
||||
change, RMM job, reboot or clock configuration is performed by this generator.
|
||||
No SSH, staging or target action is exposed here. The generated controller's
|
||||
enter phase remains closed until a separate reviewed source generation binds
|
||||
actual server source/broker/public-time-key/mTLS-route qualification. Original
|
||||
14fb evidence and Main indices are read-only; no time pins or calibration exist
|
||||
in this package. Source review and native PS AST/C# compile remain separate.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import re
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -32,16 +30,11 @@ RUNTIME_INDEX = 'e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c
|
||||
COMPONENT_INDEX = '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562'
|
||||
ORIGINAL_RESULT = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed'
|
||||
ORIGINAL_INTENT = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2'
|
||||
HELPER_CANDIDATE = ROOT / 'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8'
|
||||
HELPER_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
||||
HELPER_QUALIFICATION = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d'
|
||||
CANDIDATE = MAIN / 'devstate/windows-client/operator-window-20261115/observed-agent-build'
|
||||
# Closed until Root supplies the actual completed native qualification receipt.
|
||||
CANDIDATE_RECEIPT = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||
QUALIFICATION = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||
SOURCE_INPUTS = '11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4'
|
||||
NEW_AGENT = '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'
|
||||
NEW_HELPER = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
|
||||
CANDIDATE = ROOT / 'devstate/windows-signed-clock/freshness-candidate-link-917425d6-412b-4f70-a7db-bc02de6b9b2a'
|
||||
CANDIDATE_RECEIPT = '2abf7fe56633e68864469de2ff9ded21888301bdc737e53211d024cfd044e22e'
|
||||
QUALIFICATION = '6a624ee9b795ce67d80a91536ba242835be9757a2f502d2d9fbc545532e1b560'
|
||||
NEW_AGENT = '751657ee873c4f4d013abc4ea6daaa4641fea2fe55838fb1c701e6a71b57c192'
|
||||
NEW_HELPER = 'acf1e3f3b1609a97e0d5e88a43a421bed530a09a236bfc0dec1b1abbb22d4413'
|
||||
PROBE = '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac'
|
||||
SYSTEM_PROBE = '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434'
|
||||
require = prior.require
|
||||
@@ -68,35 +61,13 @@ def controller():
|
||||
marker = "foreach($field in @('old_agent'"
|
||||
index = prefix.index(marker)
|
||||
prefix = prefix[:index] + ("# No caller flag or staged file can replace missing server qualification.\n"
|
||||
"# Enter effects require the fixed actual protocol/exit proof below.\n"
|
||||
"if($p.action-ceq'enter'){throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'}\n"
|
||||
"if($p.new_agent-cne'"+NEW_AGENT+"'-or$p.new_helper-cne'"+NEW_HELPER+
|
||||
"'){throw 'Fixed signed-clock freshness candidate pair'}\n") + prefix[index:]
|
||||
# Require explicit absence; this bootstrap never creates or adopts a
|
||||
# calibration/public-time-pin file or changes the six-field passive config.
|
||||
marker = 'function State([bool]$new){\n'
|
||||
prefix = replace_once(prefix, marker, marker + " if(Test-Path -LiteralPath (Join-Path $helperRoot 'time-attestation.json')){throw 'Separate time-pin provisioning required; passive bootstrap does not adopt it'}\n")
|
||||
# Compare JSON objects by their contents; serialized member order is not
|
||||
# identity. Arrays retain exact order and empty/null values stay distinct.
|
||||
prefix = replace_once(prefix,
|
||||
"function JsonEqual($a,$b){return(($a|ConvertTo-Json -Depth 40 -Compress)-ceq($b|ConvertTo-Json -Depth 40 -Compress))}",
|
||||
r'''function CanonicalStateValue($value,[int]$depth=0){
|
||||
if($depth-gt40){throw 'Bounded state comparison depth'}
|
||||
if($null-eq$value){return $null}
|
||||
# ETS wrapping does not turn a CLR JSON scalar into a JSON object.
|
||||
$base=$value.PSObject.BaseObject;$culture=[Globalization.CultureInfo]::InvariantCulture
|
||||
if($base-is[string]){return [string]::new($base.ToCharArray())}
|
||||
if($base-is[char]){return [string]::new([char[]]@($base))}
|
||||
if($base-is[bool]){return [bool]::Parse($base.ToString())}
|
||||
if($base-is[sbyte]-or$base-is[int16]-or$base-is[int32]-or$base-is[int64]){return [int64]::Parse($base.ToString($culture),$culture)}
|
||||
if($base-is[byte]-or$base-is[uint16]-or$base-is[uint32]-or$base-is[uint64]){return [uint64]::Parse($base.ToString($culture),$culture)}
|
||||
if($base-is[single]-or$base-is[double]){$number=[double]::Parse($base.ToString('R',$culture),$culture);if([double]::IsNaN($number)-or[double]::IsInfinity($number)){throw 'Finite JSON state number required'};return $number}
|
||||
if($base-is[decimal]){return [decimal]::Parse($base.ToString($culture),$culture)}
|
||||
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
||||
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
||||
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
||||
return $value
|
||||
}
|
||||
function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateValue $a) -Depth 40 -Compress)-ceq(ConvertTo-Json -InputObject (CanonicalStateValue $b) -Depth 40 -Compress))}''')
|
||||
native = prior.NATIVE.replace('RmmPipeNative', 'RmmSignedClockPairNative')
|
||||
phases = prior.PHASES.replace('SystemPipeUpgrade.ps1', 'SignedClockPairUpgrade.ps1').replace('RmmPipeNative', 'RmmSignedClockPairNative')
|
||||
# No implicit fallthrough may become an effect, even if a future caller
|
||||
@@ -104,35 +75,36 @@ function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateVal
|
||||
boundary = "if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}"
|
||||
phases = replace_once(phases, boundary,
|
||||
"if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\n"
|
||||
"RequireQualifiedTimeRoute\nRequireAccessBudget 420\n" + boundary)
|
||||
phases = phases.replace(" $live=Service $role;", " if($role-ceq'agent'){RequireAccessBudget 420}else{RequireAccessBudget 300}\n $live=Service $role;", 1)
|
||||
route_gate = r'''function RequireAccessBudget([int]$minimumSeconds=420){
|
||||
if($p.access_expiry_utc-isnot[string]-or$p.access_expiry_utc-cnotmatch'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?Z$'){throw 'Exact protected access expiry'}
|
||||
$limit=[DateTimeOffset]::Parse($p.access_expiry_utc,[Globalization.CultureInfo]::InvariantCulture).UtcDateTime;$actual=(Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime()
|
||||
$configPath='C:\ProgramData\RmmDevAccess\bootstrap-public.json';CheckControl $configPath $false;if((Get-Item -LiteralPath $configPath).Length-gt32768){throw 'Bounded public access config'}
|
||||
$public=Get-Content -LiteralPath $configPath -Raw|ConvertFrom-Json;$configured=[DateTimeOffset]::Parse($public.expires_at,[Globalization.CultureInfo]::InvariantCulture).UtcDateTime
|
||||
if($actual-ne$limit-or$configured-ne$limit-or($limit-[DateTime]::UtcNow).TotalSeconds-lt$minimumSeconds){throw 'Insufficient or mismatched actual SSH access budget before service stop'}
|
||||
}
|
||||
function RequireQualifiedTimeRoute{
|
||||
$route='C:\ProgramData\RustDiscoveryBootstrap\time-route\68b841a5-784f-4a34-a8a4-060b267713f0';$control='C:\ProgramData\RustDiscoveryBootstrap\time-route-control\68b841a5-784f-4a34-a8a4-060b267713f0'
|
||||
CheckControl $route $true;CheckControl $control $true
|
||||
foreach($entry in @(@((Join-Path $route 'TimeRouteProbe.exe'),'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'),@((Join-Path $route 'report.json'),'9f1635c19c801f95c9828e9e31071a487b430f105a61977ee2d60f076f3d3623'),@((Join-Path $control 'exit.json'),'6d131d2796936913f53286573e56f7fb3e515d04ebbd55ae9d6794440e6053b5'),@((Join-Path $route 'context.json'),'3c0e4ff3b16b86fb4e98d2ff163686305ea533570c40ae3bef1270ab89648ed3'),@((Join-Path $route 'time-public-key.json'),'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'))){CheckControl $entry[0] $false;if((Hash $entry[0])-cne$entry[1]){throw 'Actual passive route and kernel-exit proof changed'}}
|
||||
$report=Get-Content -LiteralPath (Join-Path $route 'report.json') -Raw|ConvertFrom-Json;$exit=Get-Content -LiteralPath (Join-Path $control 'exit.json') -Raw|ConvertFrom-Json
|
||||
if($report.case_id-cne'68b841a5-784f-4a34-a8a4-060b267713f0'-or$report.verified-ne$true-or$report.service_role_proven-ne$false-or$report.trusted_clock_proven-ne$false-or($report.reports.http_status-join',')-cne'200,403,409'-or$report.reports[0].signature_verified-ne$true-or$report.reports[0].whole_request_context_bound-ne$true-or$exit.kernel_process_exited-ne$true-or$exit.exit_code-ne0-or$exit.timed_out-ne$false){throw 'Fixed actual passive protocol proof only'}
|
||||
}
|
||||
'''
|
||||
phases = route_gate+phases
|
||||
"throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'\n" + boundary)
|
||||
# Only the existing fixed passive journal witnesses and authenticated Probe
|
||||
# are used. No helper Snapshot/Apply/Execute or time control operation.
|
||||
return prefix+'\n'+native+prior.READBACK_SERVICE+'\n'+phases
|
||||
|
||||
|
||||
def source_guards(script):
|
||||
require("$p.action-isnot[string]-or$p.action-cnotin@('baseline','enter','finish','readback')" in script and "$p.action-notin@" not in script,'exact case sensitive actions')
|
||||
require("if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\nRequireQualifiedTimeRoute\nRequireAccessBudget 420\n" in script,'actual route and access bound before effects')
|
||||
require(" if($role-ceq'agent'){RequireAccessBudget 420}else{RequireAccessBudget 300}\n $live=Service $role;" in script,'access budget before each actual stop')
|
||||
require('9f1635c19c801f95c9828e9e31071a487b430f105a61977ee2d60f076f3d3623' in script and '6d131d2796936913f53286573e56f7fb3e515d04ebbd55ae9d6794440e6053b5' in script,'actual route report and exit binding')
|
||||
require('TimeBegin' not in script and 'TimeComplete' not in script and 'Restart-Computer' not in script,'no clock/job/reboot scope')
|
||||
require("if($p.action-ceq'enter'){throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'}" in script,
|
||||
'target effects closed pending actual independently reviewed server evidence')
|
||||
require("$p.action-isnot[string]-or$p.action-cnotin@('baseline','enter','finish','readback')" in script
|
||||
and "$p.action-notin@" not in script, 'strict string and case-sensitive action whitelist')
|
||||
boundary = ("if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\n"
|
||||
"throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'\n"
|
||||
"if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active))")
|
||||
require(script.count(boundary) == 1 and script.index(boundary) < script.index(" StopHeld 'agent'"),
|
||||
'explicit exact enter and unconditional qualification gate before all effect flow')
|
||||
require('RmmPipeNative' not in script and 'RmmPipeUpgradePayload' not in script,
|
||||
'only the new controller class and payload identifiers')
|
||||
require(script.count('Start-Service -Name $name') == script.count('Stop-Service -Name $name') == 1,
|
||||
'one fixed-role service-control primitive only')
|
||||
positions = [script.index(x) for x in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'",
|
||||
" Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
|
||||
require(positions == sorted(positions), 'backups then all four CAS replacements then helper/agent starts')
|
||||
require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in script,
|
||||
'explicit native original backup, no null backup')
|
||||
require(all(x not in script for x in ('Restart-Service', 'Restart-Computer', 'Stop-Computer',
|
||||
'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass',
|
||||
'TimeBegin', 'TimeComplete', 'TimeClose', 'ExecutionPolicy Bypass')), 'no extra effect or time-control scope')
|
||||
require('function Snapshot' not in script and 'function Apply' not in script,
|
||||
'no clock-dependent helper synchronization in passive witness')
|
||||
|
||||
|
||||
def protected(path, expected):
|
||||
@@ -183,30 +155,16 @@ def write(path, raw):
|
||||
|
||||
|
||||
def prepare(script):
|
||||
require(type(CANDIDATE_RECEIPT) is str and len(CANDIDATE_RECEIPT)==64 and QUALIFICATION==CANDIDATE_RECEIPT,'actual final native agent qualification receipt not yet bound')
|
||||
result, old_intent, settings, pin, policy = original()
|
||||
grant = prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||
expiry = grant.get('expires_at')
|
||||
require(type(expiry) is str and re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?(?:Z|\+00:00)',expiry) is not None,'protected current access expiry')
|
||||
expiry = expiry.removesuffix('+00:00')+'Z' if expiry.endswith('+00:00') else expiry
|
||||
deadline = dt.datetime.fromisoformat(expiry.replace('Z','+00:00'))
|
||||
require((deadline-dt.datetime.now(dt.timezone.utc)).total_seconds() >= 420,'current authorization window has insufficient total maintenance/readback budget')
|
||||
receipt = protected(CANDIDATE/'receipt.json', CANDIDATE_RECEIPT)
|
||||
helper_receipt = protected(HELPER_CANDIDATE/'receipt.json', HELPER_RECEIPT)
|
||||
require(receipt['source_inputs_sha256']==SOURCE_INPUTS and receipt['source_verified_before_after'] is True
|
||||
and receipt['link_exit']==0 and receipt['original_helper_sha256']==NEW_HELPER
|
||||
and receipt['artifacts']['rmm-agent-windows.exe']['sha256']==NEW_AGENT,
|
||||
'actual final source-verified locally linked and natively qualified passive agent')
|
||||
require(helper_receipt['source_receipt_sha256']==HELPER_QUALIFICATION and helper_receipt['link_exit']==0
|
||||
and helper_receipt['artifacts']['rmm-helper-windows.exe']['sha256']==NEW_HELPER,
|
||||
'unchanged independently linked original helper')
|
||||
artifact_sources={'rmm-agent-windows.exe':CANDIDATE/'rmm-agent-windows.exe',
|
||||
'rmm-helper-windows.exe':HELPER_CANDIDATE/'rmm-helper-windows.exe'}
|
||||
artifacts={'rmm-agent-windows.exe':receipt['artifacts']['rmm-agent-windows.exe'],
|
||||
'rmm-helper-windows.exe':helper_receipt['artifacts']['rmm-helper-windows.exe']}
|
||||
require(receipt['source_receipt_sha256'] == QUALIFICATION and receipt['input_count'] == 202
|
||||
and receipt['link_exit'] == 0 and receipt['target_execution'] is False
|
||||
and receipt['artifacts']['rmm-agent-windows.exe']['sha256'] == NEW_AGENT
|
||||
and receipt['artifacts']['rmm-helper-windows.exe']['sha256'] == NEW_HELPER,
|
||||
'actual new offline-linked freshness pair, no native qualification inferred')
|
||||
ident = str(uuid.uuid4()); folder = STATE/ident; folder.mkdir(mode=0o700,parents=True)
|
||||
script_sha = raw_sha(script.encode())
|
||||
draft = dict(id=ident,access_expiry_utc=expiry,old_agent=OLD_AGENT,old_helper=OLD_HELPER,old_policy=OLD_POLICY,old_pin=OLD_PIN,
|
||||
draft = dict(id=ident,old_agent=OLD_AGENT,old_helper=OLD_HELPER,old_policy=OLD_POLICY,old_pin=OLD_PIN,
|
||||
new_agent=NEW_AGENT,new_helper=NEW_HELPER,new_policy=policy,new_pin=raw_sha(pin),
|
||||
config_sha256=result['native']['config_sha256'],probe_sha256=PROBE,system_probe_sha256=SYSTEM_PROBE,
|
||||
manifest_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION,script_sha256=script_sha,
|
||||
@@ -218,7 +176,7 @@ def prepare(script):
|
||||
for name,raw in items.items():
|
||||
write(folder/name,raw);files[name]=dict(bytes=len(raw),sha256=raw_sha(raw))
|
||||
for name,expected in [('rmm-agent-windows.exe',NEW_AGENT),('rmm-helper-windows.exe',NEW_HELPER)]:
|
||||
source=artifact_sources[name];metadata=source.lstat()
|
||||
source=CANDIDATE/name;metadata=source.lstat()
|
||||
require(metadata.st_nlink == 1 and metadata.st_mode&0o777 == 0o500 and sha(source) == expected,
|
||||
'exact private linked candidate artifact')
|
||||
dependencies=prior.dependencies();dependencies[str(Path(prior.__file__).relative_to(ROOT))]=PRIOR_SOURCE
|
||||
@@ -227,15 +185,14 @@ def prepare(script):
|
||||
original_case=OLD_CASE,original_result_sha256=ORIGINAL_RESULT,original_intent_sha256=ORIGINAL_INTENT,
|
||||
original_runtime_index_sha256=RUNTIME_INDEX,original_component_index_sha256=COMPONENT_INDEX,
|
||||
candidate_receipt_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION,
|
||||
artifacts=artifacts,helper_receipt_sha256=HELPER_RECEIPT,helper_qualification_sha256=HELPER_QUALIFICATION,source_inputs_sha256=SOURCE_INPUTS,
|
||||
linux_result_sha256=receipt['linux_result_sha256'],windows_result_sha256=receipt['windows_result_sha256'],
|
||||
access_expiry_utc=expiry,access_expiry_source='protected current windows-dev-access.json public expires_at; exact VM account/bootstrap-public match before effects',
|
||||
server_qualification_bound=True,enter_enabled=True,time_configuration_created=False,
|
||||
artifacts={name:receipt['artifacts'][name] for name in ('rmm-agent-windows.exe','rmm-helper-windows.exe')},
|
||||
server_qualification_bound=False,enter_enabled=False,time_configuration_created=False,
|
||||
calibration_created=False,target_called=False,main_indices_modified=False,
|
||||
remaining=['fresh current authorized SSH window and exact VM account/public expiry match',
|
||||
'fresh native baseline and closed server witnesses','once-only preserving maintenance and independent readback'])
|
||||
remaining=['independent source review','native PS AST/C# compile-only',
|
||||
'actual server quality/broker/public-time-key/mTLS-route gate binding in separately reviewed source',
|
||||
'fresh native baseline and closed server witnesses','new once-only stage/enter/read operator'])
|
||||
write(folder/'manifest.json',canonical(manifest));print(json.dumps(dict(id=ident,prepared_locally=True,
|
||||
controller_sha256=script_sha,enter_enabled=True,target_called=False)))
|
||||
controller_sha256=script_sha,enter_enabled=False,target_called=False)))
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
"""Local public-record binding fixtures; no SSH, file staging or clock query."""
|
||||
import base64
|
||||
import copy
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import unittest
|
||||
import passive_time_closeout as c
|
||||
|
||||
class Binding(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.now = dt.datetime(2026,11,15,14,0,tzinfo=dt.timezone.utc)
|
||||
self.since = c.utc_ns(self.now - dt.timedelta(seconds=50))
|
||||
ticks='638987472000000000'
|
||||
boot=c.windows_boot(ticks)
|
||||
epoch=dt.datetime(1601,1,1,tzinfo=dt.timezone.utc)
|
||||
ft=lambda value:str(int((value-epoch).total_seconds())*10000000)
|
||||
self.native=dict(read_only=True,boot_ticks=ticks,observed_at=self.now.isoformat().replace('+00:00','Z'),runtime=dict(agent=dict(pid=1234,birth_filetime=ft(self.now-dt.timedelta(minutes=1)))),reports={})
|
||||
self.server=dict(sql_read_only=True,secrets_read=False,installation=dict(windows_boot_id=boot,connection_generation=10,capabilities=['windows.base/1','heartbeat/1','agent.update/1']))
|
||||
for i,(role,name) in enumerate(c.FILES.items()):
|
||||
record=dict(schema_version=1,agent_pid=1234,observed_at=(self.now-dt.timedelta(seconds=20)).isoformat().replace('+00:00','Z'),role=role,windows_boot_id=boot,connection_generation=10,verifier_incarnation=f'11111111-1111-4111-8111-{i+1:012d}',request_sha256=str(i+1)*64,response_sha256=str(i+3)*64)
|
||||
raw=json.dumps(record).encode()
|
||||
self.native['reports'][name]=dict(raw_base64=base64.b64encode(raw).decode(),sha256=hashlib.sha256(raw).hexdigest(),metadata=dict(last_write_filetime=ft(self.now-dt.timedelta(seconds=2)),dacl_checked=True))
|
||||
def modify(self,name,field,value):
|
||||
wrapped=self.native['reports'][name]
|
||||
record=json.loads(base64.b64decode(wrapped['raw_base64']))
|
||||
record[field]=value
|
||||
raw=json.dumps(record).encode()
|
||||
wrapped.update(raw_base64=base64.b64encode(raw).decode(),sha256=hashlib.sha256(raw).hexdigest())
|
||||
def test_current_independent_pair(self):
|
||||
self.assertEqual(len(c.validate(self.native,self.server,self.since,self.now)),2)
|
||||
def test_pid_boot_generation_and_expired_sample_are_denied(self):
|
||||
good=copy.deepcopy(self.native)
|
||||
for field,value in [('agent_pid',1233),('windows_boot_id','11111111-1111-4111-8111-111111111111'),('connection_generation',9),('observed_at','2026-11-15T13:00:00Z'),('role','system_helper')]:
|
||||
self.native=copy.deepcopy(good);self.modify('agent-time-sample.json',field,value)
|
||||
with self.assertRaises(ValueError):c.validate(self.native,self.server,self.since,self.now)
|
||||
def test_same_verifier_request_or_response_is_denied(self):
|
||||
good=copy.deepcopy(self.native)
|
||||
first=json.loads(base64.b64decode(good['reports']['agent-time-sample.json']['raw_base64']))
|
||||
for field in ['verifier_incarnation','request_sha256','response_sha256']:
|
||||
self.native=copy.deepcopy(good);self.modify('helper-time-sample.json',field,first[field])
|
||||
with self.assertRaises(ValueError):c.validate(self.native,self.server,self.since,self.now)
|
||||
def test_duplicate_json_field_and_unprotected_metadata_are_denied(self):
|
||||
wrapped=self.native['reports']['agent-time-sample.json'];raw=base64.b64decode(wrapped['raw_base64'])
|
||||
changed=raw[:-1]+b',"schema_version":1}'
|
||||
wrapped.update(raw_base64=base64.b64encode(changed).decode(),sha256=hashlib.sha256(changed).hexdigest())
|
||||
with self.assertRaises(ValueError):c.validate(self.native,self.server,self.since,self.now)
|
||||
self.setUp();self.native['reports']['agent-time-sample.json']['metadata']['dacl_checked']=False
|
||||
with self.assertRaises(ValueError):c.validate(self.native,self.server,self.since,self.now)
|
||||
def test_missing_sample_is_explicit(self):
|
||||
self.native['reports']['helper-time-sample.json']=None
|
||||
with self.assertRaisesRegex(ValueError,'PUBLIC_SERVICE_SAMPLE_MISSING'):c.validate(self.native,self.server,self.since,self.now)
|
||||
def test_native_seven_and_chrono_nine_digits_keep_exact_install_boundary(self):
|
||||
native='2026-11-15T13:59:40.1234567Z'
|
||||
chrono='2026-11-15T13:59:40.123456701Z'
|
||||
self.assertEqual(c.stamp(chrono)-c.stamp(native),1)
|
||||
self.modify('agent-time-sample.json','observed_at',native)
|
||||
self.modify('helper-time-sample.json','observed_at',chrono)
|
||||
since=c.stamp(native)
|
||||
self.assertEqual(len(c.validate(self.native,self.server,since,self.now)),2)
|
||||
with self.assertRaisesRegex(ValueError,'SAMPLE_CURRENT_INSTALL_WINDOW'):
|
||||
c.validate(self.native,self.server,since+1,self.now)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -1,140 +0,0 @@
|
||||
"""Local contract fixtures only; no native qualification or target calls."""
|
||||
import base64
|
||||
import copy
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import time_profile_config as t
|
||||
from vm_mvp_acceptance import GuardError
|
||||
|
||||
|
||||
def fixture():
|
||||
binding = {'tenant_id':'11111111-1111-4111-8111-111111111111',
|
||||
'agent_id':'22222222-2222-4222-8222-222222222222',
|
||||
'asset_id':'33333333-3333-4333-8333-333333333333',
|
||||
'enrollment_generation':1,'assignment_version':1,'public_key_hex':'11'*32}
|
||||
public = {'public-binding.json':binding,'qualified-time-public-key.json':{
|
||||
'key_generation':1,'server_instance':'44444444-4444-4444-8444-444444444444',
|
||||
'key_id':'local_fixture_only','public_key_hex':'22'*32},'public-platform.json':{'fixture_only':True}}
|
||||
agent_sid = 'S-1-5-80-1-2-3-4-5';helper_sid = 'S-1-5-80-1-2-3-4-6'
|
||||
result = {'id':'55555555-5555-4555-8555-555555555555','verified':True,'completed':True,
|
||||
'no_jobs':True,'windows_jobs_enabled':False,'helper_effects_enabled':False,
|
||||
'clock_authority_not_proven':True,'private_key_read':False}
|
||||
native = dict(agent_id=binding['agent_id'],asset_id=binding['asset_id'],
|
||||
binary_sha256=t.IMAGES['agent'],helper_sha256=t.IMAGES['system_helper'],
|
||||
policy_sha256='a'*64,pin_sha256='b'*64,files={})
|
||||
for role, service, kernel, label, user, image in (
|
||||
('agent','service','agent_kernel','agent','S-1-5-19','rmm-agent-windows.exe'),
|
||||
('system_helper','helper_service','helper_kernel','helper','S-1-5-18','rmm-helper-windows.exe')):
|
||||
native[service] = dict(state='Running',pid=42,creation_filetime='123',owner_sid=user)
|
||||
native[kernel] = dict(pid=42,creation_filetime='123',owner_sid=user,service_sid=agent_sid if role=='agent' else helper_sid,
|
||||
kernel_handle_bound=True,service_sid_enabled=True,
|
||||
image='C:\\Program Files\\RustDiscovery\\'+image)
|
||||
native['files'][label] = dict(file_id='a'*32,sha256=t.IMAGES[role])
|
||||
result['native'] = native
|
||||
settings = dict(binding=binding,enable_effects=False,agent=dict(service_sid=agent_sid),helper=dict(service_sid=helper_sid))
|
||||
payload = dict(new_agent=t.IMAGES['agent'],new_helper=t.IMAGES['system_helper'],
|
||||
new_policy='a'*64,new_pin='b'*64,qualification_sha256=t.LINK_RECEIPT,
|
||||
manifest_sha256=t.LINK_RECEIPT,settings_base64=base64.b64encode(t.canonical(settings)).decode())
|
||||
return public,result,payload,{'local-service':{'fixture_only':True},'system':{'fixture_only':True}}
|
||||
|
||||
|
||||
class PublicProfileContract(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.values = fixture()
|
||||
self.pair = patch.object(t,'PAIR_ID',self.values[1]['id']);self.pair.start();self.addCleanup(self.pair.stop)
|
||||
|
||||
def render(self, values=None):
|
||||
return t.produce(*(values or self.values),'c'*64,'d'*64)[0]
|
||||
|
||||
def test_v2_fixture_links_both_exact_roles_without_runtime_success(self):
|
||||
items = self.render();config=json.loads(items['time-attestation.json'])
|
||||
self.assertEqual(config['schema_version'],2)
|
||||
self.assertNotIn('base_error_ns',config)
|
||||
for role in config['trusted_os_active_guest']['qualifications']:
|
||||
raw=items[role['role']+'-qualification.json'];value=json.loads(raw)
|
||||
self.assertEqual(t.sha(raw),role['qualification_sha256'])
|
||||
self.assertFalse(value['signed_runtime_verified']);self.assertFalse(value['physical_calibration_claimed'])
|
||||
self.assertEqual(value['source_sha256'],t.SOURCE_SHA if role['role']=='agent' else t.ORIGINAL_SOURCE_SHA)
|
||||
|
||||
def test_missing_or_not_completed_actual_pair_is_denied(self):
|
||||
for field in ('verified','completed','no_jobs'):
|
||||
values=copy.deepcopy(self.values);values[1].pop(field)
|
||||
with self.assertRaises(GuardError):self.render(values)
|
||||
|
||||
def test_wrong_kernel_birth_account_sid_image_or_fileid_is_denied(self):
|
||||
for field,value in [('creation_filetime','124'),('owner_sid','S-1-5-18'),
|
||||
('service_sid_enabled',False),('kernel_handle_bound',False),
|
||||
('service_sid','S-1-5-18'),('image','C:\\wrong.exe')]:
|
||||
values=copy.deepcopy(self.values);values[1]['native']['agent_kernel'][field]=value
|
||||
with self.assertRaises(GuardError):self.render(values)
|
||||
values=copy.deepcopy(self.values);values[1]['native']['files']['agent']['file_id']='bad'
|
||||
with self.assertRaises(GuardError):self.render(values)
|
||||
|
||||
def test_image_build_policy_and_identity_drift_is_denied(self):
|
||||
for field in ('new_agent','new_helper','new_policy','new_pin','qualification_sha256','manifest_sha256'):
|
||||
values=copy.deepcopy(self.values);values[2][field]='0'*64
|
||||
with self.assertRaises(GuardError):self.render(values)
|
||||
values=copy.deepcopy(self.values);values[0]['public-binding.json']['agent_id']='99999999-9999-4999-8999-999999999999'
|
||||
with self.assertRaises(GuardError):self.render(values)
|
||||
|
||||
def test_no_actual_pair_pins_blocks_before_creating_any_case(self):
|
||||
with tempfile.TemporaryDirectory() as root, patch.object(t,'STATE',Path(root)/'absent'),patch.object(t,'PAIR_ID',None):
|
||||
with self.assertRaises(GuardError):t.prepare()
|
||||
self.assertFalse(t.STATE.exists())
|
||||
|
||||
def test_bounded_nofollow_read_duplicate_json_and_createonce(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
path=Path(root)/'value.json';t.write(path,b'{"a":1}\n')
|
||||
self.assertEqual(t.read(path)[1],{'a':1})
|
||||
with self.assertRaises(FileExistsError):t.write(path,b'{}')
|
||||
with self.assertRaises(GuardError):t.read(path,'0'*64)
|
||||
link=Path(root)/'link';link.symlink_to(path)
|
||||
with self.assertRaises(OSError):t.read(link)
|
||||
bad=Path(root)/'duplicate.json';t.write(bad,b'{"a":1,"a":2}')
|
||||
with self.assertRaises(GuardError):t.read(bad)
|
||||
with self.assertRaises(GuardError):t.read(path,limit=1)
|
||||
|
||||
|
||||
class OriginalPartialDiagnosticContract(unittest.TestCase):
|
||||
def test_closed_reader_cannot_publish_or_repair(self):
|
||||
source=t.partial_reader()
|
||||
self.assertIn('time-profile-'+t.PARTIAL_ID,source)
|
||||
self.assertIn('time-attestation.candidate.json',source)
|
||||
self.assertIn('old_move_hresult_unknown=$true',source)
|
||||
for forbidden in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory'):
|
||||
self.assertNotIn(forbidden,source)
|
||||
|
||||
def test_diagnostic_executes_bound_reader_without_legacy_load_or_target_success(self):
|
||||
import datetime as dt
|
||||
from unittest.mock import Mock
|
||||
manifest={'id':t.PARTIAL_ID,'generator_sha256':t.PARTIAL_GENERATOR_SHA,
|
||||
'script_sha256':t.PARTIAL_SCRIPT_SHA,'request':{'config_sha256':t.PARTIAL_CONFIG_SHA}}
|
||||
result={'id':t.PARTIAL_ID,'read_only':True,'retry_authorized':False,
|
||||
'installation_verified':False,'clock_runtime_qualified':False}
|
||||
access=Mock();access.powershell.return_value=result
|
||||
expiry=(dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=1)).isoformat()
|
||||
with tempfile.TemporaryDirectory() as root,patch.object(t,'ROOT',Path(root)), \
|
||||
patch.object(t,'read',side_effect=[(b'original',manifest),(b'staged',None)]), \
|
||||
patch.object(t,'load_case',side_effect=AssertionError('original case must not adopt new generator')), \
|
||||
patch.object(t.raw_capture,'CaptureAccess',return_value=access), \
|
||||
patch.object(t.prior.cb.contract,'protected_json',return_value={'expires_at':expiry}):
|
||||
t.diagnose_partial()
|
||||
call=access.powershell.call_args
|
||||
executed=base64.b64decode(call.args[1]['source_base64'])
|
||||
self.assertIn(t.sha(executed),call.args[0])
|
||||
cases=list((Path(root)/'devstate/windows-time-profile-diagnostics').iterdir())
|
||||
self.assertEqual(len(cases),1)
|
||||
intent=json.loads((cases[0]/'intent.json').read_bytes())
|
||||
receipt=json.loads((cases[0]/'receipt.json').read_bytes())
|
||||
self.assertEqual(intent['reader_sha256'],t.sha(executed))
|
||||
self.assertEqual(receipt['reader_sha256'],t.sha(executed))
|
||||
self.assertTrue(receipt['old_move_hresult_unknown'])
|
||||
self.assertEqual((cases[0]/'reader.ps1').read_bytes(),executed)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,613 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""First public V2 time pin for one actual qualified Windows product pair.
|
||||
|
||||
prepare/guards are local only. No target operation happens on import.
|
||||
Missing native product-role/readback evidence blocks preparation; diagnostics
|
||||
are never relabelled as calibrated product clocks or signed runtime success.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
import system_pipe_upgrade as prior
|
||||
import signed_clock_capture_acceptance as raw_capture
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
CLOCK = ROOT.parent / 'rust-discovery-signed-clock'
|
||||
MAIN = ROOT.parent / 'rust-discovery'
|
||||
STATE = ROOT / 'devstate/windows-time-profile-config'
|
||||
PUBLIC = CLOCK / 'devstate/windows-time-profile-public-preparation/c3077acf-12da-410e-9f55-e75a1cd0a75f'
|
||||
PAIR_ID = '4887940a-4c9c-4807-aaf2-6fbc94faad46'
|
||||
PAIR_RESULT_SHA = '2898a72b4b0d84159cc11d80765cbfa4206faf7038d0e860429c8b1a57538ee2'
|
||||
PAIR_INTENT_SHA = '40e9cd557225504429b51dcecd4322b32d7f0973bcbb8e2a2e52516917907b85'
|
||||
PAIR_READBACK_SHA = '63e453fb915cadee028407a6aeaa8c7d209ae88ed12a6d4d4307d4fd25e4c539'
|
||||
PAIR_ROOT = CLOCK / 'devstate/windows-signed-clock/passive-pair-upgrade'
|
||||
SOURCE_CASE = CLOCK / 'devstate/windows-signed-clock/trusted-os-qualification-c4679433-b632-4d6e-8668-f0f2fb54a542'
|
||||
LINK_CASE = MAIN / 'devstate/windows-client/operator-window-20261115/observed-agent-build'
|
||||
ORIGINAL_SOURCE_SHA = 'd8594c1eba2c2cc5d5fde4a462b2110aa2e7e64081452b742c4ed81a2cfb477d'
|
||||
SOURCE_SHA = '342494c4f9e7eca439c059745591a8e907026da20f56b223fcb0eb0707aa6d82'
|
||||
SOURCE_RECEIPT = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d'
|
||||
LINK_RECEIPT = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446'
|
||||
LINK_INPUTS = '11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4'
|
||||
ORIGINAL_LINK_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d'
|
||||
NATIVE_RESULTS = {
|
||||
'linux': ('84592e7a-6554-4a7d-a73f-2bdebdb9e9a8', '150954b0ab290d8e9fbda5616f6df071168efd88a9f1d8b48b2bd8a5f5de7c20'),
|
||||
'windows': ('44059065-c17e-43c3-86aa-d4d131454ccb', 'b235bdd444c112ff91cbc5f160d39d69ef79fb419b9b2ab7ccdcec06009d5c6b')}
|
||||
ORIGINAL_IMAGES = {'agent': '26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b',
|
||||
'system_helper': '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'}
|
||||
IMAGES = {'agent': '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c',
|
||||
'system_helper': ORIGINAL_IMAGES['system_helper']}
|
||||
ASSUMPTION = 'active_guest_no_pause_save_restore_snapshot_migration_host_suspend'
|
||||
PUBLIC_SHAS = {'qualified-time-public-key.json': 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2',
|
||||
'public-platform.json': '94ae865e0e3449f6901f4d5f593aacbd5829b06340e296e19e6f0159a157cba3',
|
||||
'public-binding.json': '9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde',
|
||||
'input-provenance.json': '1c0db66cd0692024f68bddd71949692d274380a86e4b880fea0756479ceb5d0c',
|
||||
'receipt.json': '97e4db147f31f3cff134d2bc596d7d73ea5330b8b5a87971f215bb03a9751391'}
|
||||
RAW = CLOCK / 'devstate/windows-signed-clock-capture-completion/ccba6d8f-c58f-4d2d-a51c-1efb3bfbabdf'
|
||||
RAW_RECEIPTS = {'local-service': '10dd411be265d018489bf9477747ce2d5846ac04128f583425aec4b3c9d5252b',
|
||||
'system': '7409309ea6d586566373f570d6950c60ce2597cf939f261e6d2ea4def004a22f'}
|
||||
require = prior.require
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
def canonical(value):
|
||||
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n').encode()
|
||||
|
||||
def strict_object(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate public JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
def read(path, expected=None, limit=2*1024*1024, decode=True, public=False):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
modes = (0o600,0o644,0o664) if public and expected is not None else (0o600,)
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == os.getuid() and before.st_nlink == 1
|
||||
and stat.S_IMODE(before.st_mode) in modes and 0 < before.st_size <= limit,
|
||||
'private bounded actual public evidence')
|
||||
raw = stream.read(limit + 1); after = os.fstat(stream.fileno())
|
||||
require((before.st_dev,before.st_ino,before.st_size,before.st_mtime_ns,before.st_ctime_ns)
|
||||
== (after.st_dev,after.st_ino,after.st_size,after.st_mtime_ns,after.st_ctime_ns)
|
||||
and len(raw) == before.st_size and (expected is None or sha(raw) == expected),
|
||||
'unchanged independently pinned public evidence')
|
||||
return raw, json.loads(raw, object_pairs_hook=strict_object) if decode else None
|
||||
|
||||
def write(path, raw):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd,'wb') as stream:
|
||||
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||
fd = os.open(path.parent,os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
|
||||
def public_inputs():
|
||||
values = {name: read(PUBLIC/name,digest)[1] for name,digest in PUBLIC_SHAS.items()}
|
||||
pin, platform, binding = (values[n] for n in ('qualified-time-public-key.json','public-platform.json','public-binding.json'))
|
||||
require(set(pin) == {'algorithm','schema_version','key_generation','key_id','server_instance','public_key_hex'}
|
||||
and pin['algorithm'] == 'Ed25519' and pin['schema_version'] == 1
|
||||
and type(pin['key_generation']) is int and pin['key_generation'] > 0
|
||||
and re.fullmatch('[A-Za-z0-9_-]{1,64}',pin['key_id'])
|
||||
and re.fullmatch('[a-f0-9]{64}',pin['public_key_hex']), 'actual separate public time key')
|
||||
require(str(uuid.UUID(pin['server_instance'])) == pin['server_instance'] and uuid.UUID(pin['server_instance']).int > 0,
|
||||
'actual server instance')
|
||||
require(set(binding) == {'tenant_id','asset_id','agent_id','enrollment_generation','assignment_version','public_key_hex'}
|
||||
and all(str(uuid.UUID(binding[k])) == binding[k] and uuid.UUID(binding[k]).int > 0 for k in ('tenant_id','asset_id','agent_id'))
|
||||
and type(binding['enrollment_generation']) is int and binding['enrollment_generation'] == 1
|
||||
and type(binding['assignment_version']) is int and binding['assignment_version'] == 1
|
||||
and bytes.fromhex(pin['public_key_hex']) != bytes.fromhex(binding['public_key_hex']), 'unchanged actual identity and distinct time/job keys')
|
||||
require(platform['schema'] == 1 and platform['hypervisor'] == 'kvm' and platform['state'] == 'running'
|
||||
and platform['domain_uuid'] == '1ec0d319-24bc-4953-a6b2-52b85449be07'
|
||||
and platform['has_genid'] is False
|
||||
and {'name':'hypervclock','present':'yes'} in platform['timers'], 'actual selectively observed active KVM platform')
|
||||
provenance = values['input-provenance.json']
|
||||
require(provenance['candidate_images'] == ORIGINAL_IMAGES and provenance['operating_assumption'] == ASSUMPTION
|
||||
and provenance['platform'] == 'kvm_qemu_hypervclock' and provenance['roles_qualified'] is False
|
||||
and provenance['time_config_created'] is False and provenance['target_called'] is False,
|
||||
'original incomplete public preparation stays incomplete and unchanged')
|
||||
return values
|
||||
|
||||
def source_inputs():
|
||||
_, source = read(SOURCE_CASE/'receipt.json',SOURCE_RECEIPT)
|
||||
read(SOURCE_CASE/'source/crates/agent-windows/src/signed_clock.rs',ORIGINAL_SOURCE_SHA,decode=False)
|
||||
_, link = read(LINK_CASE/'receipt.json',LINK_RECEIPT)
|
||||
_, inputs = read(LINK_CASE/'source-inputs.json',LINK_INPUTS)
|
||||
require(len(inputs) == 202 and len({item['path'] for item in inputs}) == 202,
|
||||
'exact updated source input set')
|
||||
clock = [item for item in inputs if item['path'] == 'crates/agent-windows/src/signed_clock.rs']
|
||||
require(len(clock) == 1 and clock[0]['sha256'] == SOURCE_SHA, 'same qualified V2 clock source')
|
||||
read(LINK_CASE/'source/crates/agent-windows/src/signed_clock.rs',SOURCE_SHA,decode=False)
|
||||
original_path = CLOCK/'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8'
|
||||
_, original = read(original_path/'receipt.json',ORIGINAL_LINK_RECEIPT)
|
||||
require(source['source_sha256'] == original['source_sha256'] == ORIGINAL_SOURCE_SHA
|
||||
and source['input_count'] == link['input_count'] == 202
|
||||
and source['inputs_sha256'] == original['inputs_sha256']
|
||||
and original['source_receipt_sha256'] == SOURCE_RECEIPT
|
||||
and link['source_receipt_sha256'] == ORIGINAL_LINK_RECEIPT
|
||||
and link['source_inputs_sha256'] == LINK_INPUTS
|
||||
and source['inputs_verified_before_after'] is True and link['source_verified_before_after'] is True
|
||||
and source['checks']['linux_signed_clock_guards']['passed'] == 8
|
||||
and link['link_exit'] == 0 and link['original_helper_sha256'] == IMAGES['system_helper']
|
||||
and link['target'] == 'x86_64-pc-windows-gnu' and link['patches'] == ['656102b','cc82124'],
|
||||
'actual fixed V2 source and linked product pair, no runtime success inferred')
|
||||
for artifact, role in ((link['artifacts']['rmm-agent-windows.exe'],'agent'),
|
||||
(original['artifacts']['rmm-helper-windows.exe'],'system_helper')):
|
||||
require(artifact['sha256'] == IMAGES[role] and artifact['machine'] == 'PE_AMD64', 'same actual linked role image')
|
||||
for platform in ('linux','windows'):
|
||||
case, binary_sha = NATIVE_RESULTS[platform]
|
||||
_, result = read(LINK_CASE.parent/case/'result.json',link[platform+'_result_sha256'],public=True)
|
||||
output = result['stdout'] if platform == 'linux' else '\n'.join(result['lines'])
|
||||
names = re.findall(r'^test (signed_clock::tests::[a-z_]+) \.\.\. ok$', output, re.MULTILINE)
|
||||
expected = set(source['checks']['linux_signed_clock_guards']['selected']) | {
|
||||
'signed_clock::tests::passive_sampling_requires_a_profile_and_uses_heartbeat_cadence'}
|
||||
require(result['test_binary_sha256'] == binary_sha
|
||||
and result['exit' if platform=='linux' else 'exit_code'] == 0
|
||||
and len(names) == 9 and set(names) == expected
|
||||
and '9 passed; 0 failed; 0 ignored' in output, 'same-source actual native nine guards')
|
||||
return source,link
|
||||
|
||||
def raw_inputs():
|
||||
require(sha(Path(raw_capture.__file__).read_bytes()) ==
|
||||
'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770',
|
||||
'unchanged original raw-role decoder')
|
||||
records = {}
|
||||
for role, digest in RAW_RECEIPTS.items():
|
||||
_, receipt = read(RAW/('start-'+role+'-receipt.json'),digest)
|
||||
raw_link = receipt['raw_reply']
|
||||
require(raw_link['filename'] == 'start-'+role+'-reply.json', 'fixed original raw role namespace')
|
||||
_, reply = read(RAW/raw_link['filename'],raw_link['sha256'])
|
||||
require(receipt['calibrated'] is False and receipt['clock_authority'] is False
|
||||
and reply['calibrated'] is False and reply['clock_authority'] is False,
|
||||
'raw probe is never a product calibration')
|
||||
for key in ('native_witness','server_witness','preservation'):
|
||||
item = receipt[key]
|
||||
require(Path(item['filename']).name == item['filename'], 'fixed sibling evidence leaf')
|
||||
read(RAW/item['filename'],item['sha256'])
|
||||
raw_capture.validate_role(role,reply['roles'][role],'efd17b43-7e04-49a7-9bd4-862d13365eec')
|
||||
records[role] = {'receipt_sha256':digest,'probe_image_sha256':raw_capture.EXE_SHA,
|
||||
'raw_report_sha256':reply['roles'][role]['raw_report_sha256']}
|
||||
return records
|
||||
|
||||
def validate_pair(result, intent):
|
||||
require(result.get('id') == PAIR_ID and result.get('verified') is True and result.get('completed') is True
|
||||
and result.get('no_jobs') is True and result.get('windows_jobs_enabled') is False
|
||||
and result.get('helper_effects_enabled') is False and result.get('clock_authority_not_proven') is True
|
||||
and result.get('private_key_read') is False, 'actual completed passive pair required; no missing or dummy result')
|
||||
payload = intent.get('payload',intent)
|
||||
require(payload['new_agent'] == IMAGES['agent'] and payload['new_helper'] == IMAGES['system_helper']
|
||||
and payload['qualification_sha256'] == LINK_RECEIPT and payload['manifest_sha256'] == LINK_RECEIPT,
|
||||
'actual exact V2 pair source chain')
|
||||
native = result['native']
|
||||
require(native['binary_sha256'] == IMAGES['agent'] and native['helper_sha256'] == IMAGES['system_helper']
|
||||
and native['policy_sha256'] == payload['new_policy'] and native['pin_sha256'] == payload['new_pin'], 'complete native image/pin pair')
|
||||
qualifications = []
|
||||
for role,service,kernel,label,user in [('agent','service','agent_kernel','agent','S-1-5-19'),('system_helper','helper_service','helper_kernel','helper','S-1-5-18')]:
|
||||
s,k,f = native[service],native[kernel],native['files'][label]
|
||||
require(s['state'] == 'Running' and type(s['pid']) is int and s['pid'] > 0
|
||||
and k['pid'] == s['pid'] and k['creation_filetime'] == s['creation_filetime']
|
||||
and k['owner_sid'] == s['owner_sid'] == user and k['service_sid_enabled'] is True
|
||||
and k['kernel_handle_bound'] is True and f['sha256'] == IMAGES[role]
|
||||
and k['image'] == ('C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe' if role=='agent'
|
||||
else 'C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe')
|
||||
and re.fullmatch(r'S-1-5-80-(?:[0-9]+-){4}[0-9]+',k['service_sid'])
|
||||
and re.fullmatch('[0-9]+',k['creation_filetime']) and re.fullmatch('[a-f0-9]{32}',f['file_id']),
|
||||
'actual SCM/kernel account, enabled service SID, birth and image FileID')
|
||||
qualifications.append({'role':role,'binary_sha256':IMAGES[role],'service':copy.deepcopy(s),
|
||||
'kernel':copy.deepcopy(k),'image_file':copy.deepcopy(f)})
|
||||
return native,payload,qualifications
|
||||
|
||||
def produce(public, pair_result, pair_intent, raw, result_sha, intent_sha):
|
||||
native,payload,roles = validate_pair(pair_result,pair_intent)
|
||||
binding = public['public-binding.json']; pin=public['qualified-time-public-key.json']
|
||||
require(native['agent_id'] == binding['agent_id'] and native['asset_id'] == binding['asset_id'], 'same actual device binding')
|
||||
settings = json.loads(base64.b64decode(payload['settings_base64'],validate=True),object_pairs_hook=strict_object)
|
||||
require(settings['binding'] == binding and settings['enable_effects'] is False
|
||||
and settings['agent']['service_sid'] == roles[0]['kernel']['service_sid']
|
||||
and settings['helper']['service_sid'] == roles[1]['kernel']['service_sid']
|
||||
and settings['agent']['service_sid'] != settings['helper']['service_sid'], 'actual reciprocal settings and distinct service roles')
|
||||
platform = {'profile':'rmm.windows.trusted-os.platform-provenance.v1','operating_assumption':ASSUMPTION,
|
||||
'platform':'kvm_qemu_hypervclock','public_platform_sha256':PUBLIC_SHAS['public-platform.json'],
|
||||
'original_public_preparation_sha256':PUBLIC_SHAS['input-provenance.json'],
|
||||
'source_sha256':SOURCE_SHA,'source_receipt_sha256':SOURCE_RECEIPT,
|
||||
'product_pair_receipt_sha256':LINK_RECEIPT,'pair_result_sha256':result_sha,
|
||||
'pair_intent_sha256':intent_sha,'independent_pair_readback_sha256':PAIR_READBACK_SHA,
|
||||
'independent_physical_calibration_claimed':False}
|
||||
items={'platform-provenance.json':canonical(platform),'public-platform.json':canonical(public['public-platform.json'])}
|
||||
# The original platform file is separately retained below using its actual
|
||||
# bytes; this canonical descriptive copy is never mislabelled as its hash.
|
||||
references=[]
|
||||
for role in roles:
|
||||
role.update(profile='rmm.windows.trusted-os.product-role-prerequisite.v1',pair_case_id=PAIR_ID,
|
||||
pair_result_sha256=result_sha,pair_intent_sha256=intent_sha,
|
||||
independent_pair_readback_sha256=PAIR_READBACK_SHA,
|
||||
source_sha256=SOURCE_SHA if role['role']=='agent' else ORIGINAL_SOURCE_SHA,
|
||||
original_source_receipt_sha256=SOURCE_RECEIPT,product_pair_receipt_sha256=LINK_RECEIPT,
|
||||
platform_provenance_sha256=sha(items['platform-provenance.json']),
|
||||
raw_capture=raw['local-service' if role['role']=='agent' else 'system'],
|
||||
signed_runtime_verified=False,physical_calibration_claimed=False)
|
||||
name=role['role']+'-qualification.json';items[name]=canonical(role)
|
||||
references.append({'role':role['role'],'binary_sha256':role['binary_sha256'],'qualification_sha256':sha(items[name])})
|
||||
value={'schema_version':2,'key_generation':pin['key_generation'],'server_instance':pin['server_instance'],
|
||||
'binding':binding,'public_keys_hex':{pin['key_id']:pin['public_key_hex']},
|
||||
'trusted_os_active_guest':{'operating_assumption':ASSUMPTION,'platform':'kvm_qemu_hypervclock',
|
||||
'platform_provenance_sha256':sha(items['platform-provenance.json']),'qualifications':references}}
|
||||
items['time-attestation.json']=canonical(value)
|
||||
require(len(items['time-attestation.json'])<=16384, 'real bounded public V2 configuration')
|
||||
return items,native,payload
|
||||
|
||||
# Controller and transport are defined below; no remote action on import.
|
||||
|
||||
HEADER = r'''
|
||||
$ErrorActionPreference='Stop';$request=$global:RmmTimeProfilePayload
|
||||
if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or[guid]::ParseExact($request.id,'D').ToString()-cne$request.id-or$request.profile-cne'rmm.windows.initial-public-time-profile.v2'){throw 'Exact initial time-profile operation'}
|
||||
$p=$request.pair_payload
|
||||
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-profile-'+$request.id)
|
||||
$agentRoot='C:\ProgramData\RustDiscovery';$agentState=Join-Path $agentRoot 'state';$helperRoot='C:\ProgramData\RustDiscoverySystem';$helperState=Join-Path $helperRoot 'state'
|
||||
$config=Join-Path $agentRoot 'config.json';$settings=Join-Path $helperRoot 'helper.json';$pin=Join-Path $helperRoot 'agent-pin.json'
|
||||
$agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$helperBinary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe'
|
||||
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$sys='S-1-5-18';$admin='S-1-5-32-544'
|
||||
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$helperName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$target=Join-Path $helperRoot 'time-attestation.json';$active=Join-Path $boot 'time-profile-initial-active.json'
|
||||
'''
|
||||
|
||||
BODY = r'''
|
||||
function ReadAcl($path,[bool]$directory){
|
||||
Check $path $directory;$acl=Get-Acl -LiteralPath $path
|
||||
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@($sys,$admin)){throw 'Public pin owner must remain SYSTEM/Administrators'}
|
||||
$seen=@{};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){
|
||||
$id=$rule.IdentityReference.Value;$rights=[int64]$rule.FileSystemRights
|
||||
if($rule.AccessControlType-cne'Allow'-or$id-cnotin@($sys,$admin,$agentSid,$helperSid)-or($id-cnotin@($sys,$admin)-and($rights-band(-bnot 0x1200a9))-ne0)){throw 'Only exact native reader rights, no foreign writer'}
|
||||
$seen[$id]=$true
|
||||
};foreach($id in @($sys,$admin)){if(!$seen[$id]){throw 'Privileged public-pin role missing'}}
|
||||
return $acl
|
||||
}
|
||||
function GrantRootReaders{
|
||||
$acl=ReadAcl $helperRoot $true
|
||||
foreach($id in @($agentSid,$helperSid)){
|
||||
$present=$false;foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.IdentityReference.Value-ceq$id-and([int64]$rule.FileSystemRights-band0x1200a9)-eq0x1200a9){$present=$true}}
|
||||
if(!$present){$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),[Security.AccessControl.FileSystemRights]0x1200a9,'None','None','Allow')))}
|
||||
}
|
||||
# This-folder-only ACEs: do not expose state/PKI/ledger/intent descendants.
|
||||
Set-Acl -LiteralPath $helperRoot -AclObject $acl;$null=ReadAcl $helperRoot $true
|
||||
}
|
||||
function SetPinAcl($path){
|
||||
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm(('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;'+$agentSid+')(A;;0x1200a9;;;'+$helperSid+')'))
|
||||
Set-Acl -LiteralPath $path -AclObject $acl;$null=ReadAcl $path $false
|
||||
}
|
||||
function NewPrivateCase{
|
||||
[RmmTimeProfileCase]::CreatePrivateOnce($folder);CheckControl $folder $true
|
||||
}
|
||||
function FileVolume($path){
|
||||
$handle=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0x2200000,[IntPtr]::Zero)
|
||||
try{if($handle.IsInvalid){throw 'Protected directory identity handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($handle,18,[ref]$id,24)){throw 'Protected directory volume'};return $id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)}finally{$handle.Dispose()}
|
||||
}
|
||||
function SameLive($before,$after){
|
||||
Preserved $before $after $false
|
||||
foreach($field in @('files','service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$field $after.$field)){throw 'Same original data/PKI/FileIDs/services/process generations required'}}
|
||||
}
|
||||
function ConfigBytes{
|
||||
$bytes=[Convert]::FromBase64String($request.config_base64)
|
||||
if($bytes.Length-gt16384-or$bytes.Length-lt1-or(BytesHash $bytes)-cne$request.config_sha256){throw 'Fixed complete public config bytes'}
|
||||
$value=[Text.Encoding]::UTF8.GetString($bytes)|ConvertFrom-Json
|
||||
if($value.schema_version-ne2-or$value.key_generation-ne$request.key_generation-or$value.server_instance-cne$request.server_instance-or!(JsonEqual $value.binding $request.binding)-or$value.trusted_os_active_guest.operating_assumption-cne'active_guest_no_pause_save_restore_snapshot_migration_host_suspend'-or$value.trusted_os_active_guest.platform-cne'kvm_qemu_hypervclock'-or@($value.trusted_os_active_guest.qualifications).Count-ne2-or$value.trusted_os_active_guest.qualifications[0].role-cne'agent'-or$value.trusted_os_active_guest.qualifications[0].binary_sha256-cne$p.new_agent-or$value.trusted_os_active_guest.qualifications[1].role-cne'system_helper'-or$value.trusted_os_active_guest.qualifications[1].binary_sha256-cne$p.new_helper){throw 'Closed real schema2/profile/role binding'}
|
||||
return ,$bytes
|
||||
}
|
||||
CheckControl $boot $true
|
||||
if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'InstallPublicTimeProfile.ps1')-or(Hash $PSCommandPath)-cne$request.script_sha256){throw 'Exact reviewed public-pin controller'}
|
||||
CheckControl $PSCommandPath $false
|
||||
$expected=$request.expected_native
|
||||
$before=ActualState $true;SameLive $expected $before
|
||||
if($before.agent_kernel.service_sid-cne$agentSid-or$before.helper_kernel.service_sid-cne$helperSid){throw 'Same actual qualified service SIDs'}
|
||||
$null=ReadAcl $helperRoot $true
|
||||
if($request.action-ceq'read'){
|
||||
$records=[ordered]@{};if(Test-Path -LiteralPath $folder){CheckControl $folder $true;foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','result.json')){$path=Join-Path $folder $name;$records[$name]=$null;if(Test-Path -LiteralPath $path){CheckControl $path $false;if((Get-Item -LiteralPath $path -Force).Length-gt2097152){throw 'Bounded original public-pin history'};$records[$name]=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json}}}
|
||||
if($records['intent.json']){foreach($field in $request.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $records['intent.json'].request.$field $request.$field)){throw 'Same original public-pin intent only'}}}
|
||||
$activeRecord=$null;if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active -Force).Length-gt8192){throw 'Bounded public-pin active marker'};$activeRecord=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($activeRecord.id-cne$request.id-or$activeRecord.config_sha256-cne$request.config_sha256-or$activeRecord.script_sha256-cne$request.script_sha256){throw 'Another initial public-pin case; no adoption'}}
|
||||
$current=$null;if(Test-Path -LiteralPath $target){$null=ReadAcl $target $false;$current=FileIdentity $target;if($current.sha256-cne$request.config_sha256){throw 'Unexpected existing configuration; no adoption'}}
|
||||
@{id=$request.id;read_only=$true;records=$records;active=$activeRecord;configuration=$current;native=$before;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;clock_runtime_qualified=$false;no_jobs=$true}|ConvertTo-Json -Depth 50 -Compress;exit0
|
||||
}
|
||||
if($request.action-cne'install'){throw 'Exact install action only'}
|
||||
if((Test-Path -LiteralPath $target)-or(Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing initial time profile or partial attempt: original read only'}
|
||||
$bytes=ConfigBytes
|
||||
$rootSddl=(Get-Acl -LiteralPath $helperRoot).Sddl
|
||||
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid)
|
||||
try{
|
||||
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||
$installNotBefore=[DateTime]::UtcNow.ToString('o')
|
||||
NewPrivateCase
|
||||
WriteNew (Join-Path $folder 'intent.json') @{id=$request.id;request=$request;before=$before;original_root_sddl=$rootSddl;install_not_before=$installNotBefore;no_retry=$true}
|
||||
WriteNew $active @{id=$request.id;config_sha256=$request.config_sha256;script_sha256=$request.script_sha256;no_retry=$true}
|
||||
foreach($item in $request.provenance.PSObject.Properties){if($item.Name-cnotmatch'^(platform-provenance|public-platform|original-public-platform|agent-qualification|system_helper-qualification|qualified-time-public-key|public-binding)\.json$'){throw 'Closed public provenance leaves'};$raw=[Convert]::FromBase64String($item.Value);if($raw.Length-gt65536){throw 'Bounded public provenance'};WriteBytes (Join-Path $folder $item.Name) $raw}
|
||||
$staged=Join-Path $folder 'time-attestation.candidate.json';WriteBytes $staged $bytes;SetPinAcl $staged
|
||||
if((FileIdentity $staged).sha256-cne$request.config_sha256-or(FileVolume $folder)-cne(FileVolume $helperRoot)){throw 'Verified complete same-volume public pin'}
|
||||
SameLive $before (ActualState $true)
|
||||
if((Get-Acl -LiteralPath $helperRoot).Sddl-cne$rootSddl){throw 'Immediate directory ACL CAS'}
|
||||
WriteNew (Join-Path $folder 'directory-acl-intent.json') @{old_sddl=$rootSddl;readers=@($agentSid,$helperSid);this_folder_only=$true}
|
||||
GrantRootReaders
|
||||
WriteNew (Join-Path $folder 'directory-acl-done.json') @{sddl=(Get-Acl -LiteralPath $helperRoot).Sddl}
|
||||
SameLive $before (ActualState $true)
|
||||
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||
if(Test-Path -LiteralPath $target){throw 'Target appeared before no-overwrite publication'}
|
||||
$stagedId=FileIdentity $staged
|
||||
WriteNew (Join-Path $folder 'publish-intent.json') @{config_sha256=$request.config_sha256;staged=$stagedId;create_once=$true}
|
||||
[IO.File]::Move($staged,$target)
|
||||
$null=ReadAcl $target $false;$published=FileIdentity $target
|
||||
if(!(JsonEqual $published $stagedId)){throw 'Exact same file identity/hash/ACL after publication'}
|
||||
$after=ActualState $true;SameLive $before $after
|
||||
$null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper
|
||||
$result=@{id=$request.id;installed=$true;install_not_before=$installNotBefore;configuration=$published;native=$after;original_root_sddl=$rootSddl;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;no_jobs=$true;clock_runtime_qualified=$false;services_changed=$false;private_key_read=$false}
|
||||
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 50 -Compress
|
||||
}finally{$heldAgent.Dispose();$heldHelper.Dispose()}
|
||||
'''.replace('exit0','exit 0')
|
||||
|
||||
|
||||
def controller():
|
||||
"""Reuse only existing read-only witnesses, not any old phase/repair code."""
|
||||
require(sha(Path(prior.__file__).read_bytes()) == 'e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0'
|
||||
and sha(Path(prior.u.__file__).read_bytes()) == 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38', 'unchanged reviewed original readonly witness sources')
|
||||
source = prior.u.SCRIPT
|
||||
# Every selected section ends at the next named function. No StartOnce,
|
||||
# StopPinned, Swap, Backup, original phase, or old payload dispatch is copied.
|
||||
names = ['Check','BytesHash','Hash','AclHash','CheckControl','Service','Probe','Diagnostic','RawAgentProbe','EmptyIntentStore','State','Preserved']
|
||||
functions=[]
|
||||
for name in names:
|
||||
start=source.index('function '+name+'(') if 'function '+name+'(' in source else source.index('function '+name+'{')
|
||||
end=source.find('\nfunction ',start+1)
|
||||
require(end>start, 'closed existing readonly witness boundary')
|
||||
functions.append(source[start:end])
|
||||
# File writers are new, closed by the controller's fixed namespace only.
|
||||
writers=r'''function WriteBytes($path,[byte[]]$bytes){$file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}}
|
||||
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 50 -Compress)))}'''
|
||||
return HEADER+'\n'+STRUCTURAL+'\n'+'\n'.join(functions)+'\n'+prior.NATIVE+'\n'+CASE_NATIVE+'\n'+writers+'\n'+BODY
|
||||
|
||||
# Same reviewed structural comparison as e6debe5; member order is not identity.
|
||||
STRUCTURAL = r'''function CanonicalStateValue($value,[int]$depth=0){
|
||||
if($depth-gt40){throw 'Bounded state comparison depth'}
|
||||
if($null-eq$value){return $null}
|
||||
# ETS wrapping does not turn a CLR JSON scalar into a JSON object.
|
||||
$base=$value.PSObject.BaseObject;$culture=[Globalization.CultureInfo]::InvariantCulture
|
||||
if($base-is[string]){return [string]::new($base.ToCharArray())}
|
||||
if($base-is[char]){return [string]::new([char[]]@($base))}
|
||||
if($base-is[bool]){return [bool]::Parse($base.ToString())}
|
||||
if($base-is[sbyte]-or$base-is[int16]-or$base-is[int32]-or$base-is[int64]){return [int64]::Parse($base.ToString($culture),$culture)}
|
||||
if($base-is[byte]-or$base-is[uint16]-or$base-is[uint32]-or$base-is[uint64]){return [uint64]::Parse($base.ToString($culture),$culture)}
|
||||
if($base-is[single]-or$base-is[double]){$number=[double]::Parse($base.ToString('R',$culture),$culture);if([double]::IsNaN($number)-or[double]::IsInfinity($number)){throw 'Finite JSON state number required'};return $number}
|
||||
if($base-is[decimal]){return [decimal]::Parse($base.ToString($culture),$culture)}
|
||||
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
||||
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
||||
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
||||
return $value
|
||||
}
|
||||
function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateValue $a) -Depth 40 -Compress)-ceq(ConvertTo-Json -InputObject (CanonicalStateValue $b) -Depth 40 -Compress))}'''
|
||||
CASE_NATIVE = r'''Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
public static class RmmTimeProfileCase {
|
||||
[StructLayout(LayoutKind.Sequential)] struct Attributes {public int Length;public IntPtr Descriptor;public int Inherit;}
|
||||
[DllImport("kernel32.dll",EntryPoint="CreateDirectoryW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)]
|
||||
[return:MarshalAs(UnmanagedType.Bool)] static extern bool CreateDirectory(string path,ref Attributes security);
|
||||
public static void CreatePrivateOnce(string path){
|
||||
RawSecurityDescriptor sd=new RawSecurityDescriptor("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)");
|
||||
byte[] raw=new byte[sd.BinaryLength];sd.GetBinaryForm(raw,0);GCHandle pin=GCHandle.Alloc(raw,GCHandleType.Pinned);
|
||||
try{Attributes attributes=new Attributes{Length=Marshal.SizeOf(typeof(Attributes)),Descriptor=pin.AddrOfPinnedObject(),Inherit=0};
|
||||
if(!CreateDirectory(path,ref attributes))throw new Win32Exception(Marshal.GetLastWin32Error(),"TIME_PROFILE_PRIVATE_CREATE_ONCE");
|
||||
}finally{pin.Free();}
|
||||
}
|
||||
}
|
||||
'@'''
|
||||
|
||||
LAUNCH = r'''$ErrorActionPreference='Stop';$request=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or$request.script_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed public-pin launch'}
|
||||
$script=Join-Path (Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' $request.script_sha256) 'InstallPublicTimeProfile.ps1'
|
||||
$item=Get-Item -LiteralPath $script -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$item.Length-gt100000-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$request.script_sha256){throw 'Exact bounded immutable time-pin script'}
|
||||
$acl=Get-Acl -LiteralPath $script;if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch owner'}
|
||||
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-cne'Allow'-or$rule.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch DACL'}}
|
||||
$global:RmmTimeProfilePayload=$request;& $script
|
||||
'''
|
||||
|
||||
def guards():
|
||||
script=controller()
|
||||
for forbidden in ('Stop-Service','Start-Service','Restart-Computer','Set-Date','AdjustTokenPrivileges',
|
||||
'function Swap','function Backup','function StartOnce','CreateService(', 'DeleteService('):
|
||||
require(forbidden not in script, 'no service/clock/job effect imported')
|
||||
require("$request.action-cnotin@('install','read')" in script
|
||||
and "if($request.action-cne'install')" in script
|
||||
and '[IO.File]::Move($staged,$target)' in script
|
||||
and script.index("'publish-intent.json') @") < script.index('[IO.File]::Move($staged,$target)')
|
||||
and 'This-folder-only ACEs' in script and '0x1200a9' in script
|
||||
and 'CreatePrivateOnce' in script, 'closed create-once public-pin effects')
|
||||
return script
|
||||
|
||||
def prepare():
|
||||
# All prerequisites are checked BEFORE creating a local installation case.
|
||||
# Source/link/role constants deliberately remain unset until actual evidence.
|
||||
require(PAIR_ID is not None and str(uuid.UUID(PAIR_ID)) == PAIR_ID
|
||||
and all(isinstance(value,str) and re.fullmatch('[a-f0-9]{64}',value)
|
||||
for value in (PAIR_RESULT_SHA,PAIR_INTENT_SHA,PAIR_READBACK_SHA)),
|
||||
'actual completed new pair and independently pinned role readback required')
|
||||
public=public_inputs(); source_inputs(); raw=raw_inputs()
|
||||
pair=PAIR_ROOT/PAIR_ID
|
||||
result_raw,result=read(pair/'result.json',PAIR_RESULT_SHA)
|
||||
intent_path=pair/'intent.json'
|
||||
if not intent_path.exists(): intent_path=pair/'bound-payload.json'
|
||||
intent_raw,intent=read(intent_path,PAIR_INTENT_SHA)
|
||||
_, independent=read(pair/'independent-readback.json',PAIR_READBACK_SHA)
|
||||
require(independent.get('id') == PAIR_ID and independent.get('completed') is True
|
||||
and independent.get('read_only') is True and independent.get('no_job') is True
|
||||
and independent.get('no_service_action') is True
|
||||
and result['independent_readback_sha256'] == PAIR_READBACK_SHA
|
||||
and result['intent_sha256'] == PAIR_INTENT_SHA
|
||||
and all(independent['native'][key] == result['native'][key]
|
||||
for key in ('files','service','helper_service','agent_kernel','helper_kernel')),
|
||||
'original independent same-generation role and file readback')
|
||||
items,native,payload=produce(public,result,intent,raw,sha(result_raw),sha(intent_raw))
|
||||
items['original-public-platform.json']=read(PUBLIC/'public-platform.json',PUBLIC_SHAS['public-platform.json'])[0]
|
||||
for name in ('qualified-time-public-key.json','public-binding.json'):
|
||||
items[name]=read(PUBLIC/name,PUBLIC_SHAS[name])[0]
|
||||
script=guards().encode(); ident=str(uuid.uuid4()); script_sha=sha(script)
|
||||
keep=('old_agent','old_helper','new_agent','new_helper','old_policy','old_pin','new_policy','new_pin',
|
||||
'config_sha256','probe_sha256','system_probe_sha256','intent_leaves')
|
||||
public_payload={key:payload[key] for key in keep}
|
||||
request={'profile':'rmm.windows.initial-public-time-profile.v2','id':ident,'action':'read',
|
||||
'script_sha256':script_sha,'config_sha256':sha(items['time-attestation.json']),
|
||||
'config_base64':base64.b64encode(items.pop('time-attestation.json')).decode(),
|
||||
'pair_payload':public_payload,'expected_native':native,'binding':public['public-binding.json'],
|
||||
'key_generation':public['qualified-time-public-key.json']['key_generation'],
|
||||
'server_instance':public['qualified-time-public-key.json']['server_instance'],
|
||||
'provenance':{name:base64.b64encode(value).decode() for name,value in items.items()}}
|
||||
# Existing transport passes the payload on stdin, not on the command line.
|
||||
require(len(canonical(request))<=128*1024,'bounded public bootstrap request')
|
||||
STATE.mkdir(mode=0o700,parents=True,exist_ok=True);ident_dir=STATE/ident;ident_dir.mkdir(mode=0o700)
|
||||
write(ident_dir/'InstallPublicTimeProfile.ps1',script)
|
||||
write(ident_dir/'time-attestation.json',base64.b64decode(request['config_base64'],validate=True))
|
||||
for name,value in items.items(): write(ident_dir/name,value)
|
||||
manifest={'profile':request['profile'],'id':ident,'generator_sha256':sha(Path(__file__).read_bytes()),
|
||||
'script_sha256':script_sha,'request':request,'pair_result_sha256':sha(result_raw),
|
||||
'pair_intent_sha256':sha(intent_raw),'source_receipt_sha256':SOURCE_RECEIPT,
|
||||
'product_link_receipt_sha256':LINK_RECEIPT,'target_called':False,'clock_runtime_qualified':False,
|
||||
'files':{name:{'sha256':sha(value),'bytes':len(value)} for name,value in items.items()}}
|
||||
write(ident_dir/'manifest.json',canonical(manifest))
|
||||
print(json.dumps({'id':ident,'prepared_locally':True,'target_called':False,
|
||||
'config_sha256':request['config_sha256'],'manifest_sha256':sha(canonical(manifest))}))
|
||||
|
||||
def load_case(ident):
|
||||
require(str(uuid.UUID(ident))==ident and uuid.UUID(ident).version==4,'canonical original time-pin case')
|
||||
folder=STATE/ident; _,manifest=read(folder/'manifest.json')
|
||||
require(manifest['id']==ident and manifest['generator_sha256']==sha(Path(__file__).read_bytes())
|
||||
and manifest['script_sha256']==sha(guards().encode()),'same exact reviewed operator and case')
|
||||
require(read(folder/'InstallPublicTimeProfile.ps1',decode=False)[0]==guards().encode(), 'same controller bytes')
|
||||
request=manifest['request'];read(folder/'time-attestation.json',request['config_sha256'])
|
||||
for name,item in manifest['files'].items(): read(folder/name,item['sha256'])
|
||||
return folder,manifest
|
||||
|
||||
def target(action,ident):
|
||||
"""Only Root invokes these explicit phases after independent review."""
|
||||
folder,manifest=load_case(ident)
|
||||
require(action in ('stage','install','read'),'closed public-pin phase')
|
||||
if action!='read':
|
||||
write(folder/(action+'-attempt.json'),canonical({'id':ident,'action':action,'once':True,'lost_reply_read_original_case_only':True}))
|
||||
access=raw_capture.CaptureAccess(MAIN)
|
||||
if action=='stage':
|
||||
path=folder/'InstallPublicTimeProfile.ps1';digest=manifest['script_sha256']
|
||||
stage=prior.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',path.name)
|
||||
observed=access.powershell(stage,{'sha256':digest})
|
||||
if not observed['already_uploaded']:
|
||||
import subprocess
|
||||
config=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||
prefix=config['ssh_prefix'];args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]]
|
||||
remote='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+path.name
|
||||
reply=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(remote)+'\n').encode(),capture_output=True,timeout=60)
|
||||
write(folder/'stage-transport.json',canonical({'returncode':reply.returncode,'stdout_b64':base64.b64encode(reply.stdout).decode(),'stderr_b64':base64.b64encode(reply.stderr).decode()}))
|
||||
require(reply.returncode==0,'once-only fixed script transfer; lost reply read only')
|
||||
observed=access.powershell(stage,{'sha256':digest})
|
||||
require(observed['already_uploaded'] is True and observed['sha256']==digest,'exact staged public-pin controller')
|
||||
result={'id':ident,'staged':True,'script_sha256':digest,'configuration_installed':False}
|
||||
else:
|
||||
request=copy.deepcopy(manifest['request']);request['action']=action
|
||||
result=access.powershell(LAUNCH,request,timeout=120)
|
||||
require(result['id']==ident and result.get('no_jobs') is True and result.get('clock_runtime_qualified') is False,
|
||||
'same native public-pin result, never clock readiness')
|
||||
output=folder/((action+'-'+str(uuid.uuid4()) if action=='read' else action)+'-reply.json')
|
||||
write(output,canonical(result))
|
||||
print(json.dumps({'id':ident,'action':action,'reply_sha256':sha(canonical(result)),'clock_runtime_qualified':False}))
|
||||
|
||||
# Dedicated read-only path for the already attempted original case. It never
|
||||
# passes through load_case(): changing the generator must not rewrite or adopt
|
||||
# the original staged controller/intent hash binding.
|
||||
PARTIAL_ID = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
|
||||
PARTIAL_MANIFEST_SHA = '0c9a3ffeed490757f7bd8c63d7e2ec28156212945094621f511e20679ce0b3b0'
|
||||
PARTIAL_GENERATOR_SHA = 'a8d55b60d413c1d68f568c173e6ea32727cef8645e61eb772d24f98e22b0b10a'
|
||||
PARTIAL_SCRIPT_SHA = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
|
||||
PARTIAL_CONFIG_SHA = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
|
||||
PARTIAL_CASE = ROOT.parent/'rust-discovery-agent-updater'/'devstate/windows-time-profile-config'/PARTIAL_ID
|
||||
|
||||
|
||||
def partial_reader():
|
||||
"""Fixed file/ACL/marker observation only; no service or publication code."""
|
||||
require(sha(Path(prior.__file__).read_bytes())=='e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0'
|
||||
and sha(Path(prior.u.__file__).read_bytes())=='f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38',
|
||||
'exact original metadata-only primitive sources')
|
||||
source = prior.u.SCRIPT
|
||||
functions = []
|
||||
for name in ('Check','BytesHash','Hash','AclHash','CheckControl'):
|
||||
start=source.index('function '+name+'(');end=source.find('\nfunction ',start+1)
|
||||
require(end>start,'closed original read-only function');functions.append(source[start:end])
|
||||
native=prior.NATIVE.split('function FileIdentity(',1)[0]
|
||||
identity='function FileIdentity('+prior.NATIVE.split('function FileIdentity(',1)[1].split('function Kernel(',1)[0]
|
||||
header=r'''$ErrorActionPreference='Stop';$inputRecord=$global:RmmPartialReaderInput
|
||||
if((($inputRecord.PSObject.Properties.Name|Sort-Object)-join',')-cne'kind'-or$inputRecord.kind-cne'original-public-time-profile-ad9-readonly'){throw 'Fixed original partial profile observation'}
|
||||
$sys='S-1-5-18';$admin='S-1-5-32-544';$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value;$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoverySystemHelper')).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$folder='C:\ProgramData\RustDiscoveryBootstrap\time-profile-ad9fd154-b2be-4f5d-9e17-65abb721ceaf';$root='C:\ProgramData\RustDiscoverySystem';$active='C:\ProgramData\RustDiscoveryBootstrap\time-profile-initial-active.json'
|
||||
'''
|
||||
body=r'''function ErrorNumber($errorRecord){$ex=$errorRecord.Exception.GetBaseException();$h=[int64]$ex.HResult-band0xffffffffL;$win32=$null;if(($h-band0xffff0000L)-eq0x80070000L){$win32=$h-band0xffffL};return @{exception_type=$ex.GetType().FullName;hresult_hex=('0x{0:x8}'-f$h);win32_code=$win32}}
|
||||
function ObservePublic($path){
|
||||
if(!(Test-Path -LiteralPath $path)){return @{present=$false}}
|
||||
try{Check $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt16384){throw 'Bounded public profile only'};$identity=FileIdentity $path;return @{present=$true;identity=$identity;attributes=[int64]$item.Attributes;creation_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();last_write_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();expected_hash=($identity.sha256-ceq'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b')}}catch{return @{present=$true;observation_failed=$true;error=(ErrorNumber $_)}}
|
||||
}
|
||||
CheckControl $folder $true;Check $root $true
|
||||
$records=[ordered]@{};foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','publish-failure.json','result.json')){$path=Join-Path $folder $name;if(!(Test-Path -LiteralPath $path)){$records[$name]=@{present=$false};continue};CheckControl $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-gt2097152){throw 'Bounded original marker'};$value=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json
|
||||
$record=@{present=$true;sha256=(Hash $path);bytes=$item.Length}
|
||||
if($name-ceq'intent.json'){if($value.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$value.request.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.request.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original intent binding'};$record.install_not_before=$value.install_not_before;$record.no_retry=$value.no_retry}
|
||||
if($name-ceq'publish-intent.json'){if($value.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$value.create_once-ne$true){throw 'Original publication binding'};$record.staged=$value.staged}
|
||||
if($name-ceq'directory-acl-intent.json'){$record.old_sddl=$value.old_sddl};if($name-ceq'directory-acl-done.json'){$record.sddl=$value.sddl}
|
||||
if($name-ceq'publish-failure.json'){$record.failure=@{exception_type=$value.exception_type;hresult_hex=$value.hresult_hex;win32_code=$value.win32_code}}
|
||||
$records[$name]=$record
|
||||
}
|
||||
$activeRecord=@{present=$false};if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active).Length-gt8192){throw 'Bounded active original marker'};$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($a.id-cne'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'-or$a.config_sha256-cne'2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'-or$a.script_sha256-cne'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'){throw 'Original active binding'};$activeRecord=@{present=$true;sha256=(Hash $active);id=$a.id;config_sha256=$a.config_sha256;script_sha256=$a.script_sha256}}
|
||||
@{id='ad9fd154-b2be-4f5d-9e17-65abb721ceaf';read_only=$true;candidate=(ObservePublic (Join-Path $folder 'time-attestation.candidate.json'));target=(ObservePublic (Join-Path $root 'time-attestation.json'));records=$records;active=$activeRecord;root_sddl=(Get-Acl -LiteralPath $root).Sddl;old_move_hresult_unknown=$true;retry_authorized=$false;installation_verified=$false;clock_runtime_qualified=$false;private_key_read=$false;service_action=$false}|ConvertTo-Json -Depth 20 -Compress
|
||||
'''
|
||||
reader=header+'\n'+'\n'.join(functions)+'\n'+native+identity+'\n'+body
|
||||
require(all(token not in reader for token in ('[IO.File]::Move','Set-Acl','WriteBytes','WriteNew','Start-Service','Stop-Service','CreateDirectory','function State','function Probe')),'read-only original partial observer')
|
||||
return reader
|
||||
|
||||
|
||||
def diagnose_partial():
|
||||
# Only a future explicitly authorized maintenance window may call this.
|
||||
# The original install/read code and original markers stay untouched.
|
||||
import datetime as dt
|
||||
import subprocess
|
||||
raw,manifest=read(PARTIAL_CASE/'manifest.json',PARTIAL_MANIFEST_SHA)
|
||||
require(manifest['id']==PARTIAL_ID and manifest['generator_sha256']==PARTIAL_GENERATOR_SHA
|
||||
and manifest['script_sha256']==PARTIAL_SCRIPT_SHA
|
||||
and manifest['request']['config_sha256']==PARTIAL_CONFIG_SHA,'fixed original failed installation only')
|
||||
read(PARTIAL_CASE/'InstallPublicTimeProfile.ps1',PARTIAL_SCRIPT_SHA,decode=False)
|
||||
access=raw_capture.CaptureAccess(MAIN)
|
||||
grant=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
||||
expiry=dt.datetime.fromisoformat(grant['expires_at'].replace('Z','+00:00'))
|
||||
require((expiry-dt.datetime.now(dt.timezone.utc)).total_seconds()>=60,'current confirmed access window required for read')
|
||||
source=partial_reader();digest=sha(source.encode());root=ROOT/'devstate/windows-time-profile-diagnostics';root.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
folder=root/str(uuid.uuid4());folder.mkdir(mode=0o700)
|
||||
write(folder/'intent.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reader_sha256':digest,'read_only':True,'no_retry':True}))
|
||||
# A small launcher avoids Windows' command-line limit. The source hash is
|
||||
# generated from this closed reader, never accepted from a caller.
|
||||
launcher=r'''$ErrorActionPreference='Stop';$q=([Console]::In.ReadLine()|ConvertFrom-Json);$raw=[Convert]::FromBase64String($q.source_base64);$h=[Security.Cryptography.SHA256]::Create();try{$s=([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()};if($s-cne'READER_SHA'){throw 'Exact original partial reader'};$global:RmmPartialReaderInput=$q.input_record;&([scriptblock]::Create([Text.Encoding]::UTF8.GetString($raw)))'''.replace('READER_SHA',digest)
|
||||
write(folder/'reader.ps1',source.encode())
|
||||
try:result=access.powershell(launcher,{'source_base64':base64.b64encode(source.encode()).decode(),'input_record':{'kind':'original-public-time-profile-ad9-readonly'}},timeout=45)
|
||||
except subprocess.TimeoutExpired:
|
||||
write(folder/'timeout.json',canonical({'read_only':True,'timeout_seconds':45,'old_move_hresult_unknown':True}));raise RuntimeError('original diagnostic read timed out; no publication attempted') from None
|
||||
write(folder/'reply.json',canonical(result))
|
||||
require(result['id']==PARTIAL_ID and result['read_only'] is True and result['retry_authorized'] is False
|
||||
and result['installation_verified'] is False and result['clock_runtime_qualified'] is False,'diagnostic observation is no installation success or authority')
|
||||
write(folder/'receipt.json',canonical({'id':folder.name,'original_case':PARTIAL_ID,'reader_sha256':digest,'original_manifest_sha256':PARTIAL_MANIFEST_SHA,'reply_sha256':sha(canonical(result)),'read_only':True,'old_move_hresult_unknown':True}))
|
||||
print(json.dumps({'id':folder.name,'original_case':PARTIAL_ID,'read_only':True,'receipt_sha256':sha((folder/'receipt.json').read_bytes())}))
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare','stage','install','read','diagnose-partial'));parser.add_argument('--case');arguments=parser.parse_args()
|
||||
if arguments.action=='guards': guards();print('PASS closed public-profile source guards; no target action')
|
||||
elif arguments.action=='prepare': prepare()
|
||||
elif arguments.action=='diagnose-partial':
|
||||
require(arguments.case is None,'diagnostic is fixed to the original ad9 case');diagnose_partial()
|
||||
else: target(arguments.action,arguments.case)
|
||||
@@ -1,282 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fixed once-only passive route fixture operator. All target phases initially closed."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
import signed_clock_capture_acceptance as original
|
||||
import time_route_context as collector
|
||||
|
||||
ROOT=original.ROOT
|
||||
STATE=ROOT/'devstate/windows-time-route-native'
|
||||
QUAL=ROOT/'devstate/windows-signed-clock/time-route-fixture-qualification-3fdf513e-197b-41ab-b161-9dfc2adc94da'
|
||||
RECEIPT_SHA='fce8c42cce33a35be1ee0468c97010ac3797a713668503783e449d30ea538678'
|
||||
EXE_SHA='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'
|
||||
EXE_BYTES=19172660
|
||||
PIN=ROOT/'devstate/server-time-source-bootstrap/qualified-time-public-key.json'
|
||||
PIN_SHA='c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'
|
||||
# Root pins {id, receipt_sha256} only after the actual post-deploy collector read.
|
||||
CONTEXT_GATE={'id':'68b841a5-784f-4a34-a8a4-060b267713f0','receipt_sha256':'658fa5ffa63c6e412237f5feb718b745bb560230f17c54e437ad8bd98e9ad65b'}
|
||||
require,save,load,sha=original.require,original.save,original.load,original.sha
|
||||
|
||||
SCRIPT=r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if(!$p-or$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id){throw 'Exact route action/case'}
|
||||
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,context_base64,context_sha256,id,manifest_sha256,pin_base64'-or$p.context_sha256-cnotmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed route payload'}
|
||||
$base='C:\ProgramData\RustDiscoveryBootstrap';$root=Join-Path $base 'time-route';$controlRoot=Join-Path $base 'time-route-control';$case=Join-Path $root $p.id;$control=Join-Path $controlRoot $p.id
|
||||
$exe=Join-Path $case 'TimeRouteProbe.exe';$source=Join-Path (Join-Path $base '4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088') 'TimeRouteProbe.exe'
|
||||
function Check($path,[bool]$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Protected regular route path'};$parent=$i.Directory;if($directory){$parent=$i.Parent};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No route reparse ancestry'};$parent=$parent.Parent};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Route empty DACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route DACL'}}}
|
||||
function Get-RmmRouteBytesSha256([byte[]]$raw){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function FH($path){Check $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function WriteNew($path,[byte[]]$raw){if($raw.Length-gt32768){throw 'Route record bound'};$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($raw,0,$raw.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function Record($name,$value){WriteNew (Join-Path $control $name) ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 20 -Compress)))}
|
||||
function DirectoryNew($path){New-Item -ItemType Directory -Path $path|Out-Null;$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $a;Check $path $true}
|
||||
function ReadOwn{
|
||||
$records=[ordered]@{};if(Test-Path -LiteralPath $control){Check $control $true;foreach($name in @('stage-intent.json','stage-complete.json','run-attempt.json','process.json','exit.json','stdout.txt','stderr.txt')){$path=Join-Path $control $name;if(Test-Path -LiteralPath $path){Check $path $false;$i=Get-Item -LiteralPath $path;if($i.Length-gt32768){throw 'Bounded own control read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}}
|
||||
if(Test-Path -LiteralPath $case){Check $case $true;foreach($name in @('intent.json','report.json','positive-request.json','positive-response.json','positive-agent-result.json','tenant-mismatch-result.json','stale-connection-result.json')){$path=Join-Path $case $name;if(Test-Path -LiteralPath $path){Check $path $false;if((Get-Item -LiteralPath $path).Length-gt32768){throw 'Bounded own result read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}}
|
||||
return @{id=$p.id;read_only=$true;records=$records;manifest_sha256=$p.manifest_sha256}
|
||||
}
|
||||
Check $base $true
|
||||
if($p.action-ceq'read'){ReadOwn|ConvertTo-Json -Depth 20 -Compress;exit 0}
|
||||
$context=[Convert]::FromBase64String($p.context_base64);$pin=[Convert]::FromBase64String($p.pin_base64)
|
||||
if($context.Length-gt4096-or(Get-RmmRouteBytesSha256 $context)-cne$p.context_sha256-or$pin.Length-gt4096-or(Get-RmmRouteBytesSha256 $pin)-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Exact actual public route inputs'}
|
||||
$c=[Text.Encoding]::UTF8.GetString($context)|ConvertFrom-Json;if($c.case_id-cne$p.id){throw 'Actual context own case'}
|
||||
if($p.action-ceq'stage'){
|
||||
if((Test-Path -LiteralPath $case)-or(Test-Path -LiteralPath $control)){throw 'Original route stage exists; read only'}
|
||||
foreach($directory in @($root,$controlRoot)){if(Test-Path -LiteralPath $directory){Check $directory $true}else{DirectoryNew $directory}}
|
||||
DirectoryNew $control;Record 'stage-intent.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;once=$true}
|
||||
DirectoryNew $case
|
||||
if((FH $source)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(Get-Item -LiteralPath $source).Length-ne19172660){throw 'Exact route EXE source'}
|
||||
[IO.File]::Copy($source,$exe,$false);$f=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$f.Flush($true)}finally{$f.Dispose()}
|
||||
WriteNew (Join-Path $case 'context.json') $context;WriteNew (Join-Path $case 'time-public-key.json') $pin
|
||||
if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Actual own staged inputs'}
|
||||
Record 'stage-complete.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;staged=$true}
|
||||
@{id=$p.id;staged=$true;manifest_sha256=$p.manifest_sha256}|ConvertTo-Json -Compress;exit 0
|
||||
}
|
||||
if($p.action-cne'run'){throw 'Exact run required before process start'}
|
||||
Check $case $true;Check $control $true;Check (Join-Path $control 'stage-complete.json') $false
|
||||
$stage=Get-Content -LiteralPath (Join-Path $control 'stage-complete.json') -Raw|ConvertFrom-Json
|
||||
if($stage.id-cne$p.id-or$stage.manifest_sha256-cne$p.manifest_sha256-or$stage.context_sha256-cne$p.context_sha256-or$stage.staged-ne$true){throw 'Original completed route stage'}
|
||||
if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Immediate original route input CAS'}
|
||||
Record 'run-attempt.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;once=$true;no_retry=$true}
|
||||
$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$exe;$start.Arguments='probe '+$p.id;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true
|
||||
$process=New-Object Diagnostics.Process;$process.StartInfo=$start;if(!$process.Start()){throw 'Own route probe start failed; read only'}
|
||||
try{$held=$process.Handle;$birth=$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();Record 'process.json' @{id=$p.id;pid=$process.Id;birth=$birth;held_kernel_handle=$true;exe_sha256='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'}
|
||||
$output=$process.StandardOutput.ReadToEndAsync();$errors=$process.StandardError.ReadToEndAsync();$timedOut=!$process.WaitForExit(20000)
|
||||
if($timedOut){$process.Kill();if(!$process.WaitForExit(5000)){throw 'Own held route process exit uncertain'}}
|
||||
if(!$output.Wait(5000)-or!$errors.Wait(5000)){throw 'Own route pipe drain uncertain'};$stdout=$output.Result;$stderr=$errors.Result
|
||||
if($stdout.Length-gt32768-or$stderr.Length-gt32768){throw 'Bounded fixed route output'}
|
||||
WriteNew (Join-Path $control 'stdout.txt') ([Text.Encoding]::UTF8.GetBytes($stdout));WriteNew (Join-Path $control 'stderr.txt') ([Text.Encoding]::UTF8.GetBytes($stderr))
|
||||
Record 'exit.json' @{id=$p.id;pid=$process.Id;birth=$birth;kernel_process_exited=$process.HasExited;exit_code=$process.ExitCode;timed_out=$timedOut}
|
||||
if($timedOut-or$process.ExitCode-ne0-or$stderr.Length){throw 'Actual route probe did not complete successfully; original read only'}
|
||||
ReadOwn|ConvertTo-Json -Depth 20 -Compress
|
||||
}finally{$process.Dispose()}
|
||||
'''
|
||||
|
||||
|
||||
def guards():
|
||||
require(original.sha(ROOT/'deploy/windows/signed_clock_capture_acceptance.py')=='dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770','fixed prior witnesses')
|
||||
require("$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')" in SCRIPT
|
||||
and "if($p.action-cne'run'){throw 'Exact run required before process start'}" in SCRIPT,'no action case fallthrough')
|
||||
require(all(v not in SCRIPT for v in ('Start-Service','Stop-Service','Restart-Service','Remove-Item','Invoke-Expression','Bypass','Snapshot','TimeBegin')),'own files/process only')
|
||||
require(sha(QUAL/'receipt.json')==RECEIPT_SHA and sha(QUAL/'TimeRouteProbe.exe')==EXE_SHA
|
||||
and (QUAL/'TimeRouteProbe.exe').stat().st_size==EXE_BYTES and sha(PIN)==PIN_SHA,'exact actual qualified artifacts and public time key')
|
||||
|
||||
|
||||
def gate():
|
||||
require(isinstance(CONTEXT_GATE,dict) and set(CONTEXT_GATE)=={'id','receipt_sha256'},'ACTUAL_CONTEXT_GATE_NOT_BOUND')
|
||||
ident=CONTEXT_GATE['id'];require(str(uuid.UUID(ident))==ident,'actual canonical context case')
|
||||
folder=collector.STATE/ident;receipt=load(folder/'receipt.json')
|
||||
require(sha(folder/'receipt.json')==CONTEXT_GATE['receipt_sha256'] and receipt['id']==ident
|
||||
and receipt['collector_sha256']==sha(Path(collector.__file__)) and receipt['read_only'] is True
|
||||
and sha(folder/'response.json')==receipt['response_sha256'] and sha(folder/'context.json')==receipt['context_sha256'],
|
||||
'original actual postdeploy read context only')
|
||||
return ident,folder,receipt
|
||||
|
||||
|
||||
def prepare():
|
||||
guards();ident,context,receipt=gate();STATE.mkdir(mode=0o700,parents=True,exist_ok=True);folder=STATE/ident;folder.mkdir(mode=0o700)
|
||||
for name,path in [('TimeRouteProbe.exe',QUAL/'TimeRouteProbe.exe'),('time-public-key.json',PIN),('context.json',context/'context.json')]:original.write(folder/name,path.read_bytes())
|
||||
original.write(folder/'TimeRouteAcceptance.ps1',SCRIPT.encode())
|
||||
save(folder/'manifest.json',dict(id=ident,operator_sha256=sha(__file__),script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(),
|
||||
fixture_receipt_sha256=RECEIPT_SHA,exe_sha256=EXE_SHA,pin_sha256=PIN_SHA,context_gate=CONTEXT_GATE,
|
||||
context_sha256=sha(folder/'context.json'),context_response_sha256=receipt['response_sha256'],dependencies=original.dependencies()))
|
||||
print(json.dumps(dict(id=ident,prepared_locally=True)))
|
||||
|
||||
|
||||
def case(ident):
|
||||
require(str(uuid.UUID(ident))==ident,'original case only');folder=STATE/ident;manifest=load(folder/'manifest.json')
|
||||
require(manifest['id']==ident and manifest['operator_sha256']==sha(__file__)
|
||||
and manifest['script_sha256']==hashlib.sha256(SCRIPT.encode()).hexdigest()
|
||||
and manifest['dependencies']==original.dependencies() and sha(folder/'TimeRouteProbe.exe')==EXE_SHA
|
||||
and sha(folder/'context.json')==manifest['context_sha256'] and sha(folder/'time-public-key.json')==PIN_SHA,'exact original prepared case')
|
||||
return folder,manifest
|
||||
|
||||
|
||||
def stage_exe(access,folder):
|
||||
name='TimeRouteProbe.exe';prepare=original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name)
|
||||
observed=access.powershell(prepare,dict(sha256=EXE_SHA))
|
||||
if not observed['already_uploaded']:
|
||||
credentials=original.pipe.cb.contract.protected_json(access.root/'credentials/windows-dev-access.json');prefix=credentials['ssh_prefix']
|
||||
argv=['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]]
|
||||
target='/C:/ProgramData/RustDiscoveryBootstrap/'+EXE_SHA+'/'+name
|
||||
result=subprocess.run(argv,input=('put '+json.dumps(str(folder/name))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
|
||||
save(folder/('transfer-'+str(uuid.uuid4())+'.json'),dict(returncode=result.returncode,stdout_b64=base64.b64encode(result.stdout).decode(),stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode==0,'one exact route EXE transfer; lost reply read only')
|
||||
observed=access.powershell(prepare,dict(sha256=EXE_SHA));require(observed['already_uploaded'] is True and observed['sha256']==EXE_SHA,'actual immutable EXE stage')
|
||||
|
||||
|
||||
def validate(response,manifest):
|
||||
records=response['records'];require('report.json' in records and 'exit.json' in records,'actual report and kernel exit required')
|
||||
report=json.loads(base64.b64decode(records['report.json'],validate=True));exited=json.loads(base64.b64decode(records['exit.json'],validate=True))
|
||||
require(exited['kernel_process_exited'] is True and exited['exit_code']==0 and exited['timed_out'] is False
|
||||
and report['context_sha256']==manifest['context_sha256'] and report['server_context_evidence_sha256']==manifest['context_response_sha256']
|
||||
and report['verified'] is True and report['case_id']==response['id'] and report['public_time_pin_sha256']==PIN_SHA
|
||||
and [v['http_status'] for v in report['reports']]==[200,403,409]
|
||||
and report['reports'][0]['signature_verified'] is True and report['reports'][0]['whole_request_context_bound'] is True
|
||||
and all(report[key] is False for key in ('private_key_exported','private_key_hashed','private_key_copied_to_evidence',
|
||||
'certificate_verification_disabled','service_role_proven','trusted_clock_proven','clock_freshness_qualified','sync_ready','jobs_created','grants_created')),
|
||||
'actual passive signature/context route only, no role/clock/job claim')
|
||||
|
||||
|
||||
def run(action,ident):
|
||||
guards();folder,manifest=case(ident);access=original.CaptureAccess(original.ACCESS_ROOT)
|
||||
operation='read-'+str(uuid.uuid4()) if action=='read' else action
|
||||
require(action in ('stage','run','read'),'fixed local action')
|
||||
if action=='run':
|
||||
stage=load(folder/'stage-reply.json');proof=load(folder/'stage-preservation.json')
|
||||
require(stage.get('staged') is True and stage['id']==ident and stage['manifest_sha256']==sha(folder/'manifest.json')
|
||||
and proof['id']==ident and proof['operation_id']=='stage' and proof['action']=='stage' and proof['read_only'] is False
|
||||
and proof['operator_sha256']==sha(__file__) and proof['manifest_sha256']==sha(folder/'manifest.json')
|
||||
and proof['raw_reply']==dict(filename='stage-reply.json',sha256=sha(folder/'stage-reply.json')),'original complete linked stage before the single run')
|
||||
for name in ('server','native'):
|
||||
link=proof[name+'_witness'];require(link['filename']=='stage-'+name+'.json' and sha(folder/link['filename'])==link['sha256'],'original stage witness links')
|
||||
if action!='read':
|
||||
gate_id,context,receipt=gate();require(gate_id==ident and manifest['context_gate']==CONTEXT_GATE,'actual original sealed context gate')
|
||||
fresh=collector.rpc(access,dict(id=ident,deployment_result_sha256=receipt['deployment_result_sha256'],image=collector.IMAGE),folder)
|
||||
require(fresh==load(context/'response.json'),'actual current DB boot/generation/gateway still exact before action')
|
||||
save(folder/(operation+'-attempt.json'),dict(action=action,once=True,no_retry=True,operator_sha256=sha(__file__)))
|
||||
else:save(folder/(operation+'-intent.json'),dict(action='read',read_only=True,operator_sha256=sha(__file__)))
|
||||
before_server,before_native=original.server_closed(access),original.native_witness(access)
|
||||
baseline=folder/'baseline.json'
|
||||
if not baseline.exists():save(baseline,dict(server=before_server,native=before_native))
|
||||
original.preserved(load(baseline)['native'],before_native);require(load(baseline)['server']==before_server,'same original closed server scope')
|
||||
if action=='stage':stage_exe(access,folder)
|
||||
payload=dict(action=action,id=ident,manifest_sha256=sha(folder/'manifest.json'),context_sha256=manifest['context_sha256'],
|
||||
context_base64=base64.b64encode((folder/'context.json').read_bytes()).decode(),pin_base64=base64.b64encode((folder/'time-public-key.json').read_bytes()).decode())
|
||||
response=access.powershell(SCRIPT,payload,timeout=90)
|
||||
raw=folder/(operation+'-reply.json');save(raw,response) # raw first, before outcome/witness assertions
|
||||
after_server,after_native=original.server_closed(access),original.native_witness(access)
|
||||
require(before_server==after_server,'closed server gates and counters preserved');original.preserved(before_native,after_native)
|
||||
binding=dict(id=ident,operation_id=operation,action=action,read_only=action=='read',operator_sha256=sha(__file__),
|
||||
raw_reply=dict(filename=raw.name,sha256=sha(raw)),manifest_sha256=sha(folder/'manifest.json'))
|
||||
server=folder/(operation+'-server.json');native=folder/(operation+'-native.json')
|
||||
save(server,dict(binding,before=before_server,after=after_server));save(native,dict(binding,before=before_native,after=after_native))
|
||||
save(folder/(operation+'-preservation.json'),dict(binding,server_witness=dict(filename=server.name,sha256=sha(server)),
|
||||
native_witness=dict(filename=native.name,sha256=sha(native)),no_rmm_jobs=True,no_service_action=True))
|
||||
require(response['id']==ident and response['manifest_sha256']==sha(folder/'manifest.json'),'same original route case response')
|
||||
if action=='stage':require(response['staged'] is True,'actual complete stage')
|
||||
elif action=='run' or 'report.json' in response.get('records',{}):validate(response,manifest)
|
||||
print(json.dumps(dict(id=ident,action=action,preserved=True,completed='report.json' in response.get('records',{}),read_only=action=='read')))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('guards','prepare','stage','run','read'));p.add_argument('--case');a=p.parse_args()
|
||||
if a.action=='guards':guards();print('PASS source guards; no target call')
|
||||
elif a.action=='prepare':require(a.case is None,'actual sealed context determines own case');prepare()
|
||||
else:require(a.case is not None,'original case required');run(a.action,a.case)
|
||||
|
||||
# Direct, read-only recovery of this original staged case after the historical
|
||||
# upgrade finish reader timed out. No historical manifest or reply is rewritten.
|
||||
DIRECT_CASE='68b841a5-784f-4a34-a8a4-060b267713f0'
|
||||
DIRECT_MANIFEST='22f3bc7c143a893729f193133858696f377a84296c5843bde8b1354c1493389b'
|
||||
DIRECT_OPERATOR='a817f45b43fa15feaa24a8ec8d4eea404f0e2bcf75ff252da166aebfa63b5c55'
|
||||
|
||||
|
||||
def direct_source():
|
||||
prior=original.pipe
|
||||
checks=prior.PREFIX.split('function Check(',1)[1].split('function PrivateBackupAcl',1)[0]
|
||||
service=prior.PREFIX.split('function Service($role){',1)[1].split('function Probe(',1)[0]
|
||||
native=prior.NATIVE.split('function FileIdentity(',1)[0]
|
||||
identity=prior.NATIVE.split('function FileIdentity(',1)[1].split('function Kernel(',1)[0]
|
||||
kernel=prior.NATIVE.split('function Kernel(',1)[1].split('function ActualState',1)[0]
|
||||
metadata=prior.NATIVE.split('function FileIdentityMetadata(',1)[1].split('function SameOriginal',1)[0]
|
||||
return r'''$ErrorActionPreference='Stop';$p=$global:RmmRouteDirectPreservationPayload
|
||||
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'kind'-or$p.kind-cne'fixed-time-route-direct-preservation'){throw 'Fixed readonly observation'}
|
||||
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$sys='S-1-5-18';$admin='S-1-5-32-544'
|
||||
$agentRoot='C:\ProgramData\RustDiscovery';$agentState=Join-Path $agentRoot 'state';$helperRoot='C:\ProgramData\RustDiscoverySystem';$helperState=Join-Path $helperRoot 'state'
|
||||
$agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$helperBinary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe'
|
||||
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$helperName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
'''+'function JsonEqual($a,$b){return(($a|ConvertTo-Json -Depth 40 -Compress)-ceq($b|ConvertTo-Json -Depth 40 -Compress))}\n'+'function Check('+checks+'function Service($role){'+service+'\n'+native+'function FileIdentity('+identity+'function Kernel('+kernel+'function FileIdentityMetadata('+metadata+r'''
|
||||
$services=[ordered]@{};$kernels=[ordered]@{};foreach($role in @('agent','helper')){$s=Service $role;if($s.state-cne'Running'){throw 'Both original services running'};$h=[RmmPipeNative]::Open([int]$s.pid);try{$kernels[$role]=Kernel $role $s $h;if(!(JsonEqual $s (Service $role))){throw 'Actual service race'}}finally{$h.Dispose()};$services[$role]=$s}
|
||||
$files=[ordered]@{};foreach($entry in @(@('agent',$agentBinary),@('helper',$helperBinary),@('settings',(Join-Path $helperRoot 'helper.json')),@('pin',(Join-Path $helperRoot 'agent-pin.json')),@('config',(Join-Path $agentRoot 'config.json')),@('ca',(Join-Path $agentRoot 'server-ca.pem')),@('identity',(Join-Path $agentState 'identity.json')),@('certificate',(Join-Path $agentState 'device.pem')))){$files[$entry[0]]=FileIdentity $entry[1] ($entry[0]-in@('ca','identity','certificate'))}
|
||||
$files.private_key=FileIdentityMetadata (Join-Path $agentState 'device.key')
|
||||
$db=[ordered]@{};foreach($entry in @(@('telemetry',(Join-Path $agentState 'telemetry.sqlite')),@('helper',(Join-Path $helperState 'ledger.sqlite')),@('lock',(Join-Path $helperState 'executor.lock')))){$m=FileIdentityMetadata $entry[1];$i=Get-Item -LiteralPath $entry[1];$db[$entry[0]]=@{volume_serial=$m.volume_serial;file_id=$m.file_id;creation_filetime=$i.CreationTimeUtc.ToFileTimeUtc().ToString();acl_sha256=$m.acl_sha256}}
|
||||
@{files=$files;services=$services;kernels=$kernels;database_identities=$db;read_only=$true;private_key_read=$false;database_content_read=$false;services_changed=$false}|ConvertTo-Json -Depth 25 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def direct_witness(access,baseline):
|
||||
source=direct_source();require(all(v not in source for v in ('Start-Service','Stop-Service','WriteNew','PrivateBackupAcl','function Probe','function State')),'direct observation has no old probe or mutation')
|
||||
digest=hashlib.sha256(source.encode()).hexdigest()
|
||||
launcher=r'''$ErrorActionPreference='Stop';$q=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
$raw=[Convert]::FromBase64String($q.source_base64);$h=[Security.Cryptography.SHA256]::Create();try{$sha=([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}
|
||||
if($sha-cne'FIXED_SOURCE_SHA'){throw 'Exact direct reader source'}
|
||||
$global:RmmRouteDirectPreservationPayload=$q.payload
|
||||
& ([scriptblock]::Create([Text.Encoding]::UTF8.GetString($raw)))
|
||||
'''.replace('FIXED_SOURCE_SHA',digest)
|
||||
value=access.powershell(launcher,dict(source_base64=base64.b64encode(source.encode()).decode(),payload=dict(kind='fixed-time-route-direct-preservation')),timeout=45)
|
||||
save(STATE/DIRECT_CASE/('direct-observed-'+str(uuid.uuid4())+'.json'),value)
|
||||
old=baseline['native'];stable=old['stable']
|
||||
require(value['read_only'] is True and value['private_key_read'] is False and value['database_content_read'] is False
|
||||
and value['files']==stable['files'],'actual original public file bytes/FileIDs/ACLs and private-key metadata')
|
||||
for role,name in [('agent','service'),('helper','helper_service')]:
|
||||
require(value['services'][role]==stable[name] and value['kernels'][role]==stable[role+'_kernel'],'same running original service/kernel PID/birth/image/account')
|
||||
telemetry=value['database_identities']['telemetry'];old_id=old['journal']['database_file_id'];old_birth=old['journal']['database_creation']
|
||||
require(int(telemetry['volume_serial'])&0xffffffff==old_id['volume']
|
||||
and int.from_bytes(bytes.fromhex(telemetry['file_id'])[:8],'little')==((old_id['high']<<32)|old_id['low'])
|
||||
and int(telemetry['creation_filetime'])==((old_birth['high']<<32)|old_birth['low']),'original telemetry native identity/creation')
|
||||
value['historical_helper_metadata_comparison']={}
|
||||
for name,previous in [('helper',stable['helper_witness']['helper_ledger']['file']),('lock',stable['helper_witness']['executor_lock'])]:
|
||||
current=value['database_identities'][name]
|
||||
value['historical_helper_metadata_comparison'][name]=dict(volume_equal=current['volume_serial']==previous['file_id']['volume_serial'],file_id_equal=current['file_id']==previous['file_id']['id_hex'],creation_equal=current['creation_filetime']==previous['creation_filetime'],acl_digest_equal=current['acl_sha256']==previous['acl_sha256'],historical_probe_not_repeated=True)
|
||||
return value
|
||||
|
||||
|
||||
def direct(action):
|
||||
require(action in ('run-direct','read-direct'),'fixed passive recovery phase');guards()
|
||||
folder=STATE/DIRECT_CASE;manifest=load(folder/'manifest.json');baseline=load(folder/'baseline.json')
|
||||
require(sha(folder/'manifest.json')==DIRECT_MANIFEST and manifest['operator_sha256']==DIRECT_OPERATOR
|
||||
and manifest['context_gate']==CONTEXT_GATE and manifest['dependencies']==original.dependencies()
|
||||
and sha(folder/'TimeRouteProbe.exe')==EXE_SHA and sha(folder/'time-public-key.json')==PIN_SHA
|
||||
and sha(folder/'context.json')==manifest['context_sha256'] and sha(folder/'TimeRouteAcceptance.ps1')==hashlib.sha256(SCRIPT.encode()).hexdigest(),'fixed original staged case only')
|
||||
stage=load(folder/'stage-reply.json');require(stage==dict(id=DIRECT_CASE,manifest_sha256=DIRECT_MANIFEST,staged=True),'actual original stage response')
|
||||
original.original_main();access=original.CaptureAccess(original.ACCESS_ROOT)
|
||||
operation='run-direct' if action=='run-direct' else 'read-direct-'+str(uuid.uuid4())
|
||||
if action=='run-direct':
|
||||
require(not (folder/'run-attempt.json').exists(),'original automatic run was never attempted')
|
||||
gate_id,context,receipt=gate();require(gate_id==DIRECT_CASE,'same actual context gate')
|
||||
require(collector.rpc(access,dict(id=DIRECT_CASE,deployment_result_sha256=receipt['deployment_result_sha256'],image=collector.IMAGE),folder)==load(context/'response.json'),'actual context still exact')
|
||||
intent_name=operation+'-intent.json'
|
||||
if (folder/intent_name).exists():intent_name=operation+'-preflight-'+str(uuid.uuid4())+'.json'
|
||||
save(folder/intent_name,dict(action=action,operator_sha256=sha(__file__),original_manifest_sha256=DIRECT_MANIFEST,
|
||||
direct_source_sha256=hashlib.sha256(direct_source().encode()).hexdigest(),read_only=action=='read-direct',historical_stage_witness_timeout_retained=True))
|
||||
before_server=original.server_closed(access);require(before_server==baseline['server'],'same closed server original counts and flags')
|
||||
before=direct_witness(access,baseline);save(folder/(operation+'-before.json'),before)
|
||||
payload=dict(action='run' if action=='run-direct' else 'read',id=DIRECT_CASE,manifest_sha256=DIRECT_MANIFEST,context_sha256=manifest['context_sha256'],context_base64=base64.b64encode((folder/'context.json').read_bytes()).decode(),pin_base64=base64.b64encode((folder/'time-public-key.json').read_bytes()).decode())
|
||||
if action=='run-direct':save(folder/'run-direct-start-intent.json',dict(action='run',once=True,no_retry=True,operator_sha256=sha(__file__),direct_before_sha256=sha(folder/(operation+'-before.json'))))
|
||||
try:response=access.powershell(SCRIPT,payload,timeout=45)
|
||||
except subprocess.TimeoutExpired:
|
||||
save(folder/(operation+'-timeout.json'),dict(error='SSH_TIMEOUT_45_SECONDS',result_unknown=True,repeat_run=False));raise RuntimeError('passive response missing; original read only') from None
|
||||
save(folder/(operation+'-reply.json'),response)
|
||||
after_server=original.server_closed(access);after=direct_witness(access,baseline)
|
||||
save(folder/(operation+'-after.json'),after);require(before==after and before_server==after_server,'actual service/PKI/config/native DB identities and closed server counts preserved')
|
||||
save(folder/(operation+'-preservation.json'),dict(id=DIRECT_CASE,operation=operation,operator_sha256=sha(__file__),original_manifest_sha256=DIRECT_MANIFEST,
|
||||
raw_reply_sha256=sha(folder/(operation+'-reply.json')),before_sha256=sha(folder/(operation+'-before.json')),after_sha256=sha(folder/(operation+'-after.json')),
|
||||
server_before=before_server,server_after=after_server,direct_native_preserved=True,old_finish_timeout_remains=True,no_jobs_created=True,no_service_action=True))
|
||||
require(response['id']==DIRECT_CASE and response['manifest_sha256']==DIRECT_MANIFEST,'actual own original reply')
|
||||
if action=='run-direct' or 'report.json' in response.get('records',{}):validate(response,manifest)
|
||||
print(json.dumps(dict(id=DIRECT_CASE,operation=operation,verified='report.json' in response.get('records',{}),preserved=True)))
|
||||
@@ -1,101 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One fixed post-deployment public context read. No SQL/HTTP writes or secrets."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
import signed_clock_capture_acceptance as original
|
||||
|
||||
ROOT=original.ROOT
|
||||
STATE=ROOT/'devstate/windows-time-route-context'
|
||||
# Root binds the actual successful deployment result SHA after its separate read.
|
||||
DEPLOYMENT_RESULT_SHA='3017634f101ee8aff62988f195ccb3a7a8b9e03eaa48b8fb339af9ceb3ad2b4b'
|
||||
IMAGE='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611'
|
||||
BINDING_SHA='05c5678fed81e0a2a7cdaaeaf18c64f9837cfbe76c140699a47306c9b4598a18'
|
||||
require,save,load,sha=original.require,original.save,original.load,original.sha
|
||||
|
||||
|
||||
def server_read(p):
|
||||
import hashlib,json,os,stat,subprocess,uuid
|
||||
from pathlib import Path
|
||||
def need(v):
|
||||
if not v:raise RuntimeError('FIXED_READONLY_CONTEXT_INCOMPLETE')
|
||||
need(set(p)=={'id','deployment_result_sha256','image'})
|
||||
need(str(uuid.UUID(p['id']))==p['id'] and isinstance(p['deployment_result_sha256'],str) and len(p['deployment_result_sha256'])==64
|
||||
and all(v in '0123456789abcdef' for v in p['deployment_result_sha256'])
|
||||
and p['image']=='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611')
|
||||
path=Path('/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/continue-backend-v1/result.json')
|
||||
metadata=path.lstat();need(stat.S_ISREG(metadata.st_mode) and metadata.st_uid==0 and metadata.st_nlink==1
|
||||
and stat.S_IMODE(metadata.st_mode)==0o600 and metadata.st_size<=65536)
|
||||
def identity(m):return(m.st_dev,m.st_ino,m.st_mode,m.st_uid,m.st_gid,m.st_nlink,m.st_size,m.st_mtime_ns,m.st_ctime_ns)
|
||||
raw=path.read_bytes();need(identity(path.lstat())==identity(metadata) and hashlib.sha256(raw).hexdigest()==p['deployment_result_sha256'])
|
||||
deployed=json.loads(raw);need(deployed['deployed'] is True and deployed['rmm_jobs_created'] is False
|
||||
and deployed['approvals_created'] is False and deployed['gateway_only_readonly_broker_mount'] is True)
|
||||
def command(args,data=None):
|
||||
r=subprocess.run(args,input=data,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=10)
|
||||
need(r.returncode==0 and len(r.stdout)<=65536 and len(r.stderr)<=65536);return r.stdout
|
||||
def gateway():
|
||||
value=json.loads(command(['docker','inspect','rust-discovery-server-gateway-1','--format',
|
||||
'[{{json .Id}},{{json .Image}},{{json .Config.User}},{{json .State.Running}},{{json .HostConfig.PidMode}}]']))
|
||||
need(value[1]==p['image'] and value[2]=='10001:10001' and value[3] is True and value[4]!='host');return value
|
||||
boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip();need(str(uuid.UUID(boot))==boot)
|
||||
before=gateway()
|
||||
query=("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL statement_timeout='3s'; "
|
||||
"SELECT json_build_object('tenant_id',tenant_id,'agent_id',agent_id,'asset_id',asset_id,"
|
||||
"'enrollment_generation',enrollment_generation,'assignment_generation',assignment_version,"
|
||||
"'connection_generation',connection_generation,'windows_boot_id',connection_boot_id,'capabilities',capabilities) "
|
||||
"FROM agent_installations WHERE tenant_id='11111111-1111-4111-8111-111111111111' "
|
||||
"AND agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3' AND revoked_at IS NULL; COMMIT;")
|
||||
raw=command(['docker','exec','-i','rust-discovery-server-postgres-1','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],query.encode())
|
||||
row=json.loads(raw)
|
||||
need(row['tenant_id']=='11111111-1111-4111-8111-111111111111' and row['agent_id']=='63ea15b2-0643-403d-b5b4-cba1288dbea3'
|
||||
and row['asset_id']=='a176520e-8a91-4e93-a78b-8e7620f430e0' and row['enrollment_generation']==1
|
||||
and row['assignment_generation']==1 and type(row['connection_generation']) is int and row['connection_generation']>1
|
||||
and str(uuid.UUID(row['windows_boot_id']))==row['windows_boot_id'] and 'windows.base/1' in row['capabilities'])
|
||||
need(before==gateway() and Path('/proc/sys/kernel/random/boot_id').read_text().strip()==boot)
|
||||
return dict(profile='rmm.windows.time-route.actual-public-context.v1',id=p['id'],server_boot_id=boot,
|
||||
installation=row,gateway=before,deployment_result_sha256=p['deployment_result_sha256'],sql_read_only=True,secrets_read=False)
|
||||
|
||||
|
||||
def rpc(access,payload,folder):
|
||||
# Same strict Main SSH configuration parser as CaptureAccess.server; never source/eval.
|
||||
cloud=original.pipe.u.transport.cloud
|
||||
cfg=cloud.bootstrap.access.load_config(access.root/'credentials/server.conf')
|
||||
prefix=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes',
|
||||
'-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
|
||||
code=inspect.getsource(server_read)+'\nimport json\nprint(json.dumps(server_read('+repr(payload)+')))\n'
|
||||
r=subprocess.run(prefix,input=code.encode(),capture_output=True,timeout=30)
|
||||
save(folder/('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=r.returncode,stdout_b64=base64.b64encode(r.stdout).decode(),stderr_b64=base64.b64encode(r.stderr).decode()))
|
||||
require(r.returncode==0 and len(r.stdout)<=65536,'bounded actual context transport; original read only')
|
||||
return json.loads(r.stdout,object_pairs_hook=original.pipe.cb.contract.strict_object)
|
||||
|
||||
|
||||
def collect():
|
||||
require(type(DEPLOYMENT_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}',DEPLOYMENT_RESULT_SHA) is not None,'ACTUAL_DEPLOYMENT_GATE_NOT_BOUND')
|
||||
original.original_main();STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700)
|
||||
payload=dict(id=ident,deployment_result_sha256=DEPLOYMENT_RESULT_SHA,image=IMAGE)
|
||||
save(folder/'intent.json',dict(id=ident,collector_sha256=sha(__file__),read_only=True,payload=payload))
|
||||
response=rpc(original.CaptureAccess(original.ACCESS_ROOT),payload,folder)
|
||||
save(folder/'response.json',response)
|
||||
require(response['id']==ident and response['sql_read_only'] is True and response['secrets_read'] is False,'actual original public context only')
|
||||
context=dict(schema_version=1,case_id=ident,connection_generation=response['installation']['connection_generation'],
|
||||
windows_boot_id=response['installation']['windows_boot_id'],server_boot_id=response['server_boot_id'],
|
||||
server_context_evidence_sha256=sha(folder/'response.json'),binding_sha256=BINDING_SHA)
|
||||
save(folder/'context.json',context)
|
||||
save(folder/'receipt.json',dict(id=ident,collector_sha256=sha(__file__),deployment_result_sha256=DEPLOYMENT_RESULT_SHA,
|
||||
response_sha256=sha(folder/'response.json'),context_sha256=sha(folder/'context.json'),gateway=response['gateway'],read_only=True))
|
||||
print(json.dumps(dict(id=ident,read_only=True,receipt_sha256=sha(folder/'receipt.json'),context_sha256=sha(folder/'context.json'))))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('collect','guards'));a=parser.parse_args()
|
||||
if a.action=='collect':collect()
|
||||
else:
|
||||
require('READ ONLY' in inspect.getsource(server_read) and 'UPDATE ' not in inspect.getsource(server_read),'fixed SQL read only')
|
||||
print('PASS source guards; no target action')
|
||||
@@ -1,125 +0,0 @@
|
||||
# Normaler passiver Releasekatalogcheck
|
||||
|
||||
Stand2026-11-15. Der Linux-Agent ruft den vorhandenen Releasekatalog jetzt aus
|
||||
seinem normalen `queue_update_observation`-Pfad auf. Dies ist ein passiver
|
||||
Metadatencheck, kein Artefaktbezug, Staging, Job oder ausgeführtes Selbstupdate.
|
||||
|
||||
## Aufruf, Vertrauen und Grenzen
|
||||
|
||||
Der Collector startet höchstens einen Hintergrundrequest. Erfolgreiche Checks
|
||||
werden nach24h erneuert; fehlende Konfiguration oder Fehler frühestens nach60s.
|
||||
35s Gesamtfrist und64KiB Antwortlimit gelten zusätzlich zu den vorhandenen
|
||||
mTLS-/HTTPgrenzen. Heartbeats, Cancel und SignedSync warten nicht auf HTTP.
|
||||
Die URL bleibt `/agent/v1/releases/current` am bereits konfigurierten TLSnamen;
|
||||
der vorhandene Connectoverride ändert ausschließlich das TCPziel. Keine
|
||||
Weiterleitung, Umgebungsproxy-, System-CA- oder Jobsigner-Ersatzannahme.
|
||||
|
||||
Verwendet werden ausschließlich die bereits vorgesehenen geschützten öffentlichen
|
||||
Dateien `/etc/rmm-agent-updater/policy.json`, `keyring.json` und
|
||||
`/var/lib/rmm-agent-updater/installed-record.json`. Eigentümer/Eltern sindRoot,
|
||||
keine Symlinks oder gruppen-/weltbeschreibbaren Pfade; reguläre Dateien,
|
||||
ein Hardlink, feste Größenlimits. Gehaltene FD-/Inode-/Metadaten-/Rawbytezeugen
|
||||
werden nach dem Request erneut geprüft. Es entstehen keine lokalen Dateien,
|
||||
keine Schlüsselprovisionierung und keine geänderten Dateirechte.
|
||||
|
||||
Policyidentität muss zum vorhandenen Gerätebinding passen. Separater
|
||||
Releasekeyring, aktuelle Widerrufe/Sequenzbereiche, echte Baseline- und
|
||||
Releasesignaturen, Linuxplattform, qualifizierter Protokoll-/Statevertrag,
|
||||
Updaterversion, Fristen und unveränderter Floor werden unabhängig geprüft.
|
||||
Serverzeit und die zusätzliche unsignierte Manifestansicht ersetzen keine
|
||||
lokale TrustedClock oder signierten Originalbytes; beide Manifestansichten
|
||||
müssen übereinstimmen. Fehlende Anker ergeben `not_configured`, Transport-/TLS-/
|
||||
Prüfprobleme `unavailable`; gültige Metadaten ergeben `available` oder `current`.
|
||||
|
||||
Dieser enge Erstanschluss akzeptiert als Flooranker ausschließlich die exakten
|
||||
separat signierten Bootstrap-InstalledRecordbytes. Ein späterer `Updated`-Record
|
||||
benötigt die noch fehlende unabhängig authentisierte read-only Fullhelper-
|
||||
Historybeobachtung; bloßes Parsen der neueren Recorddatei erzeugt keine
|
||||
Vertrauens- oder Floorfreigabe. Eine tatsächliche geschützte Konfiguration muss
|
||||
für den unprivilegierten Agent lesbar provisioniert sein. Unlesbare Dateien
|
||||
bleiben ehrlich unavailable; dieser Code lockert keine ACL.
|
||||
|
||||
## Übertragung und Darstellung mit älteren Servern
|
||||
|
||||
Der unveränderte `agent.update`-Snapshot erhält **kein zusätzliches Top-Level-
|
||||
Feld**. Seine qualifizierte Vorgänger-/Fullpreview bleibt `not_configured`;
|
||||
Katalogmetadaten sind keine `CandidatePreview` und eröffnen keine Check-/Applycap.
|
||||
|
||||
Der gespeicherte Katalogbericht wird ausschließlich beim ohnehin geplanten
|
||||
normalen Linuxinventar als begrenzte bestehende Unterbeobachtung
|
||||
`linux.agent_update.catalog` übertragen. Kein zusätzlicher Basiscollect wird
|
||||
angefordert. Dieser `linux.base`-/`observations`-Vertrag wird bereits von älteren
|
||||
Servern angenommen; kein neues Protobuftag und keine neue Servercap sind nötig.
|
||||
Die äußere Beobachtungszeit bezeichnet das Lesen des Caches. Das innere
|
||||
`checked_at` bleibt die tatsächliche ursprüngliche Checkzeit und wird beim
|
||||
Übertragen nicht erneuert. Über72h alte Cachewerte werden nicht neu angehängt.
|
||||
|
||||
Der aktuelle Domain-Ingest validiert zusätzlich den bekannten Berichtstyp,
|
||||
Qualität, Zeit, Kandidatenform und geschlossene Feldmenge. Altclients ohne diese
|
||||
Beobachtung bleiben gültig. Die bestehende tenantgebundene Inventoryspeicherung
|
||||
und Geräte-API transportieren dieselben geprüften Daten. Die WebUI zeigt Status,
|
||||
echten Checkzeitpunkt, spätere Cachelesezeit und gegebenenfalls Version/Hash als
|
||||
Text. Sie erzeugt keine Requests oder Bedienung zur Ausführung aus dem Bericht.
|
||||
Gemeinsame synthetische Codecfixture:
|
||||
`tests/agent_update/catalog-check-inventory.json`.
|
||||
|
||||
## Tatsächliche lokale Prüfungen
|
||||
|
||||
Im vorhandenen isolierten Rust1.99.1-Buildcontainer, Netzwerk aus:
|
||||
|
||||
```text
|
||||
cargo test --release --locked --offline -p rmm-agent -p rmm-domain --all-targets
|
||||
cargo clippy --locked --offline -p rmm-agent -p rmm-domain --all-targets -- -D warnings
|
||||
cargo fmt -p rmm-agent -p rmm-domain --check
|
||||
```
|
||||
|
||||
Abschließend89Tests bestanden,0Fehler/ignorierte/gefilterte im gesamten Lauf
|
||||
(Agentbinary32, weitere Agentintegration34, Domain23). Clippy und Formatcheck
|
||||
bestanden. Web55/55 und Typecheck bestanden. Die sechs gezielten neuen Fälle
|
||||
enthalten echte synthetische Ed25519-Baseline-/Releasebytes und einen tatsächlich
|
||||
laufenden lokalen mTLS-Testserver mit eigener CA/Geräteidentität: fester Pfad,
|
||||
Clientzertifikat, Antwort-/Redirect-/Größenverweigerung, Floor/Protokoll/Schema/
|
||||
Ablauf/Keywiderruf, fehlender Anker, falsche Baseline und unzulässige Recordbytes.
|
||||
Der Wirefall durchläuft echte Protobufbytes bis zum tatsächlichen
|
||||
`validate_for_scope`; UI und Rust benutzen dieselbe statische Datenfixture.
|
||||
|
||||
Zusätzlich wurde exakt der positive Kompatibilitätsfall mit dem ursprünglich
|
||||
unveränderten Ingestvalidator aus `c1d8eea` als privatem Datei-Mount ausgeführt:
|
||||
1/1 bestanden. Nach diesem Altvalidatorlauf schlug ein nachfolgender Negativfall
|
||||
zunächst fehl. Nach gezieltem Bereinigen der beiden betroffenen Pakete im eigenen
|
||||
Buildcache und vollständigem Neubuild bestand der gesamte89er-Lauf. Die
|
||||
Altvalidator-, erste Fehler- und abschließenden Logs bleiben getrennt erhalten;
|
||||
der fehlgeschlagene Lauf ist kein Erfolgsbeleg. Ein erster unbenutzter Import
|
||||
wurde ohne Warnungsunterdrückung korrigiert.
|
||||
|
||||
Der öffentliche Datei-Guardtest benötigt keinRoot: Unprivilegiert beweist er die
|
||||
Verweigerung des eigenen unprivilegierten/beschreibbaren Pfads. Nur der gesonderte
|
||||
lokale Rootlauf prüft zusätzlich ein eigenes geschütztes positives Dateifixture.
|
||||
Keine ungekennzeichnete Rootpflicht im neuen Test. Lokale Belege:
|
||||
`devstate/updater-passive-catalog-d86dc473-3e5f-48d4-a196-3a0d618a8e4e/`.
|
||||
|
||||
## Tatsächliche Cloud-Linux-Qualifikation
|
||||
|
||||
Root führte auf der festgelegten Cloud-Linux-Test-VM am2026-11-15 um13:07:09UTC
|
||||
exakt die sechs `agent_update_catalog::`-Fälle alsUID65534 aufx86-64 aus:
|
||||
6bestanden,0Fehler,0ignorierte,26übrige Tests bewusst gefiltert, Exit0,
|
||||
0stderr-Bytes. Der unprivilegierte Datei-Verweigerungszweig ist hierbei geprüft;
|
||||
der privilegierte positive Dateizweig stammt ausschließlich aus dem lokalen
|
||||
Rootlauf. mTLS verwendet auch auf der VM nur den eigenen Loopback-Testserver.
|
||||
Dies ist kein Katalogabruf durch den installierten Produktagenten gegen den
|
||||
Internetserver, keine Clock-/Fullhelper-/Applyqualifikation und kein Windowsbeleg.
|
||||
|
||||
Exakte Testbinary-SHA256:
|
||||
`e8fc4249db06510b6b680f5ddf7e1d539305c54741d1dea2fdc348883f205956`.
|
||||
Erhaltener privater nativer Beleg:
|
||||
`devstate/updater-passive-catalog-linux/4f3e5a4b-98a9-4acf-9106-dcdd4d5d1823/result.json`,
|
||||
SHA256 `332c8903506bf17fa8c9a9a0f512bb64ad82867513d2885359a54a80e4750e6d`.
|
||||
|
||||
## Nächster tatsächlicher Lieferweg
|
||||
|
||||
Noch offen sind der qualifizierte read-only Fullobserver für aktuelle
|
||||
Vorgänger-/Pin-/Historypreview, die normale unverbrauchte Fulladmission,
|
||||
Agent-/Helper-Artefaktstaging vor Handoff, stabiler Updaterbootstrap und der
|
||||
vollständige dauerhafte Rückweg. Agent `supported/accept` und Fullpolicy geben
|
||||
weiterhin keinen Updatejob frei. Es wurde kein Agent installiert, Dienst
|
||||
geändert, Code getauscht, Job angelegt oder genehmigt. Notebook nur Entwicklung.
|
||||
@@ -1,108 +0,0 @@
|
||||
# Linux-Readercensus: lokaler Quellenstand und geplanter nativer Nachweis
|
||||
|
||||
Stand2026-11-15, Spezifikation1.22. Keine Zielinstallation, Dienständerung,
|
||||
RMM-Ausführung oder Applyabnahme wurde in diesem Arbeitsschritt vorgenommen.
|
||||
Die WebUI-Genehmigungsgrenze bleibt unverändert.
|
||||
|
||||
Registry und Census sind mit der vorhandenen Worker-Enginequelle verbunden.
|
||||
Die Registry bindet Originalrohbytes, Bootstrapreceipt, Readervertrag,
|
||||
Hostnamespaces und exakte Unit-/Dropinkomposition. Aktuelle TGIDs und sämtliche
|
||||
Task-FD-Tabellen werden begrenzt und erneut auf Identität geprüft; auch eine
|
||||
Datei mit geschlossenem FD bleibt über ihren mmap-Inode ein Reader. Unbekannte,
|
||||
unlesbare, wechselnde oder unvollständige Beobachtungen verweigern. Fremde
|
||||
Cmdlines, Umgebungen und map-Pfade werden nicht ausgegeben.
|
||||
|
||||
Der vorhandene Root-Executorflock und die ursprüngliche Agent-Singletonsperre
|
||||
bleiben beide unter dem nicht frei konstruierbaren `ClosedReaders`-Beleg gehalten,
|
||||
bevor der Updater SQLite öffnet. Der Readervertrag fordert außerdem den
|
||||
Roothelperflock vor seinen SQLiteöffnungen und jeder SQL-/Effektoperation und
|
||||
die Agent-Sperre lebenslang vor beiden Agentdatenbanken. Dies ist kein globales
|
||||
Versprechen über zukünftige privilegierte Fremdprozesse.
|
||||
|
||||
## Tatsächlich lokal geprüft
|
||||
|
||||
Im isolierten Offline-Rustcontainer, Quellmount read-only, unveränderte
|
||||
Docker-Seccomp-Policy, eigene tmpfs für `/run`, `/tmp` und `/var/lib`:
|
||||
|
||||
- Locked all-targets Check, Release-Link, Clippy `-D warnings`, Formatcheck: PASS.
|
||||
- Vollständige Release-Workerliste10, tatsächlich10bestanden,0Fehler,
|
||||
0ignoriert,0gefiltert.
|
||||
- Die Prozessfixtures belegen bestehende FDs, anschließend mmap nach FDclose
|
||||
sowie einen Reader in einer privaten FD-Tabelle eines einzelnen Threads.
|
||||
Der TGID-only-Gegenfall findet diesen Threadreader ausdrücklich nicht;
|
||||
die vollständige Taskprüfung findet ihn.
|
||||
|
||||
Der erste Lauf unter `reader-census-ba31b221-79c4-4702-b6d6-09bb94bba7fc`
|
||||
bestand9/10. Der eigene Threadfixture wurde am Docker-Seccomp-Verbot für
|
||||
`unshare(CLONE_FILES)` mit EPERM abgewiesen. Ausschließlich im Testfixture wurde
|
||||
stattdessen `close_range(UINT_MAX,UINT_MAX,CLOSE_RANGE_UNSHARE)` verwendet:
|
||||
die gleiche eigene FD-Tabellenseparation, ohne eine tatsächlich mögliche
|
||||
FDnummer zu schließen. Keine Sandboxregel, Capability oder Produktionsprüfung
|
||||
wurde gelockert. Die Produktionsbytes vor `#[cfg(test)]` blieben identisch.
|
||||
Die Semantik folgt [close_range(2)](https://man7.org/linux/man-pages/man2/close_range.2.html).
|
||||
Der ursprüngliche Fehlerbeleg bleibt erhalten.
|
||||
|
||||
Finaler eingefrorener Privatfall:
|
||||
`devstate/agent-updater-worker/reader-census-final-da31051b-269f-4fb5-947d-94c8ad162c2a/`.
|
||||
Er enthält71Originalinputs mit Vor-/Nachhashprüfung, alle Logs und das tatsächlich
|
||||
lokal ausgeführte Release-Test-ELF. Receipt SHA256
|
||||
`9020992e888d0b22e71db88cab78f255e273be2a4a7856d43616b387c36c74ae`,
|
||||
Inputs SHA256 `382714b09349e448441345abbac6d99c0d523e98bdabaa78290b400768bac8f7`,
|
||||
ELF7.888.096Bytes/SHA256
|
||||
`e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304`.
|
||||
|
||||
## Geplant, nicht ausgeführt: zwei Cloud-Linux-Prozessguards
|
||||
|
||||
`deploy/updater_reader_census_linux_acceptance.py` ist lokal vorbereitet im
|
||||
Originalfall `168a4171-dbe3-46ef-8978-850797d0625c`. Vor Zielausführung muss Root
|
||||
seinen unabhängigen Runnerreview abschließen. Keine Zugangsdaten wurden für
|
||||
Prepare gelesen, kein Zielaufruf vorgenommen.
|
||||
|
||||
Der Runner prüft zuerst die vollständige Liste aller10Tests des exakt gebundenen
|
||||
ELF. Anschließend läuft ausschließlich der feste Filter `census_process::tests::`:
|
||||
|
||||
- `actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths`
|
||||
- `private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe`
|
||||
|
||||
Erforderlich sind2bestanden und8gefiltert. Die anderen acht Tests dürfen auf der
|
||||
VM nicht laufen: Einige lokale Fixtures verwenden feste Produktzustandspfade.
|
||||
Die zwei ausgewählten Tests verwenden nur eigene Create-once-UUIDdateien unter
|
||||
`/run`, eigene FDs, eigenen mmap und einen eigenen Fixturethread. Keine SQLopen,
|
||||
Jobs oder Dienststeuerung. Der Runner läuft als Root mit NoNewPrivileges und
|
||||
führt nach einmaligem Eintritt keine Wiederholung aus. Nach verlorener Antwort
|
||||
ist ausschließlich Read des Originalfalls zulässig.
|
||||
|
||||
Vorher/Nachher werden Boot, Ubuntu24.04/x86-64, drei bekannte Dienstgenerationen
|
||||
mit Konten/Images, geschlossener APT-Helfer, vier geschützte Control-Dateien,
|
||||
drei DB-Identitäten sowie ursprünglicher Root- und Agentlock verglichen.
|
||||
Control-Bytes sind gehasht; bei den laufenden DBs werden Identitäten geprüft,
|
||||
keine Bytegleichheit oder vollständige SQL-Historie behauptet. Der begrenzte
|
||||
Prozessnachweis ersetzt weder einen kompletten Hostcensus noch native
|
||||
Full-/Updaterdienstkontexte oder einen Updatejob.
|
||||
|
||||
## Weiterhin offen
|
||||
|
||||
Extern qualifizierte kompatible Bootstrapregistry und geschützter Hostkontext,
|
||||
native Dienst-/Namespace-/Capabilitykontexte, ursprüngliche Full-Admission und
|
||||
Runtimeentrypoint, Staging-/Downloadproducer, gültige passive Updatebeobachtung,
|
||||
Unknown-only-Recordnamespace-Adjudikation, ein vor dem ersten Apply lesbarer
|
||||
V2-Rollbackvertrag sowie tatsächlicher WebUI-genehmigter Linux-Apply mit
|
||||
Health-/Erhaltungsnachweis. V1-Restore bleibt deny. Kein erfolgreicher nativer
|
||||
Apply und keine fertige Updaterbereitschaft folgen aus diesen lokalen Guards.
|
||||
|
||||
## Tatsächlich auf Cloud-Linux ausgeführt
|
||||
|
||||
Originalfall `168a4171-dbe3-46ef-8978-850797d0625c`: vor Ausführung volle
|
||||
10er-Liste verglichen, danach genau beide Prozesscensus-Guards tatsächlich
|
||||
als UID0 bestanden;2PASS/0failed/ignored,8andere ausdrücklich gefiltert.
|
||||
Execute-Receipt
|
||||
`d6bdda0bddac74f9364fa6ec3287ed0cfa9964ae02a98cc174e95929dc94f9d5`.
|
||||
Separater Originalrückabruf bestätigte das Ergebnis und erhaltene aktuelle
|
||||
Runtime-/Control-/State-/Lockidentitäten, Receipt
|
||||
`8cbe7f4d79c238e3ad73a9c7152dcb415decbeeb1a8a1691fcc43ae4ee6c6a47`.
|
||||
|
||||
Die eigenen kurzlebigen Prozess-/Thread-/FD-/mmap-Fixtures wurden geprüft;
|
||||
keine RMM-Dienste gesteuert, keine Projekt-SQLite geöffnet oder Agentdatei
|
||||
ersetzt. Dieser Nachweis qualifiziert weder den vollständigen Host-/
|
||||
Dienstcensus noch Admission, Apply, Record-Unknown-Adjudikation oder Rollback.
|
||||
Die zuvor genannten offenen Gates bleiben offen.
|
||||
@@ -1,108 +0,0 @@
|
||||
# Geschützte Linux-Readerregistry: Quellenbaustein
|
||||
|
||||
Stand2026-11-15, Spezifikation1.22. `worker::reader_registry` implementiert nur
|
||||
Registry-/Unit-/Aktivierungspfadprüfung. Kein Bootstrap, Dienstcontrol, SQLopen,
|
||||
Updaterstart, Apply oder Capability folgt daraus. Die vollständige aktuelle
|
||||
Task-/FD-/maps-Census und die tatsächlich gehaltenen ursprünglichen Root- und
|
||||
Agentlocks sind zusätzlich Pflicht. Die lokale Enginequelle verbindet diese
|
||||
Bausteine inzwischen; ohne extern qualifizierte Bootstrapregistry, tatsächliche
|
||||
Dienst-/Hostkontexte und ursprünglichen Admissionanschluss bleiben die
|
||||
Produktcapabilities `not_configured`. Siehe
|
||||
[aktuellen Readercensusnachweis](agent-updater-reader-census-results.md).
|
||||
|
||||
Der Aufruf `QualifiedRegistry::load(&LocalUpdatePolicy)` liest ausschließlich
|
||||
`/etc/rmm-agent-updater/reader-registry.json` unter root-eigener, gegen fremdes
|
||||
Schreiben geschützter Ancestry. Originalrohbytes höchstens64KiB, root0, regulär,
|
||||
ein Link; deren exakter SHA muss `policy.reader_registry_sha256` entsprechen.
|
||||
Damit bindet der vor WebUI-Genehmigung gespeicherte Policyhash die Registry
|
||||
transitiv. Gehaltene Dateien/Parent-FDs, Rawbytes und aktuelle Metadatastempel
|
||||
bleiben erhalten; `verify_protected()` prüft unveränderte originale Namen,
|
||||
Device/Inodes, Konten/Modi/Linkzahlen, Größe, Zeitstempel und Bytes. Kein Caller-
|
||||
Boolean oder aus einem Registryfeld abgeleitetes Alleinvertrauen.
|
||||
|
||||
Schema1 und Profil `linux_shared_readers_v1` besitzen exakt:
|
||||
|
||||
- `bootstrap_receipt_sha256`: exakt der Bootstrap-Qualificationreceipthash aus
|
||||
`policy.initial_baseline.decode().record.activation_evidence`.
|
||||
- `reader_contract_sha256`: Hash der unveränderlichen öffentlichen Bytekonstante
|
||||
`READER_CONTRACT`, über `reader_contract_sha256()` unabhängig berechenbar.
|
||||
- `host_context`: `census::HostContext` mit extern bootstrapqualifizierten
|
||||
Proc-/User-/PID-/Cgroup-Namespace-Device/Inodes; aktuelle eigene gleiche
|
||||
Metadaten allein sind keine Bootstrapqualifikation.
|
||||
- `units`: die unten festgelegten21 Units in dieser Reihenfolge.
|
||||
- `rollback_timers`: höchstens32 weitere historisch bekannte, sortierte eindeutige
|
||||
`rmm-general-startup-rollback-<kanonische-v4-UUID>.timer`-Einträge.
|
||||
|
||||
Jeder Uniteintrag enthält `unit`, `unit_file_state`, `composition`, `triggers`
|
||||
und `triggered_by`. Beziehungen sind sortierte eindeutige bekannte Registrynamen,
|
||||
keine freie Dateiauswahl oder zukünftige Readererlaubnis. `composition` ist exakt
|
||||
wie im unveränderten OSport die geordnete `Vec<(path, FileProof)>`: Fragment
|
||||
zuerst, dann tatsächliche DropInPaths-Reihenfolge. Der Hash derselben JSON-
|
||||
Bytefolge muss bei den Policydiensten passen; FileProof enthält insbesondere
|
||||
Original-Device/Inode, nicht nur ContentSHA. Geschützte systemd-Fragmente und
|
||||
höchstens16 `.conf`-Dropins werden unter den bekannten systemd-Systemverzeichnissen
|
||||
gebunden, insgesamt höchstens128 Blätter. Global-/Prefixdropins sind möglich,
|
||||
aber kein unbekannter Zusatz wird ignoriert. Leere Komposition und leerer
|
||||
UnitFileState sind ausschließlich bei einem absent/not-found-Nichtreader gültig.
|
||||
|
||||
Die21 Einträge sind zunächst diese7 Services: Agentremote, Helpercloud,
|
||||
Fullmaintenance, Updater, APThelper, Legacy`rmm-agent` und
|
||||
Legacy`rmm-helper-dev-test`. Danach folgen für dieselben7 Basen jeweils `.socket`
|
||||
und `.timer`. Vollständige feste Namen stehen in der Quellkonstante `SERVICES`.
|
||||
`rmm-mvp-test.service` ist eine Wartungsfixture, kein registrierter Reader;
|
||||
dieser Baustein fragt sie nicht ab und steuert sie niemals.
|
||||
|
||||
Der feste Readervertrag bindet: Roothelper erwerben das bestehende
|
||||
`executor.lock` vor SQLiteopen und jeder SQL-/Effektoperation; der Agent hält
|
||||
die vorhandene `agent.lock` schon vor Öffnung beider Agentdatenbanken lebenslang;
|
||||
alle erlaubten Reader verstehen Update-/Handoff-/Inflightdecoder. Registry-
|
||||
Parsing beweist diese Code-/Bootstrapeigenschaften nicht selbst. Die tatsächliche
|
||||
separat qualifizierte Baseline, Originalsignaturen und Census/Locks bleiben
|
||||
Pflicht. Eine Registry oder ein flock allein verspricht keine globale Abwesenheit
|
||||
zukünftiger exec-Aufrufe oder willentlicher vertrauenswürdiger Rootneustarts.
|
||||
|
||||
`verify_admission` verlangt genau Agent/General/Full/Updater loaded/active/running
|
||||
mit echten ServiceMainPIDs, ControlPID0, ohne ausstehenden Start-/Controljob.
|
||||
`verify_stopped` verlangt Agent/General/Full inactive/dead mit tatsächlichen
|
||||
Main-/ControlPIDs0; der Updater bleibt aktiv. Der originale UnitFileState bleibt
|
||||
für alle vier exakt gebunden, enabled oder disabled. Ein aktivierter Full- oder
|
||||
Updaterdienst muss deshalb nicht heimlich enabled werden. APT ist optional nur
|
||||
als tatsächlich gebundener Policydienst vorhanden, bleibt geschlossen und
|
||||
gehört niemals ins Startset. Legacyservices und Gegenstücke sind absent oder
|
||||
loaded/inactive/dead/disabled; aktuelle unbekannte Rollbacktimer verweigern.
|
||||
|
||||
Die read-only Systemdaufrufe sind ausschließlich `/usr/bin/systemctl --system
|
||||
--no-ask-password --no-pager --full show --all` mit festen Properties/Namen und
|
||||
zwei begrenzte `list-units`-/`list-unit-files`-Aufrufe mit festem historischem
|
||||
Rollbacktimerpattern. Kein Shellglob, Pager, Authdialog, start/stop/enable oder
|
||||
freie Commandline. Jede eigene Abfrage hat10s und das zusätzliche ursprüngliche
|
||||
`Budget`; stdout/stderr je16KiB. Nur der eigene gehaltene pidfd-Prozess wird bei
|
||||
Abbruch beendet, keine fremde PID übernommen. Statuswerte und fremde Prozess-
|
||||
oder Mappfade werden nicht in Fehlermeldungen ausgegeben.
|
||||
|
||||
Typen werden nicht erfunden: Service besitzt MainPID und ControlPID, Socket
|
||||
nur ControlPID und eine tatsächliche aktuelle Verbindungsanzahl; Timer besitzt
|
||||
keine PID-Eigenschaft. Fehlende anwendbare Properties verweigern. Timer/dead
|
||||
bedeutet im [Systemd-Primärvertrag](https://github.com/systemd/systemd/blob/main/src/core/timer.c)
|
||||
disarmierte Timereventquellen; Socket/dead ist keine Listenactivation. Es wird
|
||||
kein nicht vorhandenes MainPID als gemessene0 ausgegeben.
|
||||
[DBus-Typvertrag](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.systemd1.html).
|
||||
Die ausgewählte `Job`-Property muss vorhanden sein; deren leere Ausgabe mit
|
||||
`--all` ist Systemctls Darstellung des tatsächlichen Nulljobs.
|
||||
[Primärformatter](https://github.com/systemd/systemd/blob/main/src/systemctl/systemctl-show.c).
|
||||
|
||||
`Triggers`/`TriggeredBy` sind strukturelle Beziehungen und werden exakt gegen
|
||||
die Registry gebunden. Ihre Namen allein werden nicht als laufendes Ereignis
|
||||
missverstanden. Alle relevanten registrierten Aktivierungsquellen müssen
|
||||
unabhängig geschlossen sein; offene oder unbekannte Pfade verweigern. Allgemeine
|
||||
WantedBy-Systemtargets werden damit nicht pauschal zu zu stoppenden Readern.
|
||||
Alle Statusfelder werden vor und nach der Prüfung identisch erneut gelesen,
|
||||
Registry/Unitblätter sowie aktueller Hostkontext erneut geprüft. Das ist eine
|
||||
begrenzte Momentaufnahme unter den weiteren Originalgrenzen, kein Futureexec-
|
||||
oder lückenloser Kernel-Snapshotbeweis.
|
||||
|
||||
Dieser Worker hat keine Target-/SSH-/Job-/Scope-/Dienst-/Policyaktion oder
|
||||
Systemdprobe ausgeführt. Compiler-/Format-/Clippyprüfung und unabhängiger
|
||||
Quellenreview werden durch den koordinierenden Owner nach diesem Quellenhandoff
|
||||
ausgeführt und separat berichtet. Die kleine Parserprobe verwendet ausschließlich
|
||||
synthetische Statusbytes, keine tatsächliche Registry oder laufende Units.
|
||||
@@ -1,89 +0,0 @@
|
||||
# Erhaltener Decodervertrag und weiterhin gesperrte Rückkehr
|
||||
|
||||
Stand2026-11-15, enger lokaler Quellschnitt im bestehenden Worker. Keine neue
|
||||
Journalversion, kein gestarteter Updater, keine VM- oder Applyabnahme.
|
||||
|
||||
## Konkreter Befund und Änderung
|
||||
|
||||
`history::verify_history` authentisiert die separat release-signierte
|
||||
Bootstrapbaseline, die vollständige aufsteigende InstalledRecord-Kette und die
|
||||
ursprünglichen Job-/Handoff-/Health-/Publikationszeugen im erhaltenen Helperledger.
|
||||
Die bisherige Releaseprüfung übernahm jedoch Protokollhauptversion und
|
||||
Zustandsschema aus genau dem Nachfolgermanifest, dessen Kompatibilität sie prüfte.
|
||||
Eine echte Signatur authentisiert einen Releaseinhalt; sie beweist nicht, dass
|
||||
dieser Inhalt den Decodervertrag des erhaltenen Zustands unterstützt.
|
||||
|
||||
Die bestehende Prüfung bekommt jetzt beide Vergleichswerte ausschließlich aus
|
||||
dem separat signierten qualifizierten Bootstrapmanifest. Jeder historische
|
||||
Nachfolger muss diese Werte erhalten. Aktuelle Keywiderrufe, Schlüsselbereiche,
|
||||
Manifest-/Job-/Healthsignaturen, unveränderte Originalbytes und monotoner Floor
|
||||
bleiben zusätzliche Bedingungen. Die Funktion schreibt weiterhin keine SQLzeile.
|
||||
Es gibt keinen neuen Manifest-/Job-/Handoffcodec und keine Datenmigration.
|
||||
|
||||
Dies schließt eine konkrete Kompatibilitätslücke in einem bereits aufgerufenen
|
||||
Reader: `TrustState::qualify_history` verwendet `verify_history` vor neuer
|
||||
Admission sowie unter dem übernommenen Guard vor dem Austausch. Es ist keine
|
||||
Aussage, dass gleiche Versionsnummern die gesamte tatsächliche Decoderfähigkeit
|
||||
beweisen; diese bleibt Bestandteil der unabhängig qualifizierten Bootstrap- und
|
||||
Releaseartefakte. Eine zukünftige ausdrücklich beauftragte Protokoll- oder
|
||||
Zustandsmigration braucht einen eigenen Vertrag.
|
||||
|
||||
## Weshalb damit noch kein Rollback freigegeben ist
|
||||
|
||||
Im vorhandenen Datenvertrag existiert kein normierter V2-Rückkehrzeuge:
|
||||
|
||||
- `Handoff`, `Event` und `Journal` verstehen nur Schema1 und die Vorwärtsfolge.
|
||||
Ein endgültiges `Unknown` bleibt terminal.
|
||||
- `ActivationEvidence` kennt `Bootstrap` und `Updated` mit positivem Healthbeleg;
|
||||
das Feld `rolled_back` allein authentisiert keine Rückkehrwirkung.
|
||||
- Core verweigert `NativeEffect::RestorePredecessor` sowohl beim Claim als auch
|
||||
bei der Beobachtung. Ein vorhandener Linux-Dateiport ist keine Genehmigung.
|
||||
- History verweigert rückkehrende Records und alte Recorddateien, welche die
|
||||
inzwischen vollständig abgeschlossenen Verbräuche/Publikationen auslassen.
|
||||
|
||||
Der ursprüngliche signierte Job bindet bereits
|
||||
`restore_exact_predecessor_once`. Es fehlen jedoch dessen vollständig gebundene
|
||||
dauerhafte Rückwegphasen, belegter eindeutiger Fehlstart, exklusive Guard-/Owner-
|
||||
Übergabe, jede einzelne native Rückkehrbeobachtung, neuer Prozess-/Healthbeleg,
|
||||
Record-/Floorpublikation und failed-Originaloutcome. Vor erster Applybaseline
|
||||
müssen sämtliche tatsächlich installierten Agent-/General-/Fullreader genau
|
||||
diesen noch fehlenden Vertrag verstehen. Das alte1.20-Paar ist kein Rückkehrziel.
|
||||
Kein paralleles unbeobachtetes Journalformat wird als Ersatz eingeführt.
|
||||
|
||||
## Tatsächliche lokale Prüfungen und Grenzen
|
||||
|
||||
Die neuen Fälle verwenden synthetische, aber echte Ed25519-Release-, Baseline-,
|
||||
Job- und Healthsignaturen samt vollständigen in-memory SQLiteoriginalen. Sie
|
||||
prüfen inkompatible Protokoll- und Zustandsschemas, die unveränderte positive
|
||||
Vorwärtskette, eine vorgeschlagene exakte Vorgängerrückkehr mit erhaltenem
|
||||
höherem Floor sowie gespeichertes Unknown. Vor/nach jeder Readerprüfung bleibt
|
||||
`total_changes` gleich; Unknown-Originalbytes und Floors bleiben erhalten.
|
||||
|
||||
Tatsächlich im vorhandenen isolierten Buildcontainer, Netzwerk aus:
|
||||
|
||||
```text
|
||||
cargo test --release --locked --offline -p rmm-updater-worker --all-targets
|
||||
cargo clippy --locked --offline -p rmm-updater-worker --all-targets -- -D warnings
|
||||
cargo fmt -p rmm-updater-worker --check
|
||||
```
|
||||
|
||||
Abschließender normal paralleler Testlauf:12/12 bestanden,0Fehler,0ignoriert;
|
||||
Clippy und Formatprüfung bestanden. Eine private Quellrückmutation ausschließlich
|
||||
auf den alten selbstreferenzierenden Vergleich macht den neuen signierten
|
||||
Kompatibilitätstest erwartungsgemäß rot: Exit101, `unwrap_err` erhält `Ok`.
|
||||
Die Produktionsquelle wurde hierfür nicht zurückgeändert. Dies belegt den
|
||||
konkreten Readerfehler; es ist keine simulierte Updatewirkung.
|
||||
|
||||
Der erste parallele Lauf hatte10/12 bestanden; zwei vorhandene Selbstprozess-
|
||||
Censusfixtures verweigerten eine während anderer Unitfälle wechselnde FD-Tabelle.
|
||||
Der unveränderte Produktguard bestand im seriellen12er-Lauf. Die beiden Fixtures
|
||||
laufen jetzt je in einem eigenen exakt ausgewählten Testprozess, mit unverändertem
|
||||
Censuscode und echten privaten Thread-FD-/mmap-Proben. Danach bestand der normale
|
||||
parallele12er-Lauf. Der erste Clippylauf fand zwei unnötige Testdatenklone;
|
||||
sie wurden ohne Warnungsunterdrückung entfernt. Alte Fehlerlogs bleiben erhalten.
|
||||
|
||||
Geschützter lokaler Belegpfad:
|
||||
`devstate/updater-history-contract-73511ace-428f-4aaf-8742-720619459907/`.
|
||||
Native Linux-/Windowsqualifikation, Codeaustausch und WebUI-genehmigter Updatejob
|
||||
sind nicht ausgeführt. Frühere native Censusberichte qualifizieren nicht die
|
||||
neue Testbinary. Notebook bleibt ausschließlich Entwicklungsrechner.
|
||||
@@ -135,28 +135,9 @@ unveröffentlicht; kein Cloud-VM-Apply, kein Produktfertig- oder Produktionsnach
|
||||
|
||||
Nach dem gepushten gemeinsamen Checkpoint8e93c9e und dem erhaltenden Mainmerge
|
||||
07d6118 ist die bisher offene Enginefolge als konkrete Workerquelle verbunden.
|
||||
Dieser historische Stand sperrte den Eintritt explizit mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Die folgende lokale Fortschreibung hat
|
||||
Registry und Readercensus im Quellpfad verbunden; weiterhin wird weder ein
|
||||
Daemonentrypoint noch eine Job-/Applycapability aktiviert. Die genaue
|
||||
Ihr Eintritt bleibt explizit `UPDATE_READER_CENSUS_NOT_CONFIGURED`; weder
|
||||
Daemonentrypoint noch Job-/Applycapability wird aktiviert. Die genaue
|
||||
Queue-/Reply-/Stop-/Lock-/Swap-/Start-/Healthfolge und vorhandene separate
|
||||
Agent-Singletonsperre stehen in [worker](agent-updater-worker.md). Der neu
|
||||
geprüfte öffentliche Recordbuilder löst die zuvor dort genannte fehlende
|
||||
positive authentisierte Eingangsprobe. Keine reale Applyabnahme folgt daraus.
|
||||
|
||||
|
||||
## Fortschreibung2026-11-15: Readerregistry und vollständige Task-FD-Prüfung
|
||||
|
||||
Der gemeinsame Quellsatz verbindet Registryprüfung, ursprüngliche Agent- und
|
||||
Root-Executorsperre sowie TGID-/TID-FD-/maps-Prüfung mit der bestehenden Engine.
|
||||
Vor SQLiteöffnung verlangt der Ledgerport den nicht frei konstruierbaren
|
||||
`ClosedReaders`-Beleg und den tatsächlich gehaltenen ursprünglichen Rootguard.
|
||||
Das ist ein lokaler Quellen-/Vertragspunkt, kein gestarteter Dispatcher und
|
||||
keine Zusage über zukünftige privilegierte Fremdprozesse.
|
||||
|
||||
Der eingefrorene71-Input-Quellsatz besteht lokal alle10 vorhandenen Workerguards,
|
||||
locked all-targets Check, Release-Link, Clippy mit `-D warnings` und Formatcheck.
|
||||
Ein eigener Runner ist ausschließlich für zwei eigene native Prozessfixtures
|
||||
vorbereitet; er ist noch nicht ausgeführt. Details, frühere fehlgeschlagene
|
||||
Fixtureprüfung und verbleibende MVP-Gates stehen im
|
||||
[Readercensusnachweis](agent-updater-reader-census-results.md).
|
||||
|
||||
@@ -186,18 +186,14 @@ DBclose/Rootlockreturn gehalten und wird vor der festen Startfolge zurückgegebe
|
||||
Der Agent hält schon heute seine ursprüngliche Singletondatei vor beiden
|
||||
Agent-SQLiteöffnungen; keine ACL, Agentdatei oder Sperrrolle wurde geändert.
|
||||
|
||||
Der ursprüngliche Quellencheckpoint verweigerte den Eintritt explizit mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Die Fortschreibung verbindet jetzt die
|
||||
Registry sowie tatsächliche Task-/FD-/maps-Census vor den Stops und unter beiden
|
||||
gehaltenen ursprünglichen Sperren danach. Diese Quellintegration ist lokal
|
||||
geprüft, jedoch noch nicht als installierter Dienst-/Hostkontext qualifiziert.
|
||||
Eine bekannte Unitliste allein ersetzt keinen Census. Keine CLI oder
|
||||
RMM-Admission ruft diese Runtime auf; Applycaps bleiben geschlossen. Offen sind
|
||||
insbesondere extern qualifizierte kompatible Bootstrapregistry und Hostkontexte,
|
||||
ursprüngliche Full-Admission, Staging-/Downloadproducer, passiver gültiger
|
||||
**Explizite Sperre dieses Checkpoints:** `Runtime::serve_one` verweigert mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Geschützte kompatible Bootstrapregistry
|
||||
plus vollständige aktuelle PID-/FD-/maps-Census und Nachstopbeobachtung unter
|
||||
beiden tatsächlichen Sperren fehlen noch. Eine bekannte Unitliste ersetzt
|
||||
keinen Census. Keine CLI oder RMM-Admission ruft diese Runtime auf; Applycaps
|
||||
bleiben geschlossen. Ebenso offen: Staging-/Downloadproducer, passiver gültiger
|
||||
Updatezustand, V2-Rollbackvertrag vor dem ersten Bootstrap, Unsicherheits-
|
||||
Namespaces und tatsächlicher Linux-Apply. Aktueller Nachweis und enger geplanter
|
||||
nativer Zweierlauf: [Readercensus](agent-updater-reader-census-results.md).
|
||||
Namespaces, qualifizierte Dienstkontexte und tatsächlicher Linux-Apply.
|
||||
|
||||
Lokaler Nachweis liegt unter
|
||||
`devstate/updater-engine-source-6a8bb902-4db4-4d93-8843-450ba1dd5622/`.
|
||||
|
||||
@@ -1,72 +1,5 @@
|
||||
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
|
||||
|
||||
**15. November 2026.** Der permanente Server betreibt das Zeit-Gateway.
|
||||
Die Windows-VM hat mit ihrer Geräteidentität die Signatur geprüft. Ein fremder
|
||||
Mandant und eine alte Verbindung wurden abgewiesen. Die Cloud-Linux-VM und
|
||||
der Windowsgast melden sich selbständig und sind über MCP abrufbar.
|
||||
[Gateway](server-time-gateway-deploy.md) · [Windows-Protokolltest](windows-time-route-operator.md)
|
||||
|
||||
Am 15. November liefen auf dem Windowsgast nach dem einmaligen Dienstwechsel
|
||||
der neue Agent unter LocalService und der neue Helper unter SYSTEM. Die
|
||||
separate Nachprüfung bestätigte beide Prozessstarts, das Gerätezertifikat,
|
||||
die Geräteidentität und die bisherigen Journalstrukturen. Der erste Online-Kontakt
|
||||
nach dem Wechsel gelang. Danach wies PostgreSQL den passiven Updatestatus
|
||||
`agent.update` zurück. Der letzte reguläre Kontakt vor der Störung lag um
|
||||
16:17:32 Uhr MEZ. Für die Korrektur wurden auf dem permanenten Server die
|
||||
gefilterte Basisinventarabfrage und Migration 16 aus dem zum laufenden
|
||||
ARM64-Image passenden Builder offline gebaut. Docker meldete Exit 0 für
|
||||
Image `6a76343bf65c` (Buildfall `5ad7c74c-67a1-40b8-8960-d3ba016565af`).
|
||||
[Dienstwechsel und Inventarabfrage](windows-signed-clock-upgrade-plan.md)
|
||||
|
||||
Die Zeitprofilinstallation scheiterte beim Veröffentlichen der Datei mit einer
|
||||
`IOException`. Eine separate Abfrage auf der VM bestätigte, dass die Zieldatei
|
||||
fehlte und die Dienste weiterliefen. Das SSH-Fenster endete um 16:30 Uhr MEZ.
|
||||
Für die nächste Gastprüfung muss der bestehende Teilzustand berücksichtigt
|
||||
werden. Die Zeitprüfung in beiden installierten Rollen und der erste über die
|
||||
WebUI genehmigte PowerShell-Auftrag stehen aus.
|
||||
[Zeitprofil und Originalbefund](windows-time-profile-config.md)
|
||||
|
||||
Die passive Zertifikatserneuerung ist implementiert. Fünf Wiederanlauf- und
|
||||
Fehlerfälle mit Testidentitäten bestanden auch auf Windows. Das Anlegen,
|
||||
Schützen und Wiederöffnen einer separaten Testschlüsseldatei bestand auf
|
||||
der Windows-VM unter dem Entwicklungskonto. Die Erneuerung durch den
|
||||
installierten LocalService-Dienst steht aus.
|
||||
[Zertifikatserneuerung](windows-certificate-renewal.md)
|
||||
|
||||
Der Linux-Agent kann einen signierten Releasekatalog über mTLS prüfen und das
|
||||
Ergebnis im Inventar melden. Sechs gezielte Tests bestanden auf der Cloud-VM.
|
||||
Der Katalogcheck ist im Quellstand integriert. Die laufende Installation hat
|
||||
noch kein Agent-Selbstupdate durchgeführt. [Updatekatalog und offene Schritte](agent-updater-passive-catalog.md)
|
||||
|
||||
## Frühere Zwischenschritte
|
||||
|
||||
**Broker-UDS und echte Signaturen bestanden:** Host und Standard-PIDnamespace-
|
||||
ContainerUID10001 mit getrennten Challenges tatsächlich Ed25519-verifiziert;
|
||||
ContainerpeerPID0 und RootUID0-Deny belegt. Separater Originalread und identische
|
||||
Corezeugen. [Ergebnisse](server-time-broker-signature-acceptance.md).
|
||||
HTTPSdeployment und Windowsrollen-/Jobnachweise bleiben offen.
|
||||
|
||||
**Zeitbroker tatsächlich einmal gestartet:** Effektivhärtung, gehaltener
|
||||
Prozess und Root:10001-Socket bestanden; separate Nachlese und identische
|
||||
SQL-Corezeugen belegt. [Ergebnisse](server-time-broker-start-acceptance.md).
|
||||
Noch keine Signatur-/HTTP-/Windowsjobabnahme.
|
||||
|
||||
**Historischer vorangehender Stand — Zeitbroker installiert, noch nicht gestartet:** eigenes Root500-ARM64-
|
||||
Binary5d8d und Demand-Unit4792 samt Socketgruppe10001 create-only eingerichtet;
|
||||
alle Schritte mit separatem Read. [Belege](server-time-broker-bootstrap.md).
|
||||
Noch kein Reload/Enable/Start, keine Signatur oder Windowsjobfreigabe.
|
||||
|
||||
**Separater Server-Zeitschlüssel provisioniert:** eigener Hostseed bleibt
|
||||
ausschließlich Root600; öffentlicher Pinc31d31d2 und separater Read belegt.
|
||||
[Ergebnisse](server-time-broker-bootstrap.md). Noch kein Brokerstart,
|
||||
Zeitsignieren oder Windows-/Jobgate.
|
||||
|
||||
**Tatsächliche Serverquellqualität bestanden:** neue c9-Probe Exit0,
|
||||
Kernel0/Fehler50.834ms/Syncalter43.596s, identische Erhaltungszeugen und
|
||||
separater Read. [Originalbelege](server-time-source-new-generation-probe.md).
|
||||
Kein Signer/Broker/HTTP-/Windowsjobgate daraus automatisch aktiviert;
|
||||
geschützter separater Signerbootstrap folgt.
|
||||
|
||||
**Zwei reale Schritte bestanden:** freigegebener einmaliger Chronyrestart
|
||||
und Pin395f mit separatem Read/Erhaltung ([Belege](server-time-source-chrony-generation-bootstrap.md));
|
||||
aktives Windows-Zeitprofil nativ Cloud-Linux8/18,10gefiltert, separater Read
|
||||
|
||||
@@ -1,57 +1,5 @@
|
||||
# Tatsächlicher Implementierungsstand
|
||||
|
||||
## Passiver Windows-Zeitabschluss vorbereitet — 2026-11-15
|
||||
|
||||
Ein kleiner rein lesender Collector für die beiden historischen Rollenbelege
|
||||
aus cc82124 ist ausführbar vorbereitet. Er bindet öffentliche Dienstprozesse,
|
||||
Boot, aktuelle Servergeneration, Rollen-/Hashtrennung und enge Datenalter;
|
||||
keine Dienste, IPC, Zeitrequests oder Diagnoseprogramme werden ausgelöst.
|
||||
Lokale Syntax-/Scopeguards und sechs Bindingfixtures bestanden. Der konkrete
|
||||
lokale .NET-/Chrono-Fraktionsparserfehler ist mit exakter Nanosekundenrechnung
|
||||
und +1ns-Grenzfall korrigiert. **Kein VM-Aufruf,
|
||||
keine native Collector-/Rollenabnahme** vor Roots V2-Profil-/Readbacksignal.
|
||||
[Umfang und genaue Grenzen](windows-passive-time-closeout.md).
|
||||
|
||||
## Passiver Windows-Zertifikatspfad — Quellenstand 2026-11-15
|
||||
|
||||
Eigener RotationStore mit geschützten CreateNew-Keydateien und atomarer
|
||||
öffentlicher CSR-/Zertifikats-/Versionswahl im bestehenden SQLite-Journal.
|
||||
Pending wird vor dem Transport-Hello wiederaufgenommen; kein Schlüssel im
|
||||
Telemetrie-WAL, kein automatisches Reenrollment oder Legacyfallback nach Wechsel.
|
||||
Automatische Erneuerung ausschließlich bei `enable_jobs=false`; keine neue
|
||||
Job-/Helperfähigkeit. [Vertrag und Abnahmegrenzen](windows-certificate-renewal.md).
|
||||
|
||||
Lokal Linux23/23Libtests ohne Filter, GNU-Windows-Alltargetscheck mit
|
||||
`system-helper`, Clippy beider Targets mit `-D warnings` und Workspacefmt
|
||||
bestanden. Anschließend dieselben fünf portablen Rotationsfälle tatsächlich auf
|
||||
Cloud-Linux als UID65534 bestanden (5PASS/18andere gefiltert); Ergebnisquittung
|
||||
`7e6cab5915ec00a9b1392c1f15ddb13fe9ac6dd3b8e007b82e1dc914cb0507e1`.
|
||||
Kein installierter Dienst oder Gerätezertifikat verändert; echte
|
||||
Windows-Renewal-/LocalService-Dateiabnahme bleibt offen.
|
||||
|
||||
Ein erster Windowslauf blieb bei4/5 fehlgeschlagen: Testfixture las die rohen
|
||||
SQLite-Dateien vor Schließen ihres eigenen WAL-/SHM-Locks (Win32-Fehler33).
|
||||
Nach ausschließlich diesem Testfix erneut tatsächlich Linux5/18gefiltert,
|
||||
danach Windows11-AMD64-Entwicklungsbenutzer5/44gefiltert bestanden; jeweils
|
||||
keine Skips/Fehler. Neue Quittungen `1736a19a75d49eca91062e4e7adb28732f254279b64003474efcd6201ffa08ac`
|
||||
und `64e960c2eb0b755b376028d923c6fdebbc11d5f96534103452f865ccf51a4fc0`.
|
||||
Nur portable Logik mit synthetischen KeyFiles, keine echte TLS-Rotation oder
|
||||
LocalService-Keydateiabnahme. Originalfehler und genaue Grenzen bleiben im
|
||||
verlinkten Bericht erhalten.
|
||||
|
||||
Zusätzlich tatsächlich nativ Windows bestanden: eine ausdrücklich ausgewählte
|
||||
Keydatei-Unit im bestehenden Lib-Testbinary (ein PASS/49andere gefiltert,
|
||||
Exit0/0ignored). Geschütztes CreateNew/Flush/Reopen, öffentlicher Keyhash,
|
||||
Nichtüberschreiben, breite DACL an leerer Fixture, gehaltenes Verzeichnis und
|
||||
Hardlinkablehnung geprüft. Eigener Falle0590d96, Rohread-SHA
|
||||
`68dd458a24c2455049b7799f57e30f1e858e323fa82c578e3b962f58282b5e49`.
|
||||
Nach einem lokalen JSON-Formatfehler wurde nur das ursprüngliche beständige
|
||||
Ergebnis nachgelesen, kein zweiter Start. Eigener temporärer Testkey entfernt;
|
||||
keine Dienste/Accounts/Tokenübernahme oder permanente Dateien betroffen.
|
||||
Produktcode unverändert; dieser Administratorlauf ersetzt keinen LocalService-
|
||||
Nachweis und keine echte Renewalabnahme. Im Defaultlauf bleibt die gesonderte
|
||||
Administratorfixture bewusst `ignored`.
|
||||
|
||||
## Windowsfortsetzung: Nichtstart-Kern nativ qualifiziert — 2026-11-14
|
||||
|
||||
Der zusätzliche enge deny-only Nichtstart-Kern ist implementiert und mit
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
# Parallele MVP-Fortsetzung2026-11-14
|
||||
|
||||
**Integrierter Quellencheckpoint2026-11-15:** Main13d9491 vereinigt
|
||||
Windows-Zeitprofil1.23 und Updater-Readercensus. Lokaler locked/offline
|
||||
Alltargetscheck für Server, Linuxagent, Windowslibrary und Updaterworker
|
||||
bestanden (keine Tests/VM-Wirkung dadurch). Fall0d6736fc, Log-SHA256
|
||||
`9ce99acc46912e3bd96f064ae5db330bbd23d325d63935d126592360104a2cb9`.
|
||||
Zwei frühere Harnessläufe stoppten vor Kompilierung (Entrypoint, Owner des
|
||||
eigenen neuen Targets); Fehlerlogs erhalten, kein ursprünglicher Cache
|
||||
entsperrt. Die separat gefrorenen Produkt-/VM-Nachweise behalten ihre
|
||||
eigenen Source-/Artefaktbindungen; dies ist keine neue native Applyabnahme.
|
||||
|
||||
**Updater-Quellenfortschritt1.21:** Gemeinsamer Checkpoint1e89c45 ist gepusht
|
||||
und nach Main integriert. Server/Katalog/Streaming/UI, Healthpfad bei Ready=false,
|
||||
Corehandoff/native CAS, geschützte Provisionierungscodecs und erster konkreter
|
||||
|
||||
@@ -10,8 +10,6 @@ Pfad bleiben dort sofort relevant.
|
||||
|
||||
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
||||
| --- | --- | --- |
|
||||
| Gesundheitsübersicht für größere Flotten | Beim Quellabgleich nach der MCP-Abnahme vom 15. November fiel auf, dass `monitoring.get_health` die erste Inventarseite liest und deren Fortsetzungscursor verwirft. Der aktive Testbestand passte auf eine Seite. | Vor Nutzung für größere Mandanten den Cursor für HTTP und MCP durchreichen und den Bezugszeitpunkt beibehalten. `inventory.list_devices` unterstützt bereits Folgeseiten. |
|
||||
| Verfügbarkeit der signierten Serverzeit | Tatsächliche Quellproben derselben laufenden Chronygeneration lieferten50.834ms bei43.596s Syncalter und später295.609ms bei320.110s. Beide gültig; kein kontinuierlicher Verfügbarkeitsnachweis. | Nach dem MVP natürlichen Poll-/Kernel-Fehlerverlauf und Verfügbarkeit messen, gegebenenfalls separat genehmigte Betriebsoptimierung. Fehlende Qualität muss bereits jetzt deny bleiben; keine500ms-Grenzlockerung, erfundene Frische oder implizite Resync-/Konfigurationsänderung. |
|
||||
| Windows-PE nach erneutem Debugstrip | Zwei Lieferkopien mit identischen unveränderten Original-Linkdateien unterscheiden sich nach erneutem Strippen nur an vier Bytes: COFF-Zeitstempel/PE-Prüfsumme, Offsets136/137/216/217. Lokal tatsächlich verglichen; beide ursprünglichen Packs bleiben erhalten. Jeder Pack pinnt seine konkreten Lieferbytes. | Reproduzierbare PE-Werkzeugpipeline vor M7 festlegen. Bis dahin niemals gleichen Lieferhash aus gleicher Rustquelle/gleichem Original-Link behaupten oder ein altes Manifest überschreiben. Kein aktueller Autorisierungs- oder Abnahmebypass. |
|
||||
| Dev-Reversetunnel ohne Zielbanner | Windows-RMM-Heartbeats liefen tatsächlich weiter, während Serverlistener/TCP-Verbindung auf127.0.0.1:22240 vorhanden waren, aber kein SSH-Banner durchkam. Der Bootstraploop überwacht nur das äußere ssh.exe und verbindet nach dessen Ende neu; der Task hat kein RestartOnFailure. Konkrete Ursache des blockierten SSH-Ziels unbewiesen. Keine SSH-/Hostkey-/Expirygrenze gelockert. | Nach dem MVP begrenzte Transport-/Workerdiagnose verbessern. Keine automatische Schlüsselverlängerung, öffentliche Windowsportfreigabe oder pauschalen sshd-/UID-Resets. Der aktuelle manuelle Konsolenneustart bleibt ausdrücklich zeitlich abzustimmen und ist kein RMM-Rebootnachweis. |
|
||||
| Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. |
|
||||
|
||||
@@ -10,40 +10,26 @@ Der feste Originalfall ist `5b358997-3abc-43db-945f-f41855b4e3c0`.
|
||||
Der unveränderte Pinbootstrap `fac85dd…` wird ausschließlich von
|
||||
`/var/lib/rmm-time-source-operators/<vollerSHA>/pin_bootstrap.py` geladen:
|
||||
Root:Root0600, ein regulärer Link, geschützte Ancestry und exakter SHA256.
|
||||
Seine tatsächlichen Original-Preflight-/Build-/Quellen-/Boot-/Runtimebelege
|
||||
bleiben unverändert Pflicht. Nach dem ausdrücklich genehmigten Chronyneustart
|
||||
werden die alte Prozessgeneration und ihr alter Pin ausschließlich historisch
|
||||
geprüft; der neue gemeinsame Generationbeleg bindet den aktuellen Prozess und
|
||||
den tatsächlich ersetzten öffentlichen Pin. Kein Aufruf oder Umgehen des alten
|
||||
`pin.Original`-Konstruktors ist hierfür zulässig. Der Broker muss genau das erfolgreiche
|
||||
Seine tatsächlichen Original-Preflight-/Build-/Quellen-/Boot-/Runtime- und
|
||||
Chrony-/Pinbindungen bleiben Pflicht. Der Broker muss genau das erfolgreiche
|
||||
ARM64-ELF1067136Bytes/SHA256
|
||||
`5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201`
|
||||
sein. Alte gescheiterte Probe-/Bootstrapversuche werden nicht umgeschrieben.
|
||||
|
||||
Vor jeder der drei Phasen ist zusätzlich ein tatsächlicher erfolgreicher
|
||||
`probe-native-source-v1/result.json` im neuen Generationsfall
|
||||
`c9a94f94-eecd-4c66-933d-c45c1a79c7a8` nötig, Profil
|
||||
`rmm.server-time-source.native-generation-acceptance.v1`. Der gemeinsame,
|
||||
Rootgeschützte und exakt hashgebundene `SharedGenerationProof` liest den
|
||||
historischen5b-Build ausschließlich als erhaltende Quellen-/ELFprovenanz. Er
|
||||
verlangt zusätzlich die tatsächlichen c9-Neustart-/Pin-CAS-Belege und hält den
|
||||
aktuellen Prozess-/Socket-/Konfigurations-/Namespace-/Bootkontext unabhängig.
|
||||
Sein strikter gemeinsamer Qualitätsdecoder prüft die neuen vollständigen
|
||||
Result-/Witness-/Samplebelege. Frühere GROUP-/DAC-/ca89-Fehlschläge bleiben
|
||||
unverändert fehlgeschlagen; keiner kann dieses neue Gate erfüllen.
|
||||
|
||||
Der anfänglich geschlossene `QUALITY_RESULT_SHA=None`-Gate ist jetzt durch
|
||||
ein enges Einzeilendelta ausschließlich an das tatsächlich erfolgreiche neue
|
||||
Resultat `ab8a6511517c6e3c01db2351ccdc5c48c73f34112c9ac863d0ea64de46665933`
|
||||
gebunden. Root hat Ausführung und einen separaten Original-Read nachgewiesen;
|
||||
die genauen Belege stehen am Ende dieses Dokuments. Ein erfolgreicher Restart
|
||||
oder CLI-Tracking allein hätte diesen Gate nicht erfüllt. Dies installiert
|
||||
keinen Signer oder Broker und startet weder Dienst noch HTTP-Endpunkt.
|
||||
Eine historische erfolgreiche Probe wird später nicht als aktuelle
|
||||
Zeitautorität wiederverwendet: der laufende Broker misst vor jeder Signatur
|
||||
selbst frisch. Schlüssel-/Gruppen-/Installationsphasen verbleiben create-only
|
||||
im ursprünglichen5b-Fall und speichern die exakten c9-/Controller-/Qualitäts-/
|
||||
öffentlichen-Pinlinks zusätzlich in Intent und Resultat.
|
||||
Vor jeder der drei Phasen ist zusätzlich das tatsächliche erfolgreiche
|
||||
`probe-peer-acceptance-v1/result.json` desselben Originalfalls nötig.
|
||||
Der Gate bindet den separat geprüften Probecontroller, vollständige
|
||||
Vorher-/Nachher-Zeugen samt ihren gespeicherten Bytes/Hashes, Sources, Artefakt,
|
||||
öffentlichen Pin, ursprüngliche Fehler-/Pinbelege und identische Boot-ID.
|
||||
Das tatsächliche Sample muss strikt Fehler≤500ms, Syncalter≤1h, Kernelstate0..4
|
||||
und alle unveränderten Samplefelder erfüllen. Eine Fixture, Callerbool oder
|
||||
Dateipräsenz allein qualifiziert nichts. Die Qualitätsprobe muss erfolgen,
|
||||
bevor die neue Supplementary-Gruppe angelegt wird. Die neue DAC-Probe belegt
|
||||
das separat diagnostizierte Zugriffsprofil; die frühere GROUP-Probe mit Exit1
|
||||
bleibt fehlgeschlagen und ihre Originalbytes/-Hashes bleiben gebunden.
|
||||
Eine historische erfolgreiche Probe wird nicht als aktuelle Zeitautorität
|
||||
wiederverwendet; der laufende Broker muss später vor jeder Signatur selbst
|
||||
frisch messen.
|
||||
|
||||
Auf dem Server ausschließlich isoliert starten:
|
||||
|
||||
@@ -131,7 +117,7 @@ Das notwendige Reader-Token bleibt ausschließlich Root:Root0600. Keine
|
||||
Root-Eigentümerschaft der öffentlichen PKI wird erfunden oder geändert.
|
||||
|
||||
|
||||
Der damalige historische Installationsgate war ausschließlich an die DAC-Probe gebunden,
|
||||
Der Installationsgate ist ausschließlich an die neue DAC-Probe gebunden,
|
||||
einschließlich ihrer fünf zusätzlichen Herkunftshashes. Das alte GROUP-Probe-
|
||||
Resultat und Log werden weiterhin bytegleich gelesen und nie als erfolgreich
|
||||
umgedeutet. Fehlender oder nicht erfolgreicher DAC-Nachweis verweigert bereits
|
||||
@@ -215,7 +201,7 @@ unverändert. Der tatsächliche native Qualitätsgate bleibt weiterhin geschloss
|
||||
keine Vorratsfreigabe oder Zielaktion folgt aus diesem Reviewfix.
|
||||
|
||||
|
||||
## Historischer separater Peer-Qualifier: keine operative Freigabe
|
||||
## Separater Peer-Qualifier: weiterhin keine operative Freigabe
|
||||
|
||||
Der vorbereitete Gate verwendet jetzt ausschließlich
|
||||
`probe-peer-acceptance-v1/result.json`, Profil
|
||||
@@ -265,138 +251,3 @@ Providertransport und seine tatsächlichen Abnahmen bleiben separate Gates.
|
||||
Dies ändert keinen alten Fehler in einen Erfolg. Der Brokergate bleibt
|
||||
`QUALITY_RESULT_SHA=None`; weder Schlüssel noch Gruppe oder Installation
|
||||
sind damit freigegeben.
|
||||
|
||||
|
||||
## Historischer Quellencheckpoint: zunächst geschlossener Brokeradapter
|
||||
|
||||
Root hat den vom User ausdrücklich erlaubten einmaligen Chronyneustart und
|
||||
öffentlichen Pin-CAS tatsächlich nachgewiesen. Generationsresultat SHA256
|
||||
`d648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4`
|
||||
ist ein Restart-/Identitätsbeleg, keine native Sourcequalität. Der neue aktuelle
|
||||
Daemon ist PID2519215/Birth17718075, weiterhin UID/GID989 mit demselben geprüften
|
||||
Image. Der neue öffentliche Pin umfasst195Bytes. Der alte Peerqualifier ca89
|
||||
bleibt `source_quality_qualified=false`.
|
||||
|
||||
Der Brokeradapter lädt ausschließlich den separat eingefrorenen gemeinsamen
|
||||
`new_generation_probe.py` aus seinem Content-addressed Root0600-Operatorpfad.
|
||||
Kein `pin.Original()`-Aufruf, keine Änderung alter `expected`-Werte und kein
|
||||
Fallback auf alte PIDs. `SharedGenerationProof` hält historische Originale und
|
||||
aktuellen neuen Pin; vor jedem Write werden seine Originalrecords, aktuelle
|
||||
Prozess-/Namespacezeugen und die gebundenen Qualitätsrecords erneut geprüft.
|
||||
Die drei eigenen Verzeichnisse behalten dev/ino/uid/gid/mode und ACLs; spätere
|
||||
legitime eigene Dateierzeugung wird nicht durch erfundene Verzeichnismtime-
|
||||
Gleichheit verhindert. Fremde Objekte werden weiterhin nicht übernommen.
|
||||
Alle gehaltenen Proof-FDs werden beim regulären Ende und Konstruktorfehler
|
||||
explizit geschlossen. Schlüsseltrennung, feste Tools, Crypto-/Private-Ausgabe-
|
||||
Grenzen, Unitkomposition und create-only Wirkungsphasen bleiben unverändert.
|
||||
|
||||
Der Quelladapter und isolierte Deltaguards ersetzen sämtliche externe Autorität
|
||||
durch Fixtures. Ihre Positivfälle sind kein tatsächlicher Qualitätsnachweis.
|
||||
Es wurden durch diesen Adapter weder Zielzugriffe noch Schlüssel-/Gruppen-/
|
||||
Dienstwirkungen oder weitere Updateränderungen ausgeführt.
|
||||
|
||||
Tatsächlich lokal ausgeführte Adapter-Deltaguards: drei Gruppen bestanden.
|
||||
Der initiale `None`-Gate verweigerte vor jedem ersetzten externen Zugriff;
|
||||
der gemeinsame Decoder erhielt exakt den verlangten Resulthash, fehlender
|
||||
Resultpfad oder veränderte gespeicherte Bytes verweigerten; der Context prüfte
|
||||
neuen Pin/Namespace erneut und schloss gehaltene Proofs auch nach Fehler im
|
||||
Konstruktor. Alle externen Autoritäten/Getters waren ersetzt, ausschließlich
|
||||
ein eigener temporärer Verzeichnis-FD wurde verwendet. Fünfzehn bestehende
|
||||
Crypto-/Role-/Unitcomposition-/Create-only-/Readdefinitionen und sechs feste
|
||||
Konstantenausdrücke wurden bytegleich gegen Controller31f2 nachgewiesen.
|
||||
Der erste reine Vergleichshelfer versuchte `ast.literal_eval` auf
|
||||
`bytes.fromhex(...)` und brach ab; der korrigierte AST-Ausdrucksvergleich
|
||||
bestand, ohne Änderung der Produktquelle oder einer Prüfungsausnahme.
|
||||
|
||||
|
||||
Gemeinsamer eingefrorener Generation-/Qualifiercontroller: SHA256
|
||||
`c15f4dad9aeb51270fbee7ba28a545cfe9f6a879d0bc226cf5ddda9036a5a2b6`,
|
||||
36.967Bytes, fester Hostname `new_generation_probe.py` im gleichnamigen
|
||||
SHA256-Elternpfad. Der Broker bindet genau diese Quelle; ihr gemeinsamer
|
||||
Qualitätsdecoder hält vier Originalrecords (Resultat, Log, Vorher/Nachher).
|
||||
Die separate Sourcequalifikation des Controllers ist kein tatsächlicher
|
||||
Probe-PASS. Beim damaligen Quellenfreeze blieb `QUALITY_RESULT_SHA=None`;
|
||||
der anschließende tatsächliche PASS und sein enges Hashdelta folgen unten.
|
||||
|
||||
|
||||
## Tatsächlicher neuer Qualitätsnachweis und exakte Resultbindung
|
||||
|
||||
Root führte die native Probe im c9-Generationsfall tatsächlich aus:
|
||||
Originalaufruf `a8c61ad4-5ced-44dd-a120-1ef5cd2bb68b`, Receipt SHA256
|
||||
`1aab3af930648aed260c4c66a1c3ff068656cae016fcc301f052880926f99c93`.
|
||||
Separater ausschließlich lesender Originalaufruf
|
||||
`de6273d1-3ae5-4f02-b759-e13fbf8116e9`, Receipt SHA256
|
||||
`7005ef54759412cd0d95e558ceebbf524a55c04bf6641c8241161e0d5e81fbf3`.
|
||||
Das exakte Resultat besitzt SHA256
|
||||
`ab8a6511517c6e3c01db2351ccdc5c48c73f34112c9ac863d0ea64de46665933`.
|
||||
Exit0, `source_quality_qualified=true`, unveränderte Vorher-/Nachherzeugen,
|
||||
Kernelstate0, tatsächlicher Gesamtfehler50.833.923ns und Syncalter43.596.197.206ns.
|
||||
Diese Werte sind der einzelne gemessene Probenstand, keine fortdauernde
|
||||
Qualitätszusage oder bereits signierte Zeitattestierung.
|
||||
|
||||
Ausschließlich die eine Controllerzeile `QUALITY_RESULT_SHA` wurde von `None`
|
||||
auf genau diesen Hash gesetzt; Sharedcontrollerc15f, Wirkungs-/Crypto-/Role-/
|
||||
Unitcompositionquellen und sämtliche Schutzbedingungen bleiben bytegleich.
|
||||
Die drei alten GROUP-/DAC-/ca89-Fehler bleiben unverändert fehlgeschlagen.
|
||||
Ein lokaler Decoder-Gegencheck verwendet die vier tatsächlich gespeicherten
|
||||
Originalrecords Resultat/Log/Vorher/Nachher aus dem separaten Root-Read,
|
||||
prüft ihre exakten Byteshashes und lässt sie durch die unveränderte gemeinsame
|
||||
`SharedGenerationProof.quality_proof` laufen. Live-Prozess-/Datei-FDautorität
|
||||
wird dabei ausdrücklich durch den gespeicherten Root-Read ersetzt: kein neuer
|
||||
Zielzugriff und kein Ersatz der tatsächlichen Root-Ausführung oder Nachlese.
|
||||
|
||||
Dieser Quellenschritt erzeugt keine Seeds, Schlüsseldateien, Gruppe10001,
|
||||
Binary oder Unit und startet keinen Broker, HTTP oder Windows-Clockgate.
|
||||
Root muss Host-key, Host-group und Host-install weiterhin getrennt reviewen
|
||||
und selbst ausführen. Der spätere laufende Broker muss vor jeder Signatur eine
|
||||
neue native Quelle messen; diese Probe ist kein wiederverwendbarer Zeitgrant.
|
||||
WebUI-Jobs und sämtliche RMM-Genehmigungsgrenzen bleiben unverändert.
|
||||
|
||||
## Tatsächlich eigener Zeitschlüssel auf dem Server provisioniert
|
||||
|
||||
Nach tatsächlicher Sourcequalität und unabhängigem finalem Quellenreview wurde
|
||||
ausschließlich `host-key` einmal ausgeführt. Rootreceipt
|
||||
`10ae6e10ceda1d8aca8454f9e8fdf81eadb7f33822bb1b6c9545363a386ba04d`.
|
||||
Der Host erzeugte seinen eigenen Ed25519-Seed; `seed_exported=false`.
|
||||
Private Signerkonfiguration Root:Root0600/Singlelink, getrennt von tatsächlichen
|
||||
Job-/bekannten TLSrollen; weder Seed noch private Konfigurationsbytes oder
|
||||
deren Hash wurden ausgegeben.
|
||||
|
||||
Öffentlicher Zeitpin-SHA256
|
||||
`c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2`.
|
||||
Separater ausschließlich lesender Rückabruf0e0b2469, Receipt
|
||||
`25c690925fad06a7a065e483971bd9c23acd88190c33994c560c0f7166bc6357`,
|
||||
bestätigt ursprüngliches Keyresult
|
||||
`fa81bde18a68c7c367ae7facf3914711072ba5238f0d10b5eba29c320efa3d75`
|
||||
und geschützte Metadaten. Ausschließlich der öffentliche Pin wurde zusätzlich
|
||||
lokal geschützt abgelegt; keine Kopie des privaten Signers. Noch keine
|
||||
Gruppe/Unit/Brokerstart/Signatur/HTTP- oder Windows-Clockfreigabe daraus.
|
||||
|
||||
## Tatsächlich feste lokale Socketgruppe eingerichtet
|
||||
|
||||
`host-group` einmal erfolgreich, Rootreceipt
|
||||
`c2a03d00525a63f540a8b6dd069bbc783f797566d3e0f150c3417259af93a352`.
|
||||
Die vorher abwesende Gruppe `rmm-time-gateway`/GID10001 existiert nun mit
|
||||
exakt leerer Mitgliederliste. Vorhandene öffentliche Gruppenzeilen blieben
|
||||
bytegleich; keine Benutzer wurden aufgenommen. Separater Originalread
|
||||
f185b102 bestätigt Result
|
||||
`1f987cbe7e7558ecb1e4dac9542bda69d6f09343a40098c5be4817ac9ebfca45`,
|
||||
Receipt `97c68b346b4d83d9e1e61cc029ecaa02f6256991e2bdf7c2385e1717f78f1773`.
|
||||
Noch keine Unitinstallation, Aktivierung oder Signatur durch diesen Schritt.
|
||||
|
||||
## Tatsächlich Brokerbinary und Demand-Unit installiert
|
||||
|
||||
`host-install` einmal erfolgreich, Rootreceipt
|
||||
`5d99c54fb747737991d98ec65ee715fb7c1820af5814fd36f1dbe31ed833ed03`.
|
||||
Unverändertes qualifiziertes AArch64-Binary5d8d7869/1067136Bytes unter
|
||||
`/usr/local/libexec/rmm-time-broker`, Root:Root0500/Singlelink; Unit657Bytes,
|
||||
Root:Root0644/Singlelink, SHA256
|
||||
`4792bfb65763f5a5146044d2ba152acd0a876b66c29d8cc66c16a5250214af2c`.
|
||||
Geschlossene Manager-Unitpaths/Prefix-/Typewide-/Alias-Komposition geprüft.
|
||||
Kein daemon-reload, Enable, Start oder Zeitsignieren durch diese Phase.
|
||||
|
||||
Separater Originalread a293463f bestätigt Result
|
||||
`b52aa57971fcad5a9ff3780765f4712d4029d078aab71f94eaec6d805a642f71`,
|
||||
Receipt `0f1c2bcbe7ffca5cf8f40c40c84e836bf0659b67032e89bdfadd1ef1b9b4a03b`.
|
||||
Effektive geladene Unit und tatsächlicher Prozess/Socket müssen vor dem
|
||||
separaten einmaligen Demandstart unabhängig nachgewiesen werden.
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
# Enge lokale Broker-/UDS-Signaturfixture
|
||||
|
||||
Quelle `deploy/server_time_broker_signature_acceptance.py`, Stand2026-11-15.
|
||||
Root startet allein die tatsächliche Abnahme nach unabhängigem Source-Review.
|
||||
`host-preflight` prüft ausschließlich geschützte Originale und lebenden Broker,
|
||||
endet vor Random, Phasenmkdir oder UDSrequest. `host-execute` ist create-only im
|
||||
Originalfall5b unter `broker-signature-acceptance-v1`; bei Antwortverlust oder
|
||||
Fehler ausschließlich `host-read`, keine Wiederholung oder Bereinigung.
|
||||
|
||||
Gebunden sind Startcontrollere145, tatsächlich erfolgreicher Startresult8fc6,
|
||||
öffentlicher Zeitpinc31 und das nativ qualifizierte Python-ARMimagee6f2
|
||||
(Rootreceipt6431222d). Vor/nach den Clients bleiben originale Prozess-/Socket-
|
||||
und Source-/Runtime-/Chronygenerationszeugen Pflicht. Root verknüpft seine
|
||||
getrennten Corehistory-Vorher-/Nachherreceipts; hier kein neuer SQLreader.
|
||||
|
||||
Host-UID/GID10001 und eigener Container-UID/GID10001 erzeugen jeweils eine eigene
|
||||
256-Bit-CSPRNGnonce und Verifierinkarnation. Der Container ist read-only, nonet,
|
||||
nocaps, NNP und benutzt seinen Standard-PIDnamespace; Brokerpeer-PID0 wird
|
||||
explizit erwartet. Der Hostclient muss den tatsächlichen Broker-PID sehen.
|
||||
Zwischen beiden positiven Requests erhält RootUID0 keine signierten Bytes.
|
||||
Root hat eigene CSPRNG-IDs und Schema-Testgenerationen ausdrücklich für diese
|
||||
reinen Codec-/Namespacefixtures erlaubt: keine eingeschriebenen Geräte,
|
||||
Windows-DBbindung, mTLS-, Clock-/Sync- oder Jobautorität wird behauptet.
|
||||
|
||||
Requestreihenfolge entspricht exakt RustSerde, inklusive explizitem null für
|
||||
helper_image_sha256. Der gesamte Requesthash, Serverinstance, Boot, Key-ID und
|
||||
Generation sowie Qualitätsgrenzen werden geprüft. OpenSSL prüft mit ausschließlich
|
||||
öffentlichem SPKI die Ed25519-Signatur über `RMM-TIME-ATTESTATION/v1\0` und die
|
||||
exakten Payloadbytes. Private Signerbytes werden nicht gelesen. Der Controller
|
||||
wird als `broker_signature_acceptance.py` Root0600 unter seinem Hashparent gehalten.
|
||||
|
||||
Lokal AST und drei gezielte Guardgruppen bestanden: kanonische Requestbytes,
|
||||
Bindungs-/Domain-/Publickeyprüfung mit ausdrücklich ersetzter Signaturautorität,
|
||||
sowie feste Clientgrenzen und Vorprüfungs-/Intentreihenfolge. Keine tatsächliche
|
||||
Signatur erzeugt oder Zielabfrage ausgeführt. Zwei reine Guardhelferfehler
|
||||
(mkdir-Syntaxfragment und die frühere host-read-Intentreferenz) wurden in getrennten
|
||||
Guardkopien korrigiert; Produktquelle und Originalfehlerlogs blieben unverändert.
|
||||
Tatsächliche Signaturen und Namespace-/Root-Deny-Nachweise bleiben Rootaufgaben.
|
||||
|
||||
## Tatsächlich nativ auf dem permanenten Server bestanden
|
||||
|
||||
Source `a8afe8a2167f91e743e8c976b58d9f5227fa64914ad492ffc489b0dc98392585`.
|
||||
Readonly Preflight Exit0, Receipt
|
||||
`d5c06a881d4a7493323adb9c7dfdc3c566ee208a6681e7e07b547c8141515e6a`.
|
||||
Einmalige Ausführung Exit0, Receipt
|
||||
`35b35f4e48e9806a877f3e9f2ab53eaf2ac450b492295ad57e17677d6147767c`.
|
||||
Beide unterschiedlichen CSPRNG-Challenges wurden tatsächlich signiert und mit
|
||||
OpenSSL/öffentlichem Ed25519-Key verifiziert. HostpeerPID2576117, ContainerpeerPID0
|
||||
bei eigenem Standard-PIDnamespace; beide ClientsUID/GID10001. RootUID0 erhielt
|
||||
EOF ohne signierte Bytes. Hostfehlergrenze295608676ns bei Syncalter320109975916ns,
|
||||
Container295463150ns/320435768611ns; beide innerhalb der unveränderten Grenzen.
|
||||
|
||||
Originalresultat
|
||||
`38ed1a3079f20438fe07a57f1bfa5a37348bdec9fc7780d7822ca3d6967e5ea1`;
|
||||
separate Originalnachlese Exit0 ohne failure, Receipt
|
||||
`4b442a9022f1ee56f8e851e25ad323d630b220cf47aa8169b83b9c4412c50b8d`.
|
||||
Externe Core-/Runtimezeugen vor/nach exakt gleich, beide
|
||||
`616effee49e79ff10112bb84cda3212029e489d84faaf8d9ae0d8901fce2b01a`;
|
||||
Windows0/0/0/0, Linux31/31/27/0, geschlossene Rootpolicy. Kein privater
|
||||
Signerread, weiteres Dienststarten/Neustarten, HTTPdeployment oder Windowsjob.
|
||||
Diese native Abnahme belegt Brokertransport/Namespaces/UID-Deny und zwei echte
|
||||
Signaturen. mTLS-Gerätebindung und unabhängige Windows-Rollenzeit sind weiterhin
|
||||
separate offene Abnahmen; Fixtureidentitäten sind ausdrücklich keine Geräte.
|
||||
@@ -1,147 +0,0 @@
|
||||
# Einmaliger Start des installierten lokalen Zeitbrokers
|
||||
|
||||
Quellenstand2026-11-15, Spezifikation1.23. Tatsächlicher einmaliger Serverstart
|
||||
und separate Nachlese bestanden; UDS-/Signaturabnahme bleibt separat offen.
|
||||
`deploy/server_time_broker_start_acceptance.py` enthält ausschließlich den
|
||||
Start-/Effektivkonfigurations-/Prozess-/Socketnachweis. Unixrequests und echte
|
||||
Zeit-Signaturabnahme folgen separat durch Root. Keine RMM-Jobs, HTTPdeployment,
|
||||
Windowsgateänderung oder Umgehung der WebUI-Genehmigungsgrenze.
|
||||
|
||||
Root hat Schlüssel-, Gruppen- und Binary-/Unitinstallation bereits getrennt
|
||||
nachgewiesen. Installationsresultat SHA256
|
||||
`b52aa57971fcad5a9ff3780765f4712d4029d078aab71f94eaec6d805a642f71`,
|
||||
Installationsaufrufreceipt
|
||||
`5d99c54fb747737991d98ec65ee715fb7c1820af5814fd36f1dbe31ed833ed03`,
|
||||
separate Nachlese
|
||||
`0f1c2bcbe7ffca5cf8f40c40c84e836bf0659b67032e89bdfadd1ef1b9b4a03b`.
|
||||
Dabei blieben Reload, Start und Enable ausdrücklich false. Der Controller
|
||||
bindet außerdem exakt die eigenen ursprünglichen Key-/Groupresultate.
|
||||
|
||||
## Feste geschützte Eingänge
|
||||
|
||||
Der bestehende Bootstrapcontroller2fdcbc95 wird ausschließlich aus seinem
|
||||
Content-addressed Root0600-Pfad als `broker_bootstrap.py` geladen. Sein echter
|
||||
Context erhält unverändert die c15-Generation-/Qualitätsbelege, aktuellen
|
||||
Chronypin, Boot, Source, Konfiguration, Namespace und API-/Gatewayruntime.
|
||||
Der neue Startcontroller muss ebenfalls Root0600, ein regulärer Link, feste
|
||||
Datei `broker_start_acceptance.py` unter seinem eigenen vollständigen Hashparent
|
||||
sein; sein FD wird gehalten und vor Effekten erneut geprüft.
|
||||
|
||||
Ein eigener `InstalledProof` hält die originalen erfolgreichen Installations-
|
||||
records, Unit, Binary und öffentlichen Zeitpin. Die private Signerkonfiguration
|
||||
wird ausschließlich mit `O_PATH|O_NOFOLLOW` auf ihre originale Identität und
|
||||
Metadaten geprüft: der Controller liest keinen Seed. Binary bleibt exakt
|
||||
1067136Bytes/SHA256 `5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201`,
|
||||
Unit657Bytes/SHA256 `4792bfb65763f5a5146044d2ba152acd0a876b66c29d8cc66c16a5250214af2c`.
|
||||
Keine Übernahme fremder Objekte, keine Umgehung des `UnitComposition`-
|
||||
Konstruktors: der separate qualifizierte InstalledProof erlaubt ausschließlich
|
||||
den originalen eigenen Unitinode. Alle übrigen festen Control-/Attached-/
|
||||
Generator-/Prefix-/typweiten Drop-ins, Alias- und eigenen Dependencypfade
|
||||
verweigern. Originaler Manager-UnitPath und merged-usr-Alias bleiben gebunden.
|
||||
|
||||
## Geplant, nicht ausgeführt
|
||||
|
||||
```text
|
||||
python3 -I /var/lib/rmm-time-source-operators/<reviewterSHA>/broker_start_acceptance.py host-preflight
|
||||
python3 -I /var/lib/rmm-time-source-operators/<reviewterSHA>/broker_start_acceptance.py host-start
|
||||
python3 -I /var/lib/rmm-time-source-operators/<reviewterSHA>/broker_start_acceptance.py host-read
|
||||
```
|
||||
|
||||
`host-preflight` ist ausschließlich lesend. Er darf die vorhandene Unit über
|
||||
D-Bus zur Auskunft laden; weder Reload noch Start folgt daraus. Für die
|
||||
wirkende Phase muss `5b358997-3abc-43db-945f-f41855b4e3c0/broker-start-acceptance-v1`
|
||||
vorher fehlen. Vor Daemonreload entsteht der dauerhafte create-only Intent,
|
||||
danach ein eigener Reloadintent. Genau ein `systemctl daemon-reload` und dessen
|
||||
Exit werden gespeichert. Erst die vollständige erneute geladene Prüfung erlaubt
|
||||
den eigenen Startintent und genau ein `systemctl start -- rmm-time-broker.service`.
|
||||
Kein Enable, Restart, Stop, Cleanup, Adopt oder retry. Verlorene Antwort oder
|
||||
Fehler erlaubt nur `host-read` des ursprünglichen Falls; eine spätere erfolgreiche
|
||||
Beobachtung schreibt ein fehlendes oder gescheitertes Resultat nicht um.
|
||||
|
||||
Vor Start werden echte typisierte D-Buswerte geprüft: exaktes Fragment ohne
|
||||
Drop-ins, static/nicht enabled, kein pending Job, ausschließlich ein ExecStartEx
|
||||
mit genau dem Binary und ohne Zusatzargument/Flag sowie sämtliche anderen
|
||||
Exec- und ExecEx-Arrays leer. Root/_chrony, Supplementary10001, Typeexec,
|
||||
Restartno, NRestarts0, Bounding524290/0x80002, Ambient0, NNP, ProtectSystemstrict,
|
||||
ProtectHomeyes, PrivateTmp/Devices, AF_UNIX-only, IPv4/IPv6-Denyall/Allowleer,
|
||||
exakte Debug-/ptrace-/process_vm-Denylist, fester eigener ReadWritePath, UMask0077
|
||||
und Corelimit0 bleiben erforderlich. Keine nicht vorhandene Eigenschaft wird
|
||||
als Null erfunden. Die echten12 bereits unabhängig gelesenen ABIwerte stammen
|
||||
von systemd259.5 Ubuntu, Rootreceipt
|
||||
`77c98ef563837e36c487227142258490d57b630b56b2c2f8db6474a51263aa0d`.
|
||||
|
||||
Die Typen und Execarrayverträge folgen den Primärquellen für
|
||||
[Service](https://github.com/systemd/systemd/blob/main/src/core/dbus-service.c),
|
||||
[Execution](https://github.com/systemd/systemd/blob/main/src/core/dbus-execute.c),
|
||||
[Unit](https://github.com/systemd/systemd/blob/main/src/core/dbus-unit.c) und
|
||||
[IP-Cgroupgrenzen](https://github.com/systemd/systemd/blob/v255/src/core/dbus-cgroup.c).
|
||||
Der tatsächliche Root-ABIbeleg bindet die konkrete installierte Ausprägung,
|
||||
keine Vermutung aus einem anderen lokalen Systemd.
|
||||
|
||||
Nach Start werden tatsächliche PIDFD, Birth, InvocationID, gehaltenes
|
||||
/proc/exe gegenüber originalem Binaryinode, UID0/GID989, Supplementarygruppen
|
||||
nur aus0/989/10001 mit10001, Effective/Permitted/Bounding0x80002, Ambient0,
|
||||
NoNewPrivileges1, Seccomp2, Hostuser-/PID-/Cgroupnamespaces, Rootmountread-only
|
||||
und genau der eigene Cgroupprozess geprüft. Ein begrenztes lesendes Warten
|
||||
auf den Socket ist keine Wiederholung des Starts. Der Listener muss Root:10001,
|
||||
0660, Singlelink und ein tatsächlicher eindeutiger AF_UNIX-Streamlistener
|
||||
sein, dessen Kernelinode ein FD genau dieses unveränderten Brokerprozesses hält.
|
||||
Es wird keine Verbindung und keine Signatur angefordert.
|
||||
|
||||
## Grenzen und tatsächliche lokale Prüfungen
|
||||
|
||||
Der Sharedproof prüft Vorher/Nachher Runtime-/Pin-/Konfigurations-/Boot- und
|
||||
Chronygeneration. Er behauptet keine SQL-Corehistorienprüfung. Root muss die
|
||||
bereits vorhandene getrennte `server_closed(CaptureAccess(Main))`-Nachlese vor
|
||||
und nach dem tatsächlichen Start verwenden und beide externen Receipts mit dem
|
||||
Original-Startfall verbinden. Dieser Controller führt keinen neuen SQLreader
|
||||
und keine Credentialsdatei ein.
|
||||
|
||||
Lokal tatsächlich bestanden: Python-AST und drei gezielte Guardgruppen. Die
|
||||
zwölf tatsächlichen Root-ABIwerte wurden benutzt; übriger geladener Zustand
|
||||
war ausdrücklich Fixtureautorität. Änderungen von Drop-in, CAP_SYS_TIME,
|
||||
Filter, argv oder zusätzlichem Exec wurden verweigert. Eigene Scratchfixtures
|
||||
belegten den exakt erlaubten Unitinode sowie Prefix-/Dependency-Deny. Die
|
||||
statische Reihenfolge belegte genau zwei Wirkkommandos und deren dauerhafte
|
||||
Intents mit vollständiger Effektivprüfung dazwischen. Keine Targets, Seeds,
|
||||
Schlüssel-, Gruppen- oder Dienstwirkungen. Der erste Guard las die zusätzliche
|
||||
Root-RPC-Hülle falsch und brach vor Prüfungen ab; eine getrennte Guardkopie
|
||||
prüft Exit/Stderr und dekodiert korrekt. Produktquelle und ursprüngliche
|
||||
Fehlerlogs blieben unverändert.
|
||||
|
||||
Die nativen Unit-/Prozess-/Socketprüfungen, tatsächlicher einmaliger Start,
|
||||
separate Nachlese sowie positive und negative UDS-/Signaturfälle sind noch
|
||||
offen. Ein Start-/Listenerbeleg allein qualifiziert keine Signatur oder
|
||||
Windowsbereitschaft; der Broker muss vor jeder tatsächlichen Signatur erneut
|
||||
eine aktuelle native Quelle messen.
|
||||
|
||||
## Tatsächlich ausgeführt auf dem permanenten Server
|
||||
|
||||
Controller `e1458cb3feecd3d3302f2fccaff4850cfc8c403ee3314563f5f641e7c8bdfc39`:
|
||||
readonly Preflight bestanden, Receipt
|
||||
`51995f5dfb0b6e668246f423843f4b7aa67b4ab0765b60a54cb7dd0c6f3db5ed`.
|
||||
Vorheriger622-Preflight scheiterte vor Phasenanlage/Reload/Start an einer
|
||||
unzutreffenden InvocationID-Annahme. Typisierte tatsächliche ABI-Nachlese
|
||||
`201b306fab8efb4ebd4fa22e8c6925a735eaa2dea9651581596ae5c97436c410`
|
||||
belegt `ay=[]` für den noch nie gestarteten Dienst. Die unabhängig geprüfte
|
||||
Korrektur verlangt inaktiv exakt[] und laufend weiterhin16gültige, nicht
|
||||
sämtlich nullwertige Bytes. Kein laufender Null-Fallback.
|
||||
|
||||
Genau ein Daemonreload und ein Start, Exit0, Rootreceipt
|
||||
`5177b5a32d13a053e21197513b029bc920c6e40ed4c2fc793e20d5d74e6eb87a`.
|
||||
Originalresultat
|
||||
`8fc6ed5193f9802b7686a93523730c7e805595415c8e887552ffcf4224968d4d`;
|
||||
separate Originalnachlese
|
||||
`731527c0e30aaaddf386f414ffcdd11333000b9897b856cb994da1eccd255d54`
|
||||
bestätigt vollständige Records ohne failure. Tatsächlich PID2576117,
|
||||
Birth18167723, UID0/GID989, Supplementary989/10001, Caps0x80002, NNP,
|
||||
Seccomp2, Rootmountreadonly und genau ein eigener Cgroupprozess. Eigener
|
||||
SocketRoot:10001/0660, Kernelinode8409245 und BrokerFD10 gebunden.
|
||||
|
||||
Externe tatsächliche SQL-Core-/Runtimezeugen vor/nach exakt gleich, beide
|
||||
SHA256 `616effee49e79ff10112bb84cda3212029e489d84faaf8d9ae0d8901fce2b01a`.
|
||||
Windows0/0/0/0, Linux31/31/27/0, Rootpolicycf15 geschlossen.
|
||||
Chronygeneration, Pins, Signermetadaten und RMM-Runtime erhalten. Kein Enable,
|
||||
Restart, weiterer Chronyrestart, Unixrequest, Signieren oder HTTPdeploy;
|
||||
Windowsjobgate unverändert geschlossen. Dieser Schritt belegt ausschließlich
|
||||
Start/Effektivhärtung/Prozess/Listener, keine vollständige Windowsabnahme.
|
||||
@@ -1,146 +0,0 @@
|
||||
# Fixed time gateway deployment preparation
|
||||
|
||||
Source-only, no deployment executed by this author. The operator uses only the
|
||||
already qualified ARM64 image422c2c28 from stage
|
||||
`d11a6fb7-cfdd-41b2-87c5-b48a2cfd2e27`, source2af. It performs no rebuild and
|
||||
does not package, replace or delete existing WebUI files. The original seven
|
||||
web files, their bytes and inodes, index95d6f905, compose d2044b0e, PKI/key
|
||||
metadata, closed policycf15, PostgreSQL container/volume and Chrony generation
|
||||
remain bound. Root independently captures immutable31/31/27 closed core history,
|
||||
Windows0 and native-role evidence before/after; this controller does not claim
|
||||
those external witnesses from container checks alone.
|
||||
|
||||
`deploy/server.time-broker.compose.yaml` is the199-byte fixed optional overlay,
|
||||
SHA256 `dbd08faea8f58c032562d822f4191c719f9a6828b00d6c368fc2596155a9a314`.
|
||||
Only gateway receives the read-only `/run/rmm-time-source` bind, with
|
||||
`create_host_path: false`. API receives no time mount. No port, environment,
|
||||
authentication, TLS, policy or capability changes are added.
|
||||
|
||||
`cloud_server_upgrade.deploy` automatically includes that exact Root0:0/0644
|
||||
single-link overlay whenever installed. Wrong bytes, owner, mode, hardlinks or
|
||||
symlink/unsafe ancestry deny before UI/tag/migration effects, with repeat checks
|
||||
before each backend effect. Absence retains the original compose invocation.
|
||||
A stage reserved by the fixed operator cannot later be replayed through generic
|
||||
deploy. The new reviewed public upgrade tool is installed with a retained old
|
||||
copy, so future upgrades keep the mount.
|
||||
|
||||
`deploy/server_time_gateway_deploy.py` has only `host-preflight`, one
|
||||
`host-deploy`, and original `host-read`. Root stages `gateway_deploy.py` plus the
|
||||
two fixed public files under the controller's content hash. It checks source209
|
||||
files and original build result, actual old6f API/GW containers and runtime tag,
|
||||
UI CAS, PostgreSQL identity, and actual broker start8fc6/e145 proof. Live broker
|
||||
checks retain the original process/birth/image/socket independently of the old
|
||||
6f application IDs; no old InstalledProof freshness check is bypassed or reset.
|
||||
The separate C31 public key is pinned. A missing actual signature-PASS result
|
||||
and separate read hash hard-denies before deployment.
|
||||
|
||||
The final source pins actual signature controllera8afe8a2 and result
|
||||
`38ed1a3079f20438fe07a57f1bfa5a37348bdec9fc7780d7822ca3d6967e5ea1`,
|
||||
with separate read receipt
|
||||
`4b442a9022f1ee56f8e851e25ad323d630b220cf47aa8169b83b9c4412c50b8d`.
|
||||
Both host and default-container UID/GID10001 signatures were verified in that
|
||||
separate fixture. They do not attest mTLS, an enrolled Windows identity, sync
|
||||
readiness or clock authority. The deploy operator sends no signature request.
|
||||
|
||||
New case `fb87aa88-2b67-4cff-9c90-4cd713380889` writes intent before installing
|
||||
the create-only overlay, persistent upgrade tool or moving the runtime tag.
|
||||
Each tag, migration and API/GW recreate has its own intent and retained exit/log.
|
||||
Migration uses the existing compiled image once; actual versions1–14 must become
|
||||
1–15. Only API/GW are forcibly recreated, without dependencies or rebuilds. All
|
||||
old role mounts remain equal, plus exactly the gateway-only read-only broker
|
||||
mount. Broker, Chrony and PostgreSQL are not restarted.
|
||||
|
||||
Failure/lost reply permits only the same case's `host-read`, with no retry,
|
||||
automatic rollback, reset, enrollment, key generation, signature request or
|
||||
API/DB approval. The existing WebUI approval boundary for every RMM job remains
|
||||
unchanged. Readback performs no Docker/service/SQL/time action.
|
||||
|
||||
## Tatsächlicher lesender Vorabcheck
|
||||
|
||||
Controller `e14aeabfd7d3a8ab298985706dc26014e0ad540a1c3ef40cf57e1a65b77b7f3b`
|
||||
mit unabhängigem QuellenreviewPASS. Auf dem permanenten Server wurde ausschließlich
|
||||
`host-preflight` ausgeführt: Exit0, Rootreceipt
|
||||
`9c08cce4f21da8a895eabeea80c4ff1e6068346fb5b46b4fe95b0ee2d30db1e9`.
|
||||
Geschützte Sources/Buildresultate, bestehende6f-Runtime, alleUI-Dateien, PKI-,
|
||||
Broker-/Signatur-/Pinbelege, PostgreSQL und Migrationsstand1..14 akzeptiert.
|
||||
Noch kein Deploymentfall angelegt, Overlay installiert, Image getaggt, Migration
|
||||
oder Recreate ausgeführt. Die Runtime bleibt6f;422 bleibt gebauter Kandidat.
|
||||
Vor tatsächlichem `host-deploy` folgen die getrennten vollständigen SQL-
|
||||
Historienzeugen, nachher deren Originalvergleich sowie Endpoint-/Windowsnachweise.
|
||||
|
||||
## Erster Bereitstellungsversuch am 15. November
|
||||
|
||||
Der Server installierte die schreibgeschützte Socket-Einbindung und das
|
||||
Upgrade-Werkzeug. Vor dem Wechsel des Image-Tags brach der Vergleich der
|
||||
Containerkonfiguration ab. Docker liefert die vorhandenen Mounts in wechselnder
|
||||
Reihenfolge. Die getrennte Nachlese zeigte bei API und Gateway ausschließlich
|
||||
eine andere Reihenfolge, PostgreSQL war identisch. Alle Mountattribute stimmten
|
||||
nach Sortierung nach Zielpfad überein.
|
||||
|
||||
Der ursprüngliche Versuch bleibt fehlgeschlagen. Es gab keinen Tag-, Migrations-
|
||||
oder Containerneustartauftrag. Der Vorher-/Nachhervergleich über 18 Tabellen
|
||||
und die Geräteidentitäten war identisch. Die Datenbank steht auf Migration 14.
|
||||
Ausführung `7f11898cd87e312066cdbcf9909b72a867bf3e6c1b1ff6b905f81974fa4391e5`,
|
||||
Nachlese `eafe1c067aa3f8bb8cfe1203636319a24fba705a18a7a2166b568c5f4c81cda6`,
|
||||
Mountvergleich `a06256380d2febeddb506ffe17a614325b25c25464f45b4d022c82f644a0fc0f`.
|
||||
|
||||
## Bereitstellung und Nachprüfung am 15. November 2026
|
||||
|
||||
Auf `discovery.ease-technologies.de` laufen API und Gateway mit dem geprüften
|
||||
ARM64-Image `422c2c28`. Die Fortsetzung verglich alle Docker-Mountattribute nach
|
||||
eindeutigem Zielpfad. Sie führte anschließend nur das Setzen des Image-Tags,
|
||||
Migration 15 und den Austausch der zwei Anwendungscontainer aus. Alle drei
|
||||
Befehle endeten mit Exit 0. PostgreSQL behielt seinen Container und sein
|
||||
Volume. Nur das Gateway erhielt die schreibgeschützte Einbindung des
|
||||
Zeitbroker-Sockets. Der ursprüngliche Abbruch ist separat erhalten.
|
||||
|
||||
Beide internen TLS-Healthchecks lieferten 200 und `ok`.
|
||||
Die private Anmeldung meldete das dev/test-Profil. Am öffentlichen Gateway
|
||||
lieferten die sechs geprüften Verwaltungsrouten einschließlich WebUI und MCP 404.
|
||||
Der Agentenschlüssel-Endpunkt erforderte weiterhin Geräteauthentifizierung (401).
|
||||
Die Daten der 18 geprüften Historientabellen und die Geräteidentitäten stimmten
|
||||
mit der Vorhermessung überein, offene Jobs 0. Migrationen 1 bis 15 erfolgreich.
|
||||
Die Prüfung des signierten Zeitabrufs aus dem Windowsgast folgt separat.
|
||||
|
||||
| Prüfung | SHA-256 des Belegs |
|
||||
| --- | --- |
|
||||
| Lesender Vorabcheck | `77d3d1011d5a6f7981306910edd535310e09d10cb161c3a30e79fe4b037802c1` |
|
||||
| Bereitstellung | `06607548806d47ef8378ae3d569e5779943cb67519305975d2665cc872fc87a3` |
|
||||
| Separat gelesenes Serverergebnis | `3017634f101ee8aff62988f195ccb3a7a8b9e03eaa48b8fb339af9ceb3ad2b4b` |
|
||||
| Nachlese | `b8cc94a9f9ba4d1782e052ef0bf317b5229b9578c646bf393c24b33a9507fab4` |
|
||||
| Historie nach Migration | `cb72a95afc94c9d96ae78a38495e62b59db4598b8ea16996b00d83e2cd6c08a7` |
|
||||
| TLS und öffentliche Zugriffstrennung vor und nach Migration | `f381279d3e5ebbded79b0b3ad587dee09ebf7adbbbf47d9099584f00ddcd95d5` |
|
||||
|
||||
### Wiederverbindung der beiden Geräte
|
||||
|
||||
Nach dem Gatewaywechsel meldeten sich beide bestehenden Geräte selbständig
|
||||
wieder über WSS. Die gespeicherten Daten des Entwicklungsmandanten zeigten am
|
||||
15. November um 12:38 UTC für Linux einen 12 Sekunden alten Kontakt und einen
|
||||
18 Sekunden alten Inventareingang. Für Windows betrugen die Werte 23 bzw.
|
||||
146 Sekunden. Die Verbindungsgenerationen waren 153 und 91. Dafür war kein
|
||||
Live-Auftrag erforderlich. Beleg der lesenden Abfrage
|
||||
`9ce23669ff03a7ec5a08e10437a009a7ae617f472614d161ab082e17c02c2095`.
|
||||
|
||||
Auch die normale MCP-Schnittstelle lieferte beide Geräte im selben Mandanten
|
||||
über `inventory.list_devices`, `inventory.get_device` und
|
||||
`monitoring.get_health`. Linux und Windows standen auf `online`, mit
|
||||
29 bzw. 18 Sekunden seit dem letzten Kontakt. Die Liste enthält außerdem
|
||||
zwei widerrufene Altinstallationen. Die erste Auswertung hatte fälschlich
|
||||
genau zwei Listeneinträge insgesamt erwartet. Die korrigierte Prüfung glich
|
||||
die beiden aktiven Gerätekennungen und den Widerrufsstatus separat ab.
|
||||
Der mandantenweite Gesundheitswert lautete `unknown`. Das Inventar war
|
||||
für beide aktiven Geräte abrufbar. MCP-Beleg
|
||||
`f6fe5ab254c9ca3fad238271601b0f8df2029b6b6138c47ff000d55071ab70cf`.
|
||||
|
||||
Migration 15 hat die beiden Tabellen für Agent-Releases und Updateartefakte
|
||||
auf dem permanenten Server angelegt. Eine lesende Abfrage im PostgreSQL-Katalog
|
||||
bestätigte für beide Tabellen erzwungene Row-Level Security, die Mandantenpolicy
|
||||
und den aktiven Unveränderlichkeits-Trigger. Die Anwendungsrolle darf lesen
|
||||
und einfügen. UPDATE und DELETE sind ihr entzogen. Beide Tabellen waren leer.
|
||||
Beleg `623fe75484f337996e784b24dae0b0be29a4596f2a6842841c7636a99daaf754`.
|
||||
|
||||
Ein zusätzlicher Abruf vom Entwicklungsrechner über den öffentlichen DNS-Namen
|
||||
und Port 443 prüfte den externen Zugang ohne Geräteidentität. TLS wurde gegen
|
||||
die öffentliche CA der Windows-Installation geprüft. POST an die Zeitroute
|
||||
lieferte 401, GET an `/`, `/auth/config` und `/mcp` jeweils 404.
|
||||
Beleg `346c2c60635e52cb758f3e6092f7187a9c35203d1fff3c8f18d1dbca73607607`.
|
||||
@@ -1,88 +0,0 @@
|
||||
# One native source sample for the proven c9 generation
|
||||
|
||||
The user-approved Chrony generation change actually passed. Generation result
|
||||
`d648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4`
|
||||
and separate Root read receipt
|
||||
`58970ef8e89af86b68fdbbf2cb5119210bcb37cec603feb23b4f6030b0b36623`
|
||||
bind the new daemon and public pin. This is a non-quality bootstrap result.
|
||||
No native source sample or signed time authority follows from it.
|
||||
|
||||
`deploy/server_time_source_new_generation_probe.py` defines one new create-only
|
||||
subphase `/var/lib/rmm-time-source-bootstrap/c9a94f94-eecd-4c66-933d-c45c1a79c7a8/probe-native-source-v1`.
|
||||
It executes only the original root:root 0500 AArch64 probe from the 5b build:
|
||||
848,632 bytes, SHA256
|
||||
`216b4d6a0f29ef47576f5ccc469954623141e55d7b43bd73175c1d956363bbbd`.
|
||||
The named-client provider remains exactly source3fd. The fixed systemd-run
|
||||
profile remains root:989 with empty supplementary groups, NoNewPrivileges,
|
||||
CAP_SYS_PTRACE plus CAP_DAC_OVERRIDE, strict root filesystem protection,
|
||||
AF_UNIX only, IPAddressDeny, private tmp/devices, the original syscall deny list,
|
||||
3-second runtime limit and 10-second owned command watchdog. Only the unit/case
|
||||
identity changes. There is one sample attempt and no automatic retry.
|
||||
|
||||
Two proofs deliberately remain separate:
|
||||
|
||||
- `QualifiedBuild` reads and holds the original preflight/stage/build records,
|
||||
archive0da5, manifestbdf7, complete verified workspace and both original
|
||||
root500 ELF artifacts. The build result is pinned to58eaf011. These records
|
||||
describe the old generation historically. No old `pin.Original` constructor,
|
||||
freshness check, monkeypatch, PID adoption or reset is used.
|
||||
- `SharedGenerationProof(pin)` imports exactly the protected Root600 fac/ecb/d5
|
||||
source bytes. It retains original FDs for all17 actual c9 records with their
|
||||
exact Root read hashes and metadata; the other21 fixed record names must stay
|
||||
absent. It checks the195-byte current public pin395f and complete metadata
|
||||
against the result, after/CAS/new-pin records and old194-byte backup. Fresh
|
||||
complete ecb process/cgroup/socket/runtime/boot observations must match the
|
||||
new after record. Public configuration, typed D-Bus commands and actual
|
||||
AppArmor/ACL namespace must equal d5's recorded after state.
|
||||
|
||||
The shared read-only API exports `CASE_ID`, `QUALITY_PHASE`,
|
||||
`SharedGenerationProof(pin)`, `.operator`, `.operator_guard`, `.artifacts`,
|
||||
`.source_sha`, `.manifest_sha`, `.expected`, `.public_pin_raw`,
|
||||
`.public_pin_metadata`, `.target_directories`, and `.records` mapping Path to
|
||||
original raw bytes/metadata. `.fresh()` returns the six actual new pin fields;
|
||||
`.namespace_verify()` returns the checked namespace. `.close()` releases all
|
||||
held FDs. Directory identities use dev/inode/UID/GID/mode and ACLs, permitting
|
||||
incidental parent directory timestamps from later owned broker bootstrap files.
|
||||
The shared proof never reads signer-key contents or assumes a broker must remain
|
||||
absent. The one native-probe host action separately enforces no broker/time key.
|
||||
|
||||
Intent, before witness and a separate start intent precede the only execution.
|
||||
The raw log and actual exit are preserved before sample validation. The positive
|
||||
schema is exactly the previous ca89 sample schema: same boot UUID, exact known
|
||||
fields, integer time domains, total error at most500ms, reference age at most1h,
|
||||
kernel state0..4, and explicit false clock/signature authority. Before/after
|
||||
witnesses must be identical. Result, raw log and both witnesses are hash-linked.
|
||||
`quality_proof(expected_result_sha256)` validates that same format read-only and
|
||||
returns the four held records for a broker adapter. A caller must already pin a
|
||||
real independently reviewed positive result hash; None cannot open this gate.
|
||||
|
||||
`host-read` reads only the original fixed subphase and metadata. It runs no
|
||||
preflight, service command, probe, time query or effect. A lost reply or partial
|
||||
phase permits only that original read, never a new phase or replay. No command
|
||||
changes clocks, Chrony service/configuration, public pin, capabilities, ACL/MAC,
|
||||
signer keys, broker installation, RMM jobs or application runtime.
|
||||
|
||||
Status: source/local qualification only. Root must separately review, stage
|
||||
`new_generation_probe.py` as Root600 under its content hash, then execute one
|
||||
`host-probe` and a separate `host-read`. Native quality remains unproven until
|
||||
those actual records pass; all old5b failed probe cases remain unchanged.
|
||||
|
||||
## Tatsächlich native Qualität auf dem permanenten Server bestanden
|
||||
|
||||
Originalfallc9/`probe-native-source-v1`: genau eine Ausführung des
|
||||
unveränderten AArch64-Probes216b/848632Bytes nach unabhängigem Review.
|
||||
Tatsächlicher Exit0 und striktes Sample validiert. Kernelstate0, konservativer
|
||||
Gesamtfehler50.833923ms, tatsächliches gutes Quellensync43.596197206s alt;
|
||||
keine Werte aus Pollzeit oder bloßem Heartbeat abgeleitet. Before/After-Zeugen
|
||||
identisch e72ce5f6; Runtime, Boot, neue Pin-/Chrony-/Configbindung erhalten.
|
||||
Rootreceipt `1aab3af930648aed260c4c66a1c3ff068656cae016fcc301f052880926f99c93`.
|
||||
|
||||
Separater ausschließlich lesender Originalrückabruf de6273d1 bestätigt Exit0,
|
||||
Sample, identische Zeugen und Resultat-SHA256
|
||||
`ab8a6511517c6e3c01db2351ccdc5c48c73f34112c9ac863d0ea64de46665933`;
|
||||
Readreceipt `7005ef54759412cd0d95e558ceebbf524a55c04bf6641c8241161e0d5e81fbf3`.
|
||||
Dieser neue erfolgreiche Beleg ersetzt keinen früheren Fehler und ist keine
|
||||
Signatur oder Jobgenehmigung. Kein Signer/Key/Broker/HTTPendpoint oder
|
||||
Windowsclock wurde durch die Probe aktiviert. Erst dieser konkrete aktuelle
|
||||
Nachweis darf den getrennten geschützten Signerbootstrap ermöglichen. Jeder
|
||||
spätere Brokerbeleg benötigt trotzdem seine eigene neue NativeTimeSource-Probe.
|
||||
@@ -1,196 +0,0 @@
|
||||
# Windows: Geräte-TLS bei passiver Telemetrie erneuern
|
||||
|
||||
Quellenstand 2026-11-15, Spezifikation 1.23. Der Windowsdienst verwendet jetzt
|
||||
einen eigenen `RotationStore` und den vorhandenen gemeinsamen mTLS-Transport.
|
||||
Die portable Logik ist nativ auf Linux und Windows geprüft. Dies ist keine
|
||||
Rotation der permanenten Windowsidentität und keine native
|
||||
Windows-Renewal-/Datei-I/O-Abnahme.
|
||||
|
||||
Der tatsächliche Serverendpoint `POST /agent/v1/certificates/renew` verlangt
|
||||
eine noch gültige, registrierte mTLS-Identität. Er prüft die signierte P-256-CSR,
|
||||
stellt ein neues Gerätezertifikat für dieselbe Agent-ID aus, erhöht die
|
||||
Verbindungsgeneration und akzeptiert den vorherigen Fingerprint 300 Sekunden.
|
||||
Die exakten CSR-Bytes sind der serverseitige Wiederholungsschlüssel; eine
|
||||
Wiederholung innerhalb des zulässigen alten Identitätsfensters liefert dasselbe
|
||||
bereits gespeicherte Zertifikat. Weder Reenrollment noch Widerruf sind enthalten.
|
||||
|
||||
Der Client prüft alle 30 Sekunden, ob das Zertifikat mindestens 20 Tage alt ist
|
||||
oder höchstens zehn Tage Restgültigkeit hat. Automatische Erneuerung läuft in
|
||||
diesem Schnitt ausschließlich bei `enable_jobs=false`. Ein dauerhaftes Pending
|
||||
wird nach Prozessneustart und vor einem neuen Transport-Hello wiederaufgenommen,
|
||||
ohne zuvor einen erfolgreichen WSS-/HTTPS-Kanal vorauszusetzen. Während eines
|
||||
Pending ist die Umschaltung auf Jobbetrieb verweigert. Nach erfolgreichem Commit
|
||||
baut der Client eine neue Verbindung auf; Heartbeats und unbestätigte
|
||||
Inventarbytes behalten den bestehenden Journalvertrag.
|
||||
|
||||
Die bisherigen Dateien `identity.json`, `device.pem` und `device.key` werden
|
||||
nicht ersetzt. Nur vor der ersten Versionswahl wird das bestehende Paar als
|
||||
Initialversion aufgenommen. Jeder neue private Schlüssel entsteht mit
|
||||
`CreateNew` als `device-<UUID>.key` im bestehenden geschützten State. Das
|
||||
exklusive Dateihandle verweigert gleichzeitiges Ersetzen; Reparsepoints und
|
||||
Hardlinks werden abgewiesen. Die bestehende SYSTEM-/Administratoren-/Service-
|
||||
SID-DACL wird vor dem ersten Schlüsselbyte geprüft, anschließend werden die
|
||||
Dateibytes mit Write-through und `sync_all` geflusht. Das gehaltene
|
||||
Verzeichnishandle verweigert Löschen/Umbenennen seines Parents. Keine neue
|
||||
ACL-Freigabe oder allgemeine LocalService-Schreibfreigabe wird hinzugefügt.
|
||||
|
||||
Im vorhandenen exklusiv gesperrten Telemetriejournal stehen ausschließlich
|
||||
öffentliche CSR-/Zertifikatsbytes und UUID-/Identitätsselektoren; private
|
||||
Schlüssel gelangen weder in SQLite noch WAL. Die neue Schlüsseldatei ist vor
|
||||
Pending-Commit vollständig geschrieben. Vor der Netzwerkanfrage committen
|
||||
Versions-ID und exakte CSR gemeinsam. Die Antwort wird gegen die konfigurierte
|
||||
CA-Kette, ClientAuth-Verwendung, Gültigkeit, genau einen passenden Geräte-CN,
|
||||
Nicht-CA-Leaf und tatsächlich passende private Schlüsselbytes geprüft.
|
||||
Zertifikat und aktiver Selektor wechseln in einer einzigen SQLite-Transaktion
|
||||
unter dem vorhandenen WAL-/`synchronous=FULL`-Vertrag.
|
||||
|
||||
Ein Schreib-, Antwort-, Validierungs- oder Commitfehler lässt den bisherigen
|
||||
Selektor erhalten. Unselektierte Schlüsseldateien nach Abbruch werden nicht
|
||||
adoptiert oder automatisch gelöscht. Nach Auswahl einer neuen Version gibt es
|
||||
keinen automatischen Rückfall auf die Initialversion, auch nicht bei fehlender
|
||||
Datei oder Ablauf. Alle vorhandenen mTLS-Verbraucher des Windowsagenten
|
||||
(WSS/HTTPS, Zeitabruf und gegebenenfalls MSI-Download) verwenden dieselbe
|
||||
Version. Kein Helper-Signierpin, Zeitpin, Geräte-/Enrollmentgeneration oder
|
||||
Jobrecht wird rotiert oder freigeschaltet.
|
||||
|
||||
Antwortverlust länger als die serverseitigen 300 Sekunden, abgelaufene oder
|
||||
widerrufene Zertifikate und beschädigter State benötigen eine ausdrücklich
|
||||
abgestimmte Wiederherstellung. Der Client erfindet kein neues Identitätsfenster.
|
||||
Die Crashsicherheit beruht auf der vorhandenen SQLite-/Dateisystem- und
|
||||
Datenträger-Durabilität: keine Behauptung unabhängiger Stromausfalltests oder
|
||||
Schutz gegen Administratoren, die Schlüssel und State verändern können.
|
||||
|
||||
Lokale Prüfungen und noch offene native Gates werden im Implementierungsstand
|
||||
getrennt festgehalten. Native LocalService-DACL-/Flush-/Reparse-/Hardlinktests,
|
||||
Windows-Renewal mit tatsächlichem Server, Antwortverlust, Prozessabbruch,
|
||||
Transportwechsel und Negativabnahmen bleiben vor einer Runtimefreigabe offen.
|
||||
Die permanente Identität darf hierfür nicht ohne weitere Abstimmung rotiert
|
||||
oder widerrufen werden. Keine RMM-Jobs oder Operatorenserie sind Bestandteil.
|
||||
|
||||
Tatsächlich lokal ausgeführt: `cargo test --offline --locked -p
|
||||
rmm-agent-windows --lib` (23/23, keine Filter); `cargo check --offline --locked
|
||||
-p rmm-agent-windows --target x86_64-pc-windows-gnu --all-targets --features
|
||||
system-helper`; Clippy für beide Targets mit `-D warnings`,
|
||||
`cargo fmt --all --check` und tatsächlicher GNU-Link beider Windowsbinaries mit
|
||||
`system-helper` bestanden. Das Windows-Lib-Testbinary wurde mit `--no-run`
|
||||
gebaut (SHA256 `60e053e6e9cc7fb43de73fe05d50f7934a890e2f5de3c330175af4eba5ed50c5`),
|
||||
hier nicht ausgeführt. Der erste Crosscheck in der unvollständigen
|
||||
Builderimage scheiterte an fehlendem WIDL; der vorhandene vollständige
|
||||
WIDL-/clang-Builder bestand danach, ohne Buildguardänderung.
|
||||
|
||||
Der Orchestrator führte anschließend dasselbe Linux-Testbinary tatsächlich
|
||||
auf Cloud-Linux als UID65534 aus: genau fünf `certificate_rotation::tests::*`
|
||||
bestanden, 18 andere Tests bewusst gefiltert, keine Skips oder Fehler.
|
||||
Binary-SHA256 `33d6e1f0c145e90247e123fba00bad6a972bad6aa8d1f84ffcfa801a97787890`;
|
||||
eigene geschützte Quittung
|
||||
`devstate/cert-renewal-linux/d61686f2-7829-4756-869e-a407667d1f97/result.json`,
|
||||
SHA256 `7e6cab5915ec00a9b1392c1f15ddb13fe9ac6dd3b8e007b82e1dc914cb0507e1`.
|
||||
Das ist ein nativer Linuxnachweis der portablen Logik mit synthetischen
|
||||
In-memory-KeyFiles, kein Windows-DACL-/Dateiflush- oder echtes Renewal.
|
||||
Keine permanente Identität oder Dienstkonfiguration wurde hierfür geändert.
|
||||
|
||||
Die fünf Fälle prüfen exakte CSR-Wiederverwendung nach Antwortverlust;
|
||||
falsche Agent-ID, CA, Schlüssel, Verwendung und Ablauf bei erhaltener alter
|
||||
Version; fehlenden neuen Key ohne Legacyfallback; manipuliertes Pending und
|
||||
Enrollmentbindung; sowie echten SQLite-/WAL-Reopen mit fortbestehender Sequenz
|
||||
und einen absichtlich verweigerten Selektorcommit, bei dem auch das zuvor im
|
||||
selben SQL-Commit geschriebene Zertifikat zurückgerollt wird.
|
||||
|
||||
Erster tatsächlicher Windows-Unitlauf: vier Fälle bestanden, der fünfte endete
|
||||
mit Exit101/Win32-Fehler33 beim rohen Dateiscan nach allen SQL-Prüfungen. Die
|
||||
Testfixture hatte ihr Journal noch geöffnet und traf auf SQLite-WAL-/SHM-
|
||||
Bytebereichssperren. Originalbeleg
|
||||
`f981a395f4eceb527ad8a8859cff3c69ba79e52421300968b057404742fa1d8c`
|
||||
bleibt fehlgeschlagen. Die Fixture schließt nun das Journal vor dem rohen
|
||||
Restdateiscan; keine Fehler werden übergangen und kein Produktguard geändert.
|
||||
Dieser Scan behauptet keinen Zugriff auf ein aktiv gesperrtes Windows-WAL.
|
||||
Der erste Viererfolg ist keine vollständige Windowsabnahme.
|
||||
|
||||
Das enge Testdelta ist anschließend tatsächlich zuerst auf Cloud-Linux als
|
||||
UID65534 bestanden: fünf PASS, 18 andere gefiltert, keine Skips oder Fehler;
|
||||
Fall `bc2158ce-d500-4c64-8f17-e12527559f5b`, Quittung-SHA256
|
||||
`1736a19a75d49eca91062e4e7adb28732f254279b64003474efcd6201ffa08ac`.
|
||||
Linux-Binary-SHA256
|
||||
`1f9482ce78b6690e6bfbadecc5df61d5157620fce5302c094364cc8c371d1093`.
|
||||
Danach auf Windows11 AMD64 im Entwicklungsbenutzerprozess: dieselben fünf
|
||||
PASS, 44 andere gefiltert, keine Skips oder Fehler; Fall
|
||||
`01d26081-895f-4dea-8eb0-7c4defed1d27`, Quittung-SHA256
|
||||
`64e960c2eb0b755b376028d923c6fdebbc11d5f96534103452f865ccf51a4fc0`.
|
||||
Windows-Binary-SHA256
|
||||
`951a0ddad1225752d8817c15234f74926f1e216c1ca22e1aee8ba0a5e7f97e60`.
|
||||
Beide Nachprüfungen führte der Orchestrator aus. Der Produktcode blieb beim
|
||||
Fixturefix unverändert. Die Windowsfälle verwenden synthetische
|
||||
In-memory-KeyFiles: kein LocalService-/ProtectedKeyFiles-Nachweis, kein echter
|
||||
Renewal-HTTP-Aufruf und keine permanente Zertifikats-, Dienst- oder
|
||||
Jobänderung. Die oben benannten Runtimegates bleiben offen.
|
||||
|
||||
Die Dateiflags folgen [CreateFileW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)
|
||||
und [FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers);
|
||||
der öffentliche Selektor übernimmt den vorhandenen
|
||||
[SQLite-WAL/FULL-Vertrag](https://www.sqlite.org/pragma.html#pragma_synchronous).
|
||||
|
||||
Historischer Vorbereitungsstand45b5337: eine weitere enge native Datei-I/O-Unit
|
||||
war **vorbereitet, nicht ausgeführt**:
|
||||
`certificate_rotation::tests::protected_key_files_create_new_reopen_acl_and_hardlink_guards`.
|
||||
Sie steckt im vorhandenen Lib-Testbinary; kein zusätzliches Diagnostikbinary,
|
||||
keine Tokenübernahme, Impersonation, Dienste oder Accounts. Wegen ihrer
|
||||
expliziten Administrator-/Dateisystemwirkung ist sie im Defaultlauf als
|
||||
`ignored` markiert und muss separat mit `--ignored --exact` ausgewählt werden.
|
||||
Dies ist ein offenes natives Gate und wird nicht als bestandener Test gezählt.
|
||||
|
||||
Die Unit verlangt bereits vorhandene Administratorrechte und die vorhandene
|
||||
Agent-Service-SID, erstellt ausschließlich einen eigenen zufälligen Unterordner
|
||||
im temporären Verzeichnis mit expliziter SYSTEM-/Administratoren-/Agent-SID-DACL
|
||||
und nutzt darin den unveränderten `ProtectedKeyFiles`-Produktpfad. Sie prüft
|
||||
CreateNew/Flush, die wirkliche geerbte DACL, bytegleiche Wiederöffnung samt
|
||||
öffentlichem P-256-Keyhash, verweigertes Überschreiben, verweigertes Umbenennen
|
||||
des gehaltenen Verzeichnisses und Hardlinkablehnung. Eine zu breite DACL wird
|
||||
nur an einer separaten **leeren** eigenen Verzeichnisfixture geprüft.
|
||||
Private Schlüsselbytes stehen weder in stdout noch in Assert-Debugausgaben.
|
||||
Bei Erfolg entfernt sie ausschließlich ihre eigenen Fixturedateien und das
|
||||
leere eigene Verzeichnis; ein Fehler lässt den isolierten Fall erhalten.
|
||||
|
||||
Das belegt nach einem zukünftigen tatsächlichen Lauf nur Datei-I/O des bereits
|
||||
vorhandenen Administratorprincipals und die geprüfte Service-SID-DACL. Die
|
||||
produktive Ownerprüfung bleibt vollständig bestehen; ein unzulässiger
|
||||
Dateieigentümer wird weiterhin verweigert. Tatsächliche LocalService-Erzeugung,
|
||||
Wiederöffnung und erneutes Öffnen nach Prozessabbruch sind damit weiterhin
|
||||
nicht nachgewiesen. Es wurde kein konkreter Produkt-I/O-Fehler nachgewiesen,
|
||||
also kein Produktguard dafür verändert. Der Controller-/Dienstupgradeumfang
|
||||
und die permanente Identität bleiben unberührt.
|
||||
|
||||
Für diesen vorbereiteten Testschnitt tatsächlich lokal: Linux23/23 ohne
|
||||
Filter, Windows-GNU-Lib `--no-run`, Windows-Alltargets-Clippy mit
|
||||
`system-helper`/`-D warnings` und Workspacefmt bestanden. Noch kein neuer
|
||||
Zielaufruf. Das vorbereitete Windows-Testbinary hat SHA256
|
||||
`cd385c3b8696303220d8e601768d70ac96a6e4187a14cbac9d511162a57eee5a`.
|
||||
|
||||
Nach dem ausdrücklichen SSH-Readback-Signal des Orchestrators wurde genau diese
|
||||
Unit tatsächlich einmal auf der Windows-VM ausgeführt. Eigener Fall
|
||||
`e0590d96-7e62-4bdc-a0b1-f53e8a9a9972`, unverändertes Binary `cd385c3b…`,
|
||||
Aufruf `--ignored --exact certificate_rotation::tests::protected_key_files_create_new_reopen_acl_and_hardlink_guards --test-threads=1`.
|
||||
Ergebnis: **ein PASS, null Fehler, null ignored, 49 andere gefiltert**, Exit0,
|
||||
gemeldete Unitlaufzeit0.09s. Der vorhandene Administratorprincipal wurde im
|
||||
Test geprüft; keine Tokenübernahme oder Impersonation.
|
||||
|
||||
Damit sind der wirkliche geschützte Windows-KeyFiles-CreateNew-/Flush-/Reopen-
|
||||
Pfad, bytegleiche private Wiederöffnung, öffentlicher P-256-Keyhashvergleich,
|
||||
Nichtüberschreiben, breite leere DACL-Negativfixture, gehaltenes Verzeichnis
|
||||
und Hardlinkablehnung für diesen Principal bestanden. Die Unit entfernte ihren
|
||||
eigenen temporären Schlüssel, Hardlink und Testordner erfolgreich. Es gab keine
|
||||
Änderung an Client, SCM, Accounts, SSH-Zugang oder dauerhafter Identität. Stagingbinary und
|
||||
eigene öffentliche Ergebnisdateien bleiben geschützt im Bootstraparchiv.
|
||||
|
||||
Der private Aufrufwrapper gab das bereits auf der VM beständig gespeicherte
|
||||
Ergebnis zunächst als PowerShell-Tabelle aus; dadurch schlug ausschließlich das
|
||||
lokale JSON-Einlesen fehl. Es gab **keinen zweiten Teststart**. Ein anschließend
|
||||
streng lesender Aufruf übernahm nur die ursprüngliche eigene `result.json`.
|
||||
Geschützter lokaler Rohread:
|
||||
`devstate/windows-keyfile-fixture/e0590d96-7e62-4bdc-a0b1-f53e8a9a9972/result-read.json`,
|
||||
SHA256 `68dd458a24c2455049b7799f57e30f1e858e323fa82c578e3b962f58282b5e49`.
|
||||
Die separate lokale Acceptancequittung `acceptance.json` bindet Intent,
|
||||
Transfer, Start und diesen Originalread; SHA256
|
||||
`268e3146acfcab55022f9534509e74c80caf7b8ca246bcc5eb3c30e08cfd1383`.
|
||||
Dies bleibt eine Administrator-Fixtureabnahme; tatsächliches
|
||||
LocalService-Keyfile-I/O, Prozessabbruch und echte Zertifikatserneuerung sind
|
||||
weiter offen. Keine bestehende Plattform-/Jobqualifikation wird damit erweitert.
|
||||
@@ -260,81 +260,3 @@ Ausgabe und expliziten Root-/SYSTEM-Ausführungsrechten gelegt. Paketabnahmen
|
||||
sind nachgeordnet. Der erneuerte SSH-Bootstrapzugang verleiht selbst keine
|
||||
RMM-Ausführungsrechte und ersetzt keine dieser noch separat nachzuweisenden
|
||||
Genehmigungs- und Ausführungsgrenzen.
|
||||
|
||||
## Manuelles Wartungsfenster am 15. November 2026
|
||||
|
||||
Der Server bestätigte die abgelaufene Freigabe vom 15. November um 13:05:58 UTC.
|
||||
Für die Windows-Entwicklung wurde die Frist desselben Forwarding-Schlüssels auf
|
||||
15:30:00 UTC (16:30 Uhr MEZ) gesetzt. Ein separater SSH-Lesezugriff bestätigte
|
||||
Frist, Hostpin, Schlüsselbindung, SSH-Profil und Konto. Der Port ist serverseitig
|
||||
an Loopback gebunden. Ein einmaliger, aktiver Servertimer für 15:30:00 UTC
|
||||
begrenzt auch eine noch offene Weiterleitung des dedizierten Tunnelkontos dieser
|
||||
Schlüsselgeneration. Das tatsächliche Auslösen des Timers steht noch aus.
|
||||
|
||||
Die Bedienperson öffnet das Fenster in der VM-Konsole mit
|
||||
`deploy/windows/Open-ConsoleMaintenanceWindow.ps1`; Parameter sind
|
||||
`-PreviousExpiry '2026-11-15T13:05:58+00:00' -Until '2026-11-15T15:30:00+00:00'`.
|
||||
Während der einmaligen SSH-Verbindung pausiert das Skript den vorhandenen
|
||||
Autostarttask. Bei normalem Ende oder Strg+C beendet es den Client und stellt die
|
||||
vorherigen Fristen und den Task wieder her. Bei hartem Abbruch oder VM-Ausfall
|
||||
den Zustand über die Konsole prüfen. Lokales PowerShell-Parsing bestanden.
|
||||
VM-Ausführung, SSH-Readback und Dienstwechsel stehen bei Veröffentlichung aus.
|
||||
Die WebUI-Freigabe für Agentjobs gilt weiterhin.
|
||||
|
||||
Das manuell geöffnete Fenster wurde anschließend vom Entwicklungsrechner über
|
||||
die bestehende gepinnte SSH-Verbindung bis zum Windows-Gast geprüft. Die
|
||||
Kontofrist und die Frist in der Bootstrapkonfiguration ergaben beide
|
||||
15:30:00 UTC. Der Gast bestätigte den Servernamen und den deaktivierten
|
||||
Autostarttask. Beide installierten Dienste liefen beim Readback mit ihren
|
||||
bisherigen Prozess-IDs: Agent 5528 als LocalService, Helper 9464 als LocalSystem.
|
||||
Danach wurde die Ablaufzeit im lokalen Zugangsdatensatz an die geprüfte
|
||||
Gastfrist angepasst. Dies ist der Nachweis für den Entwicklungszugang.
|
||||
|
||||
### Unterbrechung nach Ruhezustand des Notebooks
|
||||
|
||||
Das Hostjournal belegt Suspend zwischen 14:48:24 und 15:39:01 Uhr MEZ.
|
||||
Danach blieb die Windows-VM im KVM-Status `running`. Der Entwicklungszugang
|
||||
lieferte bei der SSH-Begrüßung einen Timeout. Auch direkt am bestätigten
|
||||
Loopback-Listener des Servers kam keine Begrüßung an. Um 15:47 Uhr wurde
|
||||
nur die anhand von Konto, Prozess und Listener erneut identifizierte alte
|
||||
Forwarding-Sitzung geschlossen. Schlüssel und vereinbarte Frist von
|
||||
16:30 Uhr MEZ blieben erhalten. Zum erneuten Aufbau ist die VM-Konsole nötig.
|
||||
|
||||
Der Produktagent meldete sich nach dem Resume beim permanenten Server. MCP
|
||||
lieferte bei der Abfrage um 15:48 Uhr MEZ für den Windows-Gast `online`,
|
||||
Quelle `windows.base`, letzter Kontakt 15:47:51 Uhr MEZ. Beim Unterbruch war
|
||||
der Dienstwechsel noch nicht in die Ausführungsphase gelangt.
|
||||
|
||||
Eine weitere reine MCP-Abfrage bestätigte das nach dem Aufwachen neu
|
||||
eingegangene Windows-Inventar. Beobachtungszeit 15:39:13 Uhr MEZ, späterer
|
||||
Kontakt 15:52:23 Uhr MEZ. Betriebssystem, Volumes, Hardware und Software
|
||||
lagen jeweils als `valid/partial` vor. CPU-Anzahl, Verhältnis von freiem zu
|
||||
gesamtem Speicher und die Volumenwerte bestanden die Plausibilitätsprüfung.
|
||||
Windows-Inodes waren ausdrücklich `unsupported` mit leerem Zahlenwert.
|
||||
Beleg-SHA-256 `cce907d4c5e4ca9b788bab4aad8aac1f082b59f6a2922484289f19be061a1162`.
|
||||
Die Abfrage nutzte gespeicherte Telemetrie und erforderte keine SSH-Verbindung.
|
||||
|
||||
Beim erneuten Konsolenstart meldete der Gast die Sammelmeldung
|
||||
`Unexpected account, task, server or previous expiry.`. Sie stammt aus der
|
||||
Vorprüfung vor der ersten Änderung. Welcher Gastwert abweicht, steht bis zum
|
||||
Konsolen-Readback offen. Die Serverfrist wurde zu diesem Zeitpunkt nochmals
|
||||
mit 15:30 UTC bestätigt. Neuere Versionen des Konsolenskripts benennen die
|
||||
abweichenden Felder einzeln. Drei lokal simulierte Vorprüfungen bestanden
|
||||
(Ausgangszustand, drei abweichende Werte, alle sechs Bedingungen abweichend).
|
||||
|
||||
Der Konsolenreadback vom 15. November um 15:59:11 Uhr MEZ ergab
|
||||
`Disabled`, aktives Konto, Konto und Konfiguration beide mit Frist 16:30 Uhr
|
||||
MEZ, passender Servername, laufender sshd und genau eine ausstehende Sicherung.
|
||||
Der Bediener kann diesen konkreten Zustand mit `-ResumeInterrupted` im selben
|
||||
Zeitfenster übernehmen. Das Skript prüft die ursprüngliche Frist der Sicherung
|
||||
und rekonstruiert daraus die aktuelle Konfiguration. Bereits laufende
|
||||
Wartungsprozesse verhindern einen Doppelstart. Bei regulärem Ende verwendet
|
||||
es die ursprüngliche Sicherung zur Rücksetzung. Lokaler Parser- und Fixturetest
|
||||
für passende Sicherung, aktiven Prozess, Konfigurations- und Fristabweichungen
|
||||
bestanden. Die Wiederaufnahme muss auf der Windows-Konsole erfolgen.
|
||||
|
||||
Um 16:04:25 Uhr MEZ war der Windows-Gast über die vom Bediener wieder
|
||||
geöffnete Verbindung erreichbar. Der Gast bestätigte für Konto und Konfiguration
|
||||
denselben Ablauf um 16:30 Uhr MEZ, den erwarteten Servernamen und den
|
||||
deaktivierten Autostarttask. Agent und Helper liefen weiterhin mit ihren
|
||||
ursprünglichen PIDs 5528 und 9464 als LocalService beziehungsweise LocalSystem.
|
||||
|
||||
+1
-34
@@ -1,37 +1,4 @@
|
||||
# Windows-Client: aktueller MVP-Stand
|
||||
|
||||
Stand2026-11-15, Spezifikation1.23. Das begrenzte Linux-MVP ist abgeschlossen;
|
||||
der ausdrücklich zusätzlich beauftragte Windows-/Skriptkonsolen-/Updaterumfang
|
||||
ist noch nicht vollständig abgenommen. Notebook ausschließlich Entwicklung,
|
||||
Windowsgast eigenes Testgerät, endgültiger Server discovery.ease-technologies.de.
|
||||
Quellen-/Build-/Unitnachweis wird nicht als laufender Dienst-/Jobnachweis ausgegeben.
|
||||
|
||||
| Bereich | Tatsächlich implementiert/nachgewiesen | Was konkret noch fehlt / warum |
|
||||
| --- | --- | --- |
|
||||
| Passive Windowsverwaltung | Laufender LocalService-Agent, Enrollment/mTLS, WSS/HTTPS/Fallback, Inventar/Heartbeats und Tenanttrennung nativ bestanden. Die passive Zertifikatserneuerung ist implementiert. Fünf Tests mit separaten Zertifikaten bestanden auf der Cloud-Linux-VM und auf Windows 11. | Echte Erneuerung durch den LocalService-Dienst mit einer separaten Testidentität und anschließender Wiederverbindung sowie ein eigenständiger Widerrufstest fehlen. [Zertifikatsnachweise](windows-certificate-renewal.md) |
|
||||
| SYSTEM-Trennung | Helper läuft als SYSTEM/Manual; Pipe-v2, gegenseitige Prozess-/Image-/Dateibindung und echte LocalService-Probe bestanden. | Unabhängiger signierter Laufzeitsync und erste genehmigte SYSTEM-Wirkung; die frühere Peerprobe-Störung ist kein aktueller offener Blocker. |
|
||||
| Skriptkonsole | MCP-Antrag, feste Bytes/Plan/WebUI, PowerShell5.1/RemoteSigned-Prozessprofil, Vollwartungsprofil und Ausgabe-/Prozessgrenzen implementiert; native Windows-Vertragsunits bestanden. Linux-UID0-Vollwartungsjob tatsächlich bestanden. | Neue Windowsruntime noch nicht installiert/qualifiziert; erste WebUI-genehmigte LocalService-/SYSTEM-Skripte, tatsächliche Ausgabe und Fehlerverhalten offen. Der laufende Windowsclient bleibt passiv/0Jobs. |
|
||||
| Zeitvertrauen | Signierter Codec, getrennte Agent-/Helperprüfung und ausdrückliches aktives KVM-OS-Profil1.23 implementiert; Linux-first und Windows-Rohcapture belegt. Auf dem permanenten Server läuft das Zeit-Gateway. Die Windows-VM prüfte über ihr Gerätezertifikat eine echte signierte Antwort (200). Fremder Mandant (403), alte Verbindung (409) und öffentlicher Zugriff ohne Geräteidentität (401) wurden abgewiesen. | Der HTTPS-Nachweis stammt aus einem separaten Prüfprozess im Gast. Agent und Helper müssen jeweils selbst eine neue Antwort mit ihrem aktuellen Dienst- und Verbindungskontext prüfen. Dafür fehlen auf der VM noch das neue Dienstpaar und die geschützte Zeitkonfiguration. |
|
||||
| Dienst-/MSI-Aktionen | Typisierte SCM-/MSI1.0→1.1-Verträge, getrennte SYSTEM-Policies, Runtime-/Nachbedingungsquellen und native Vertragsunits vorhanden. | Nach Zeit-/Syncbereitschaft je eigene WebUI-genehmigte Dienst- und MSI-Installation/Upgrade/Noop mit echten unabhängigen Nachbedingungen. Keine allgemeine EXE-/OSupdatefreigabe aus Fixtures. |
|
||||
| Strukturierte Eventlogs | Begrenzter Provider-/Worker-/UI-Vertrag und native Vertragsunits vorhanden. | Eigenständig geprüfter Prozess-/Clockkontext des Kindworkers und echte genehmigte Live-Abfrage offen; Parentclock darf nicht als fremder Prozessbeleg verwendet werden. Genehmigte PowerShell-Skripte sind für Logwartung zusätzlich vorgesehen. |
|
||||
| Dauerhafte Windowsjobs | Gemeinsamer Einmalverbrauch, Journale, Dispatch/Abandon/RawMirror und Fehlerverträge implementiert. | Redelivery/ACK-Verlust, Crash/Unknown, Ablauf/Entzug, Reconnect und gemischter Linux-/Windowsplan am echten aktivierten Windowsdienst nachweisen. Linuxerfolge ersetzen diese OS-Nachweise nicht. |
|
||||
| Agent-Selbstupdate | Signierte Codepaare/Releasekatalog, eigene Artefaktstreams, WebUI-Plan, Handoff/Health und Readercensus im Quellpfad; lokale und ausgewählte native Linuxfixtures bestanden. Der passive [Linux-Katalogcheck](agent-updater-passive-catalog.md) ist integriert und mit sechs Fällen auf der Cloud-VM geprüft. | Ausgelieferter Worker/Full-Admission/Staging, kompatible erhaltende erste Baseline, unklare Record-I/O-Adjudikation und V2-Code-Rückweg fehlen; danach tatsächlicher genehmigter Linux-Apply, anschließend Windows. APT/MSI-Fixtures aktualisieren nicht den Agenten. |
|
||||
| Auslieferung/Betrieb | Windows-GNU-Artefakte gebaut und bestimmte Binaries nativ ausgeführt; Verwaltung bleibt SSH-Tunnel, keine öffentliche Dev-Anmeldung. | MSVC-/signierter Installer und eigenständige native Installer-/Reboot-/Lifecyclebelege offen. Produktiver IdP/MFA/HA/Restore sind zusätzliche Betriebsreife, keine bestandene MVP-Produktionsfreigabe. |
|
||||
|
||||
Aktuelle Detailbelege: [Windows-Zeitabruf](windows-time-route-operator.md), [Gatewaybereitstellung](server-time-gateway-deploy.md), [Zeitbrokerstart](server-time-broker-start-acceptance.md),
|
||||
[Signaturen](server-time-broker-signature-acceptance.md),
|
||||
[OS-Zeitprofil](windows-trusted-os-clock-source.md),
|
||||
[Pipe-v2](windows-system-pipe-upgrade.md),
|
||||
[Skriptkonsole](script-console-windows-link.md),
|
||||
[Updater](agent-updater-runtime-source.md).
|
||||
Jeder wirkende Auftrag bleibt bis zum tatsächlichen WebUI-Klick pending_approval;
|
||||
Entwicklungsabnahmen ausschließlich sichtbar simuliert, kein Produktionsnachweis.
|
||||
|
||||
## Historischer Stand2026-11-14
|
||||
|
||||
Die folgende ursprüngliche Tabelle bleibt als damaliger Snapshot erhalten.
|
||||
Insbesondere fehlender Helper/Peerprobe und ausschließlicher Alt-Clockentwurf
|
||||
sind durch die obigen aktuellen tatsächlichen Nachweise überholt.
|
||||
# Windows-Client: Abnahmegates
|
||||
|
||||
Stand 2026-11-14, Spezifikation 1.18. Der Windows-11-x64-Gast ist ein eigenes
|
||||
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
# Grenze vor dem ersten Windows-PowerShell-Job
|
||||
|
||||
**Aktueller Vorrang2026-11-15:** Dieser Text enthält den historischen1.15-
|
||||
Entwurf. Gemeinsamer Jobkern, SYSTEM-Helper/Pipe-v2 und Skriptquellen sind
|
||||
inzwischen implementiert und teilweise nativ geprüft; der signierte Zeitanker
|
||||
ist mit1.22 und das aktive KVM-OS-Profil mit1.23 ausdrücklich angenommen.
|
||||
Der laufende Windowsclient bleibt trotzdem passiv, bis neue Zeit-/Sync-/
|
||||
Jobruntimebelege vorliegen. Aktueller Überblick: [windows-gates.md](windows-gates.md),
|
||||
[Zeitprofil](windows-trusted-os-clock-source.md). Die folgenden Aussagen
|
||||
„kein Helper“/„Alternative nicht beschlossen“ sind historisch, keine aktuellen
|
||||
Entscheidungen oder offenen Produktfragen.
|
||||
|
||||
Stand 2026-11-13, Spezifikation **1.15**. Dieses Dokument beschreibt notwendige
|
||||
Voraussetzungen und offene Nachweise, keine neue Zeitvertrauensentscheidung und
|
||||
keine Windows-Jobfreigabe. Notebook ausschließlich Entwicklungsrechner;
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# Lesender Abschluss zweier passiver Windows-Zeitbeobachtungen
|
||||
|
||||
Der Collector `deploy/windows/passive_time_closeout.py` ist lokal vorbereitet
|
||||
und ausführbar. **Noch kein Zielaufruf oder nativer Abschlussnachweis.** Die
|
||||
V2-Profileinrichtung und ihr ausdrücklich gemeldetes Zeitfenster stehen vor
|
||||
dem Aufruf. Tunnel-/Zugangserneuerung, Profileinrichtung und Dienstwartung sind
|
||||
keine Aktionen dieses Collectors.
|
||||
|
||||
Der unabhängige Quellreview von `cc821246ccd98ee6d3dc5c1b12c7303d3010e8a7`
|
||||
fand im engen Veröffentlichungsdelta keine konkrete Regression. Der Agent hält
|
||||
pro Verbindung den ersten Vergleich je Rolle erst nach erfolgreichem eigenen
|
||||
`complete` bzw. authentifiziertem Helper-`TimeCompleted` fest. Nur der aktuelle
|
||||
Verbindungsowner schreibt beim Heartbeat. Ein verworfener Worker erhält keinen
|
||||
Publikationspfad. Die JSONs sind historische Beobachtungen, keine aktuellen
|
||||
Clockleases, Jobfreigaben oder unabhängig erneut verifizierbare Signaturpakete.
|
||||
|
||||
Auf der Windows-VM liest der Collector ausschließlich die Inhalte von
|
||||
`C:\ProgramData\RustDiscovery\state\agent-time-sample.json` und
|
||||
`helper-time-sample.json`, jeweils höchstens8192Bytes, durch gehaltene Handles.
|
||||
Singlelink, Nicht-Reparse, Dateigröße, native FileID/LastWrite und die
|
||||
SYSTEM-/Administratoren-/Agent-Service-SID-DACL werden geprüft. Die
|
||||
Verzeichnis-DACL und Dateisicherheit müssen während des Reads gleich bleiben.
|
||||
Reparse-Vorfahren werden verweigert. Keine privaten Schlüssel-, Journal- oder
|
||||
Konfigurationsinhalte werden gelesen. Kurze gehaltene Lesehandles können einen
|
||||
gleichzeitigen atomaren Reporttausch vorübergehend verweigern; der bestehende
|
||||
Publisher behält den Sample für einen späteren Heartbeat.
|
||||
|
||||
Vor und nach diesem Read werden ausschließlich öffentliche CIM-/SCM- und
|
||||
native Prozessmetadaten geprüft: beide festen Dienste Running, richtige
|
||||
Konten/Startarten/Kommandos, Agent-/Helper-PID und Geburt, tatsächlicher
|
||||
Prozessimagepfad und erwartete öffentliche Binaryhashes. Der Boot wird aus
|
||||
demselben festen CIM-LastBootUpTime-Vertrag wie im Agenten abgeleitet. Es wird
|
||||
kein Agent-, Helper-, SQLite-/Statusprobeprogramm oder IPC aufgerufen. Die
|
||||
vorhandenen streng gepinnten Bootstraptransporte werden nur lesend verwendet;
|
||||
C#-Interop enthält lediglich Query-APIs.
|
||||
|
||||
Der bestehende `time_route_context` liest davor und danach ausschließlich den
|
||||
öffentlichen registrierten Gerätekontext in einer Read-only-SQL-Transaktion
|
||||
und die feste Gateway-/Serverbootbindung. Die beiden Serverzeugen müssen
|
||||
identisch sein. Die Capabilitymenge muss exakt passiv bleiben. Beide Reports
|
||||
brauchen dieselbe positive aktuelle Serververbindungsgeneration und denselben
|
||||
aktuellen Windows-Boot; ihre Agent-PIDs müssen dem aktuellen Agentprozess
|
||||
entsprechen. Rollen, Feldschema und Datentypen sind exakt; doppelte JSONkeys
|
||||
werden bereits beim Rohparse verweigert. Verifier-UUID, Request- und
|
||||
Response-SHA256 müssen zwischen den Rollen verschieden sein.
|
||||
|
||||
Die Beobachtung muss nach der von Root belegten V2-Einrichtung und nach der
|
||||
aktuellen Agentgeburt liegen. Beobachtungs- und Dateialter sind höchstens180s;
|
||||
Publikationsverzug höchstens90s bei2s Zukunftstoleranz. Der aktuelle Windows-
|
||||
UTC-Read muss höchstens10s vom lokalen Operatorzeitpunkt abweichen. Dies sind
|
||||
Akzeptanzgrenzen für historische Daten, keine behauptete native Zeitgenauigkeit.
|
||||
Fehlende/stale Belege und ein Generationenwechsel erlauben nur neue Readversuche.
|
||||
Das Wartefenster beträgt180s; ein bereits begonnener vollständiger Readsatz
|
||||
hat zusätzlich höchstens105s Transportbudget. Ein Timeout erzeugt einen
|
||||
unvollständigen eigenen Beleg, niemals eine erfolgreiche Abnahme.
|
||||
|
||||
Lokale private Fälle entstehen unter `devstate/windows-passive-time-closeout/`.
|
||||
Rohantworten stehen vor ihrer Validierung auf dem lokalen Datenträger;
|
||||
Acceptancereceipts binden die aktuellen Native-/Serverzeugen per SHA256. Die
|
||||
Befehlsparameter für den späteren Aufruf sind die tatsächlich installierten,
|
||||
qualifizierten Agent-/Helperhashes und Roots UTC-Untergrenze nach der
|
||||
V2-Einrichtung. Keine frei wählbaren Guestpfade, Aktionen oder Abfrageprogramme.
|
||||
|
||||
**Geplant, nicht ausgeführt:**
|
||||
|
||||
```text
|
||||
python3 deploy/windows/passive_time_closeout.py collect \
|
||||
--agent-sha256 <tatsächlich-installierter-qualifizierter-SHA256> \
|
||||
--helper-sha256 <tatsächlich-installierter-qualifizierter-SHA256> \
|
||||
--profile-after <Roots-tatsächliche-V2-Einrichtung-UTC-mit-Z>
|
||||
```
|
||||
|
||||
Tatsächlich lokal ausgeführt und bestanden:
|
||||
|
||||
```text
|
||||
python3 -m py_compile deploy/windows/passive_time_closeout.py
|
||||
python3 deploy/windows/passive_time_closeout.py guards
|
||||
python3 -m unittest discover -s deploy/windows -p test_passive_time_closeout.py
|
||||
```
|
||||
|
||||
Sechs lokale Fixtures prüfen aktuelle unabhängige Rollen, falsche PID/Boot/
|
||||
Generation/Rolle/Beobachtungsfrist, gleiche Verifier-/Request-/Responsewerte,
|
||||
doppelte JSONfelder, fehlende Sicherheitsprüfung und fehlenden Helperbeleg.
|
||||
Der zusätzliche Grenzfall prüft die tatsächlichen sieben .NET- und neun
|
||||
Chrono-Nachkommastellen. Python3.10s ursprüngliches `fromisoformat` verweigert
|
||||
diese Formen; dieser konkrete lokale Fehler wurde vor jedem Zielaufruf
|
||||
behoben. UTC- und FILETIME-Grenzen werden jetzt vollständig mit Ganzzahl-
|
||||
Nanosekunden verglichen. Ein Sample genau an der Installationsuntergrenze wird
|
||||
akzeptiert, eine um1ns spätere Untergrenze verweigert dasselbe Sample. Keine
|
||||
Native- oder Testzeit wird hierfür erfunden.
|
||||
Danach lokal mit vorhandenem `/tmp/rmm-powershell-parser/pwsh` tatsächlich
|
||||
ausgeführt: vollständiger Reader-AST ohne Parserfehler und Kompilierung der
|
||||
C#-Querydefinitionen ohne Methodenaufruf bestanden. `Info` besitzt die
|
||||
erwartete52-Byte-Interopgröße. Lokale Quittung unter
|
||||
`devstate/windows-passive-time-closeout-local/receipt.json`; kein nativer
|
||||
Win32-Aufruf oder VM-Zugriff. Windows-PowerShell5.1-/tatsächliche Win32-Reads
|
||||
und echte Rollenbelege bleiben offen; lokale Prüfungen ersetzen sie nicht.
|
||||
|
||||
Der konkrete Profileinsatz wurde zusätzlich unabhängig rein im Quellcode
|
||||
geprüft (`time_profile_config.py`, SHA256
|
||||
`36f0451a146ca8dc73d4c66b48f2e65fbaefde5c7643133993d1c136cc3318de`).
|
||||
Kein konkreter Befund im geprüften Schnitt: getrennte öffentliche Source-/
|
||||
Plattform-/Key-/Bindingketten, exakte neue Rollen mit PID/Geburt/Token-/Service-
|
||||
SID/Image/FileID, SameLive-/Kernel-CAS vor und nach Veröffentlichung,
|
||||
Intent-vor-ACL/Move, überschreibungsfreier gleichvolumiger Move und ausschließlich
|
||||
ThisFolderOnly-Leserechte für die zwei Rollen. Die UTC-Untergrenze wird vor
|
||||
dem ersten privaten Fallintent aufgezeichnet. Noch ungesetzte Paarbeleg-
|
||||
Konstanten blockieren die Vorbereitung. Der konkrete spätere Rollen-/
|
||||
Readbackbinding-Delta und die tatsächliche Veröffentlichung bleiben separat
|
||||
nachzuweisen. Dieser Review ist keine Profileinrichtung oder native Abnahme.
|
||||
|
||||
Im laufenden Wartungsfenster folgte ein enger unabhängiger Quellreview des
|
||||
konkreten SCM-ETS-Fixes (Clockoperator-SHA256
|
||||
`90c2708c17903e4bc630f6655dba38ff6448251941abd53f5874e991042b0f2c`).
|
||||
Die tatsächlich gelesenen Int32-SID-Typen trugen PowerShell-ETS-Metadaten und
|
||||
wurden vom bisherigen `PSCustomObject`-Zweig als Objekt behandelt. Der Fix
|
||||
behandelt die primitiven CLR-BaseObjects zuerst und rekonstruiert reine
|
||||
JSONskalare. Stringcase und vollständige Integerwerte bleiben erhalten;
|
||||
NaN/Infinity werden verweigert. Arrayreihenfolge, Null, Keykollisions-/Tiefe-
|
||||
und Wirkungs-CAS bleiben unverändert. Keine weiteren konkreten Findings im
|
||||
geprüften Schnitt. Derselbe vollständige Comparator wurde im Profiloperator
|
||||
SHA256 `8588241eac3036e665b6010e4bf9fac1547be88d68f95b4c02cb24e425267c68`
|
||||
per reinem AST-Literalvergleich bytegleich bestätigt. Das ist ausschließlich
|
||||
Source-Review, kein Zielaufruf oder Beleg einer ausgeführten Wartung.
|
||||
|
||||
Falls Reports fehlen, können die bereits vorhandenen passiven Dateien
|
||||
`helper-probe.json` und `pipe-last-error.json` getrennt nur lesend bei der
|
||||
Pipeeingrenzung helfen. Sie enthalten keinen vollständigen Timeworkerfehler;
|
||||
auch Metadaten vorhandener fester `.agent-time.pending`/`.helper-time.pending`
|
||||
können eine unterbrochene Publikation erklären. Dieser Collector liest oder
|
||||
ändert diese zusätzlichen Dateien nicht und löst keine Diagnose aus.
|
||||
@@ -87,339 +87,3 @@ Die Kandidaten751657ee/acf1e3f3 gehören zum Frischefix. Der anschließend
|
||||
ausdrücklich angenommene Zeitmodus aus Spezifikation1.23 ist noch in Umsetzung;
|
||||
er benötigt neue Produktartefakte und eigene Nachweise. Der vorbereitete
|
||||
Controller wird nicht allein aufgrund dieser AST-/Fixtureprüfungen aktiviert.
|
||||
|
||||
## Nachtrag: neues aktives Profilpaar, weiterhin geschlossenes ENTER
|
||||
|
||||
Nach der ausdrücklichen Userentscheidung für das begrenzte aktive OS-Zeitprofil wurde das Produktpaar erneut gelinkt: Agent `26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b`, Helper `59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e`, unveränderlicher Buildreceipt `04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d` und Qualifikationsbeleg `96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d`. Die früheren Plan-/Kandidatengenerationen bleiben erhalten.
|
||||
|
||||
Der korrigierte P1-Aktionsvertrag wurde für genau diese neue Kandidatengeneration beibehalten. Neuer Generator `bbdd0ef4649c97e0fe48e11d3eb8ccdaf7a7e78f9f5614720249ec5fcf8f44af`, lokaler Vorbereitungsfall `2dc20d01-d19e-4d7c-bce9-44f8904f2620`, Manifest `a8f2a39e3a64a0df56ebc45ccab85c7499e63ced44d9f6b17c34bb6a3b6fa904`, PS `ca7478fb61ca46f2c47952a818ea93b43ea522e29b36cbefc4bc15f460286796`. Änderungen gegenüber dem P1-fixierten77fb-Schnitt: nur neue Kandidaten-/Belegpfade und Hashbindungen sowie der tatsächliche Feldname im neuen Linkreceipt. Neue geschlossene Helperpolicy `aed124bfd6eaf84e10f9dfa1da4d403826331a6d3a64ff8182cfead35067cc8a`, Agentpeerpin `27c38c6b7e1985174018a009de5708f5171f585dcab74500a4f4d333f4d8aa76`.
|
||||
|
||||
Python-AST, dieselben Sourceguards und lokale create-only Vorbereitung PASS; keine Zielaktion oder neue native Controllerqualifikation. Beide festen Serversperren und die strikt typisierte/case-sensitive Aktionsgrenze bleiben erhalten. **ENTER bleibt geschlossen**, bis tatsächliches Gateway-/Brokerdeployment und der noch folgende native mTLS-Zeitroutebeleg konkret gebunden und unabhängig geprüft sind. Die [neue feste Routefixture](windows-time-route-fixture.md) ist ausschließlich für diesen passiven200/403/409-Endpunktnachweis vor dem Upgrade gebaut; sie erzeugt keine Dienstrollen-/Clock-/SyncReady-/Jobfreigabe und noch keine V2-Zeitkonfiguration.
|
||||
|
||||
## Native Vorbereitungsprüfung des aktuellen Profilpaarcontrollers
|
||||
|
||||
Der bestehende Controller für26dc/5967 (ca7478fb61ca46f2c47952a818ea93b43ea522e29b36cbefc4bc15f460286796)
|
||||
wurde nach ausdrücklicher Rootdelegation auf Windows ausschließlich im Speicher
|
||||
geparst und seine genau eine feste C#-HereStringdefinition kompiliert.
|
||||
PowerShell5.1.26100.9818, AST0, C#compile-onlytrue, Controller nicht ausgeführt.
|
||||
Keine Stage-, Stop-, Start-, Swap-, Konfigurations- oder Jobaktion. Original14fb-
|
||||
Lesewitnesses vor/nach bewiesen dieselben sechs stabilen nativen Felder,
|
||||
Journalidentität und monotone Sequenz. Fall3962b83b-c194-4318-8925-83e86c840b7f unter
|
||||
`devstate/windows-time-route-native-readonly/`, Receipt
|
||||
69d221997f247c2c291f0c7c079a79f2bae2c943628032835e49955af1ef7289.
|
||||
Das ersetzt nicht die noch fehlende Quellenbindung des tatsächlichen positiven
|
||||
Zeitroutebelegs vor der weiterhin gesperrten Enterphase.
|
||||
|
||||
## Tatsächliche Route bestanden, Paarwechsel noch nicht ausgeführt
|
||||
|
||||
Die passive HTTP-Abnahme68b841a5… ist einschließlich separatem Read tatsächlich
|
||||
bestanden (200/signature/context,403,409, Exit0). Der bestehende Paarcontroller
|
||||
bindet nun direkt die geschützten tatsächlichen Report-/Exit-/Kontext-/Probe-/
|
||||
öffentlichen Pin-Dateien dieser VM; der alte Harddeny-Entwurf bleibt historisch.
|
||||
Die strikte Aktionsgrenze steht weiterhin vor jeder Wirkung. Jobflags/Policies
|
||||
bleiben geschlossen, keine Zeitkonfiguration wird als Teil dieses Austauschs
|
||||
erstellt oder übernommen.
|
||||
|
||||
Stagingversuch0406dd40-c3c4-464b-8cc6-c9b98365d12a: neues Helperimage5967…
|
||||
tatsächlich vollständig im separaten Bootstraphashpfad vorhanden. Der vorhandene
|
||||
kleine lesende Agent-Staging-Prepareaufruf antwortete nach180s nicht. Noch kein
|
||||
Agentupload und kein Controllerinvoke mit Enter, kein ServiceStop/Start/Swap.
|
||||
Dieselbe sporadische SSH-/Commandantwortstörung betrifft damit auch eine kleine
|
||||
Vorbereitung und ist nicht allein dem alten Upgrade-finish-Reader zuzuordnen.
|
||||
Der konkrete Ursprung dieser sporadischen Transportstörung ist noch offen.
|
||||
|
||||
Eine danach begrenzte20s-Statusablesung antwortete tatsächlich: ursprünglicher
|
||||
Agent `RmmDiscoveryWindows` weiterhinRunning5528 mit unverändertem Servicepfad,
|
||||
ursprünglicher SYSTEM-Helper weiterhinRunning9464, neuer Agentbootstrapfile
|
||||
absent, neuer Helperbootstrapfile13143052Bytes vorhanden. Tatsächliche VM-UTC
|
||||
12:59:46, Kontoablauf13:05:58UTC. Der sichere Gesamtpuffer war unterschritten;
|
||||
daher wurde bewusst keine erste Dienständerung begonnen. Beide ursprünglichen
|
||||
laufenden Komponenten sind erhalten. Belege unter dem ursprünglichen0406-Fall:
|
||||
`stage-agent-preflight-timeout.json`, `final-no-stop-status.json`.
|
||||
|
||||
Für das nächste ausdrücklich autorisierte Zeitfenster wurde die alte feste
|
||||
Ablaufzeit aus der Generatorquelle entfernt. Prepare liest ausschließlich
|
||||
`expires_at` aus der aktuellen geschützten lokalen Zugangskonfiguration und
|
||||
verlangt mindestens420s Gesamtbudget vor Vorbereitung. Der konkrete Wert wird
|
||||
unveränderlich im neuen Payload/Manifest gebunden. Auf der VM muss er vor Wirkung
|
||||
mit **beiden** vorhandenen tatsächlichen Ablaufzeiten übereinstimmen: Konto
|
||||
`rmm-dev` und geschützt gelesenes `bootstrap-public.json`. Vor erster Wirkung und
|
||||
Agentstop420s; vor dem anschließenden Helperstop300s Restbudget, damit gewöhnlicher
|
||||
Zeitablauf nicht denselben hohen Grenzwert erneut unterschreitet. Unmittelbare
|
||||
Service-/Kernel-CAS bleiben auf beiden Stops. Dieser Code ändert Konto, Tunnel,
|
||||
Schlüssel oder deren Konfiguration nicht und schafft kein neues Zugangsfenster.
|
||||
|
||||
Pythoncompile und vorhandene Quellguards bestanden. Kein neuer Preparefall mit
|
||||
dem abgelaufenen knappen Fenster, keine weitere Zielaktion nach dem kleinen
|
||||
abschließenden Statusread. Quellenbindung/neue Baseline und tatsächlich einmalige
|
||||
Paarwartung samt Readback bleiben für das nächste bestätigte Fenster offen.
|
||||
|
||||
Nach Ablauf des SSH-Wartungsfensters meldete das gespeicherte MCP-Inventar
|
||||
den Windowsgast weiterhin als `online`. Der Agent hatte den permanenten Server
|
||||
am 15. November 2026 um 14:06:34 MEZ kontaktiert. Die Daten wurden ausschließlich
|
||||
über `inventory.get_device` gelesen. Beleg
|
||||
`003f000e16e53ce3ff8799694e7138e014689e741f69be6577519c616aee6bab`.
|
||||
|
||||
## Neues bestätigtes Fenster: Staging und Baseline tatsächlich bestanden
|
||||
|
||||
Nach erneuter ausdrücklicher Freigabe, tatsächlicher Konsolenbestätigung beider
|
||||
ursprünglichen Dienst-PIDs und Konto-/Konfigurationsablauf15:30UTC entstand der
|
||||
neue Fall5c627d08-aff0-42a1-a922-dcf7eebccb15. Der alte0406-Stagingversuch bleibt
|
||||
unverändert als unvollständiger Versuch ohne Dienständerung erhalten.
|
||||
|
||||
Tatsächlich native Stagingprüfung bestanden: Helper5967… (bereits eigener
|
||||
Bootstraphashpfad), Agent26dc… und fester Controller
|
||||
`d808f47b5de8563e7e32d49dc5a0ad83c988c7de12cc286f1814b3a69e7e27a6`.
|
||||
Danach vollständige native Baseline ohne Timeout: Config-/PKI-/Datei-/ACLbindung
|
||||
und tatsächlicher Helper-DB-/Lock-/Intentzustand stimmen mit dem angenommenen
|
||||
ursprünglichen14fb-Beleg überein. AgentRunning5528, HelperRunning9464.
|
||||
BaselineSHA `cc876073b87086021ba449748deebff8309e06977438bb1854565f5d58cbba88`.
|
||||
Geschlossene Serverflags und Job-/Outbox-/Permitzähler unverändert.
|
||||
Bis zu diesem Beleg kein ServiceStop/Start/Swap, kein Job, kein Zeitprofil.
|
||||
Die anschließende einmalige Enterphase ist ein gesonderter noch offener Schritt.
|
||||
|
||||
## Erste Enterphase vor jeder Wirkung verweigert; Ursache nachgewiesen
|
||||
|
||||
Im Fall5c627d08… wurde Enter genau einmal aufgerufen und mit
|
||||
`Preserved identity config or ACL` verweigert. Kein erneuter Enteraufruf.
|
||||
Die feste unabhängige Originalfallnachlese bestätigt: Fallordner absent,
|
||||
active-intent absent, sämtliche Intent-/Stop-/Swap-/Startmarker absent;
|
||||
ursprüngliche Dienste weiterhinRunning5528/9464. Es gab keine Dienständerung.
|
||||
Der erste Versuch bleibt fehlgeschlagen und wird nicht nachträglich geheilt.
|
||||
|
||||
Eine frische vollständige native Baseline bestätigte alle betroffenen Werte
|
||||
semantisch exakt identisch. Der konkrete Fehler lag im bisherigen PS-`JsonEqual`:
|
||||
Er verglich JSON-Texte einschließlich Objektmemberreihenfolge. Die Python-
|
||||
kanonisch sortierte gespeicherte Baseline und die native PS-Ordered-Ausgabe
|
||||
ordnen `public_hashes`, `identity_acls` und `private_key_metadata` anders an.
|
||||
Das war ein falscher Unterschied trotz unveränderter Werte, kein ACLwechsel.
|
||||
|
||||
Der enge Quellfix normalisiert nur Objektmember für den Inhaltsvergleich;
|
||||
Arrayreihenfolge sowie Null gegenüber leeren Arrays bleiben unterschieden,
|
||||
Tiefe bleibt auf40 begrenzt. Tatsächlich fünf native In-Memory-Gegenfälle
|
||||
bestanden: umgeordnetes Objekt akzeptiert, Scalaränderung, umgekehrtes Array,
|
||||
Null gegenüber leerem Array und Null-Element gegenüber leerem Array verweigert.
|
||||
Keine Dienste, Produktdateien oder Jobs wurden vom Guard verändert. Unabhängiger
|
||||
Quellenreview läuft getrennt; noch keine neue mutierende Controllerausführung.
|
||||
|
||||
Inzwischen behebt Main656102b die passive Zeitprüfung ohne Jobopt-in. Weil das
|
||||
ursprüngliche Paar nachweislich noch unmutiert ist, wird26dc nicht mehr installiert:
|
||||
Root qualifiziert zuerst das notwendige neue Agentimage; Helper5967 bleibt
|
||||
unverändert. Danach neue feste Image-/Controllerbindung und neue Baseline vor
|
||||
**einem** tatsächlichen Paarwechsel. Der fehlgeschlagene5c-Versuch wird dabei
|
||||
weder wiederholt noch als Erfolg ausgegeben.
|
||||
|
||||
## JsonEqual-Korrektur eng geprüft und nativ belegt
|
||||
|
||||
Der unabhängige Quellenreview fand im ersten Normalisierer einen zusätzlichen
|
||||
Randfehler: ein case-sensitives IDictionary mit `A` und `a` hätte beim Kopieren
|
||||
in eine case-insensitive OrderedDictionary einen Wert verlieren können. Beide
|
||||
Objektzweige verweigern nun vor dem Einfügen Nichtstringkeys oder bereits
|
||||
vorhandene kollidierende Namen. Bestehende feste Native-State-DTOs erzeugen
|
||||
solche Kollisionen nicht; der zusätzliche Pfad ist trotzdem geschlossen.
|
||||
|
||||
Unabhängiger enger Re-review der Quelle
|
||||
`4ef8c6787fd3defdd8416401b3b40dd63be0e3afffc195736eed0ce350286201`
|
||||
ohne weiteren konkreten Befund. Nativ anschließend sechs feste In-Memory-Guards
|
||||
bestanden: ursprüngliche fünf Fälle plus case-kollidierendes
|
||||
`Dictionary(StringComparer.Ordinal)` wird verweigert. ResultSHA
|
||||
`2429b869792854ac799c403422e26561df2b2c5310b408e6a7287751129c2a94`
|
||||
im erhaltenen5c-Fall, `comparison-collision-guard-result.json`.
|
||||
Pythoncompile und bestehende Quellguards ebenfalls PASS. Kein Service-/Datei-/
|
||||
Jobeffekt und weiterhin keine26dc-Installation. Der folgende Agentkandidat wird
|
||||
separat durch Root qualifiziert; Controller-/Payloadbindung und neuer echter
|
||||
Baselinebeleg werden erst mit dessen endgültigem Artefakt erzeugt.
|
||||
|
||||
## Ein Austausch mit passiver Zeitprüfung
|
||||
|
||||
Nach der Verweigerung vor dem ersten Dienststopp wurde der ursprüngliche
|
||||
202-Dateien-Quellstand erneut gegen sein Manifest geprüft. Nur drei Quellen
|
||||
haben sich für den Installationskandidaten geändert: Zeitabfrage im Agenten,
|
||||
Auswahl des Abfrageintervalls und Schreiben der zwei historischen
|
||||
Dienstbelege. Die Änderungen kommen aus den Commits `656102b` und `cc82124`.
|
||||
Das Manifest dieser 202 Inputs hat den SHA-256-Wert
|
||||
`11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4`.
|
||||
Der isolierte Offline-Releasebuild für AMD64 ergab das Agentbild
|
||||
`0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c`.
|
||||
Für den Helper wird das bereits qualifizierte Image `59675a3c…` verwendet.
|
||||
Der Agent-Zwischenbuild `34b7458d…` wurde nicht installiert.
|
||||
|
||||
Die neun gezielten Zeitprüfungen aus diesem konkreten Quellstand bestanden auf
|
||||
der Cloud-Linux-VM als UID 65534, Exit 0. SHA-256 der Ergebnisquittung
|
||||
`333f8d2dba3b35dcd79faafd8faf5c88da321942c9672c0a80f1f2c8fceb24a3`.
|
||||
|
||||
Anschließend bestanden die gleichen neun Tests auf der Windows-VM aus dem
|
||||
separat gebauten AMD64-Librarytestbinary desselben Release-Quellstands, Exit 0.
|
||||
Die Ergebnisquittung hat SHA-256
|
||||
`7700096145afdca74e7473e56c6dd2e65651252e889a696f84bb1fc2441ff513`.
|
||||
Nach erneutem Abgleich aller 202 Quelldateien, des PE-Headers und des Helperhashs
|
||||
wurde das Buildreceipt
|
||||
`f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446`
|
||||
für den einmaligen Dienstwechsel erstellt. Der Windows-Testprozess hat weder
|
||||
einen Dienst ausgetauscht noch einen Agentjob ausgeführt.
|
||||
|
||||
Der exakt gebaute Quellstand für das neue Agentbild liegt in Gitea auf
|
||||
`codex/windows-passive-time-candidate`, Commit
|
||||
`c6c4037d072a96d62136264066d0257782c7a932`. Alle 202 Build-Inputs wurden
|
||||
byteweise mit dem Release-Manifest abgeglichen. Der Ausgangsstand der
|
||||
ursprünglichen Qualifikation entspricht für dieselben 202 Dateien
|
||||
`b8ca8266bbb3b4806f4d20a3039f25196638804e`.
|
||||
|
||||
## Endgültiger passiver Agent und erneute Transportverweigerung
|
||||
|
||||
Root qualifizierte für genau den beobachtbaren passiven Stand cc82124 den
|
||||
Agent0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c.
|
||||
Tatsächliche Linux9-/Windows9-Guards und Release-Link sind im Receipt
|
||||
f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446 gebunden,
|
||||
Sourceinputs11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4.
|
||||
Helper5967… bleibt aus dem ursprünglichen04ed-Produktreceipt unverändert.
|
||||
Der Generator bindet diese beiden getrennten tatsächlichen Artefaktquellen,
|
||||
keinen nochmals eingebauten26dc-Agenten. Der öffentliche neue lokale Receipt
|
||||
war zunächst0664; nur sein Modus wurde auf0600 gehärtet, Bytes/SHA unverändert.
|
||||
|
||||
Neuer unveränderlicher Fall570c7a86-6509-49e6-b95e-8f0df74b18bf,
|
||||
Controller67d2fb1f9fdfec05b08f53a37be9a7df4cc3bb39f6cde8f950a226286474fd45,
|
||||
bindet das bestätigte15:30UTC-Fenster. Sein allererster kleiner Stage-Read wurde
|
||||
jedoch bereits beim SSHtransport verweigert: return255, stdout0, stderr89Bytes.
|
||||
Ein einzelner begrenzter Statusversuch klassifizierte CONNECTION_TIMEOUT,
|
||||
keinen Authentifizierungs-/Hostkeyfehler. Kein neuer Agenttransfer, kein Enter,
|
||||
keine Dienständerung oder Wiederholung unklarer Wirkung durch diesen Fall.
|
||||
|
||||
Root belegte danach Notebook-System-Suspend13:48:24–14:39:01UTC und einen nicht
|
||||
mehr antwortenden alten Forwardingkanal. Damals existierte weiterhin keine
|
||||
V2-Konfiguration/Zeitauthorität; beide ursprünglichen Produktdienste waren passiv.
|
||||
Root beendete ausschließlich den separat kernelgebundenen alten Bastionforwarder
|
||||
und forderte kontrolliertes Neuöffnen desselben Fensters an. Dieser Wartungsagent
|
||||
änderte weder Tunnel, Konto, Schlüssel noch SSHkonfiguration. Seit Roots Sperre
|
||||
keine weiteren VM-Aufrufe bis bestätigtem Transportreadback.
|
||||
|
||||
Abschließender lokaler Check: Pythoncompile, bestehende Quellguards, exakte
|
||||
saved-controller-/Generatorbytes, neues Agentimage, unverändertes Helperimage,
|
||||
Source-/Native-Receipt und geschützte15:30-Payloadbindung PASS. Beleg
|
||||
74ca4c2572872eb64cecc250aefd4bbffa5d8e4dc9b3729b5b83c19ac07a670f,
|
||||
`final-local-check.json` im570c-Fall. Neue native Baseline, tatsächlicher
|
||||
Paarwechsel und unabhängige Nachlese bleiben offen. Es wird kein Windowsabschluss
|
||||
oder funktionierender installierter Zeitvergleich behauptet.
|
||||
|
||||
## Transport wieder bestätigt: endgültiger570c-Stand nativ bereit
|
||||
|
||||
Nach Roots tatsächlichem Konsolen-/Transportreadback15:04:25UTC wurde ausschließlich
|
||||
der vorhandene570c-Fall fortgesetzt, unverändertes Ende15:30UTC. Tatsächliche
|
||||
Stagebestätigung für Helper5967…, endgültigen Agent0549… und Controller67d2…
|
||||
bestanden. Volle neue native Baseline bestätigt ursprüngliche Running-PIDs5528/9464,
|
||||
unveränderte config/PKI/ACLs und vollständigen bisherigen Helper-DB-/Lock-/Intent-
|
||||
zustand. BaselineSHA
|
||||
b1a7928f89ad2bb9c63720dedea6f343d644c9882052877b5144dc200537f5e7.
|
||||
Geschlossene Serverflags und Windows0-/Linux31/31/27-Zähler unverändert.
|
||||
Noch keine Dienständerung bis zu diesem Baselinebeleg. Nächster Schritt ist die
|
||||
genau einmalige, an diese neuen tatsächlichen Bytes gebundene Enterphase.
|
||||
|
||||
## ETS-Skalartypfehler vor erster Wirkung behoben
|
||||
|
||||
Die einmalige570c-Enterphase verweigerte `Original SCM invariant`. Die reine
|
||||
Nachlese zeigt erneut eigenen Ordner/active-intent und alle Stopmarker absent;
|
||||
Originaldienste laufen5528/9464. Keine Enterwiederholung und keine Dienstwirkung.
|
||||
Isolierter Vergleich aller sechs SCM-Felder inklusive CLR-/Basistyp und Wrapping
|
||||
belegt ausschließlich `sid_type`: Baseline und live beide System.Int32=1, aber
|
||||
der ETS-wrapped Registrywert erfüllt zusätzlich `-is[pscustomobject]` und wurde
|
||||
irrtümlich zu `{}` normalisiert. Die anderen fünf Felder stimmten exakt überein.
|
||||
|
||||
Der Vergleich rekonstruiert jetzt JSON-Skalare aus ihrem CLR-Basiswert vor dem
|
||||
Objektpfad (primitive Strings/Bool/Integer/finite Double/Decimal), ohne ETS-Notes
|
||||
als fachlichen Objektinhalt umzudeuten. Echte JSON-Objekte behalten alle Keys;
|
||||
Casekollisionen/Arrayreihenfolge/Null/Tiefengrenze bleiben geschützt. Unabhängiger
|
||||
enger Review der Quelle90c2708c… ohne weiteren konkreten Befund.
|
||||
|
||||
Tatsächlich anschließend auf derselben VM: vollständiges originales
|
||||
`SameOriginal` gegen gespeicherte Baseline und frischen LiveState bestanden.
|
||||
Zusätzlich native ETS-Add-Member-Fälle für Integer/String/Bool gleich,
|
||||
Scalaränderung/Arrayumkehr/Null gegenüber leerem Array weiterhin verweigert.
|
||||
Result82c4ebe75bff95005ebd946ae99e206ec69648bec93adb17cf683c46fc46212a,
|
||||
`typed-full-pre-effect-comparison.json` im570c-Fall. Weiterhin keine Ordner/active-
|
||||
Marker und keine Dienständerung. Neuer Controllerfall folgt getrennt;570c bleibt
|
||||
als fehlgeschlagene Vorwirkungsphase erhalten.
|
||||
|
||||
## Neuer typkorrigierter Fall4887 nativ bereit
|
||||
|
||||
Fall4887940a-4c9c-4807-aaf2-6fbc94faad46 bindet unverändert Agent0549/Helper5967,
|
||||
denselben echten Quell-/Linux9-/Windows9-Beleg und das unveränderte15:30-Fenster.
|
||||
Controller66ca45e15e8f790c4614db74dd491137d5e28104e2d28ee658cc287debcd021f.
|
||||
Alle festen Stagebytes erneut nativ bestätigt; volle frische Baseline einschließlich
|
||||
ursprünglicher PIDs5528/9464, config/PKI/ACLs und Helper-DB/Lock/Intents bestanden.
|
||||
Baseline00bf31bd5355dc77e0aadd73d2ab57ea32410956ef764f3f2aeb195bd218479e.
|
||||
Geschlossene Servergates unverändert, bis hier weiterhin kein Serviceeffekt.
|
||||
4887 besitzt noch keinen Enterversuch;570c bleibt getrennt vor Wirkung verweigert.
|
||||
|
||||
Nach dem tatsächlichen Dienstwechsel bestätigten SCM und MCP zunächst beide
|
||||
laufenden Dienste und die bisherige Geräteidentität. Der letzte Kontakt blieb
|
||||
dann bei 16:17:32 Uhr MEZ stehen. Um 16:21:38 Uhr authentifizierte der Agent
|
||||
sich weiterhin erfolgreich. Die drei serverseitigen Sperren für Restore,
|
||||
Sequenzregression und Sync-Recovery waren alle aus. Der neue Agent meldet
|
||||
`agent.update/1` und sendet eine passive `not_configured`-Beobachtung. Auf
|
||||
dem Server ließ der CHECK von `observations.source_id` ausschließlich
|
||||
`linux.base` und `windows.base` zu. PostgreSQL protokollierte seit dem Wechsel
|
||||
15 Verletzungen genau dieses CHECKs. Der erste Online-Status war damit kein
|
||||
Nachweis für fortlaufende Heartbeats.
|
||||
|
||||
Die Geräteansicht selektiert im geänderten API-Quellstand gezielt den neuesten
|
||||
Basisdatensatz. Die aus dem Produktcode extrahierte LATERAL-Abfrage lieferte in
|
||||
einer lesenden PostgreSQL-Prüfung auf dem Server die erwarteten Windows- und
|
||||
Linux-Werte sowie NULL für ein Gerät mit ausschließlich Updatebeobachtungen.
|
||||
Auch Mandant und Seitenstichtag wurden im Datensatz gegengeprüft.
|
||||
|
||||
## Tatsächlicher einmaliger Paarwechsel, Abschluss nur lesend wiedergewonnen
|
||||
|
||||
4887 führte den tatsächlichen Paarwechsel genau einmal aus: beide ursprünglichen
|
||||
Prozesse kontrolliert beendet, vier Originaldateien gesichert, Agent/Helper und
|
||||
reziproke geschlossene Settings/Pins vollständig ersetzt, danach Helper und Agent
|
||||
jeweils einmal gestartet. Neue tatsächlich laufende Kernel-/Serviceinstanzen:
|
||||
Agent0549… PID4420, Helper5967… PID10264. Der ursprüngliche Enteraufruf meldete
|
||||
allerdings beim abschließenden Schemaerhaltungscheck einen Fehler; er wurde
|
||||
**nicht** erneut aufgerufen. Originalmarker belegen alle vier Replacements und
|
||||
beide tatsächlichen Starts; `entered.json` wurde wegen des Nachprüfungsfehlers
|
||||
nicht geschrieben. Der erste Postcheck bleibt fehlgeschlagen.
|
||||
|
||||
Der exakte Nachbefund: Telemetriedatei-ID, Creation und Geräteidentitätshash sind
|
||||
identisch. Alle bisherigen Schemaeinträge/Trigger sind bytegleich erhalten;
|
||||
ausschließlich `update_health_inventory` wurde additiv angelegt. Deren komplette
|
||||
DDL entspricht der tatsächlich qualifizierten eingefrorenen Quelle
|
||||
`agent-core/src/update_health_inventory.rs` (Sourceinputs11717fab…). Dies ist
|
||||
keine globale Lockerung des Schemaerhalts: der Abschlussleser verlangt exakt
|
||||
einen zusätzlichen Eintrag, exakt diesen Typ/Namen/DDL und unveränderte übrige
|
||||
Einträge. Die neue Tabelle wurde nicht auf Zeileninhalt abgefragt; es wird keine
|
||||
solche Prüfung behauptet. Bestehende Job-/Reconcilezähler bleiben vollständig0,
|
||||
Serverjob-/Outbox-/Permitgates ebenfalls unverändert geschlossen.
|
||||
|
||||
Eine erste reine Abschlusslesung verweigerte fälschlich wegen PowerShell-
|
||||
Pipelineflattening der Schema-Tupel; nach Beschränkung auf explizite Listen
|
||||
bestand derselbe ausschließlich lesende Originalfallvergleich. Keine weitere
|
||||
Service-/Datei-/Jobmutation war Teil dieser Recovery. Der Reader prüft zusätzlich
|
||||
Originalintent/active-Bindung, vollständigen Config-/PKI-/Privatekeymetadaten-/
|
||||
DB-/Lock-/Helperrowerhalt sowie exakte beiden gespeicherten einzelnen neuen
|
||||
Service-/Kernelstarts. Native tatsächliche Zeitquelle/Clockfreigabe wird dadurch
|
||||
nicht behauptet.
|
||||
|
||||
Anschließend unabhängiger zweiter Originalfallread: dieselben neuen Prozesse,
|
||||
Images und Dateiidentitäten, sämtliche Erhaltungsbedingungen erneut bestanden.
|
||||
Belege im4887-Fall:
|
||||
|
||||
- `completion-readback.json`:13448d833b32dedfb5e07cb4e76f046e666522488ffabbb3a38a57d2d485d1b8
|
||||
- `independent-readback.json`:63e453fb915cadee028407a6aeaa8c7d209ae88ed12a6d4d4307d4fd25e4c539
|
||||
- `intent.json`:40e9cd557225504429b51dcecd4322b32d7f0973bcbb8e2a2e52516917907b85
|
||||
- `bound-payload.json`:074a13fd3e4cdefd85aedb5a9fc17d247994e0e515b71e4e0925f713d37774f7
|
||||
- `result.json`:2898a72b4b0d84159cc11d80765cbfa4206faf7038d0e860429c8b1a57538ee2
|
||||
|
||||
Das Resultat kennzeichnet ausdrücklich `recovered_postcondition_read=true` und
|
||||
`original_enter_postcheck_failed=true`. Es meldet keine erfundene erfolgreiche
|
||||
ursprüngliche Enterantwort. Kein Jobmodus, Effektgate, VM-Reboot, Enrollment,
|
||||
Gerätezertifikatswechsel oder Zeitprofil wurde durch diese Wartung aktiviert.
|
||||
|
||||
Getrennt offen: Parent bestätigte einmaligen korrekten neuen Hello/Identität und
|
||||
unverändertes Gerätezertifikat/Enrollment/Assignment, jedoch noch keine zwei
|
||||
fortlaufenden Heartbeats; gespeicherte Präsenz wurde später stale. Die zusätzliche
|
||||
Capability `agent.update/1` stammt aus dem konkret installierten passiven
|
||||
not_configured-Schema. Heartbeatkontinuität und installierte Clockautorität
|
||||
bleiben im Resultat ausdrücklich **nicht bewiesen**. Windows-MVP damit nicht
|
||||
vollständig abgenommen. Wichtige spätere Werkzeugverbesserung: erwartete additive
|
||||
Schemaentwicklung vor Wartung aus dem qualifizierten Quellstand planen; hierfür
|
||||
jetzt keinen allgemeinen Migrations-/Resumeframework bauen.
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
# Erste öffentliche Windows-Zeitkonfiguration V2
|
||||
|
||||
Stand 2026-11-15: Der reale Paarfall `4887940a-4c9c-4807-aaf2-6fbc94faad46`
|
||||
ist nach abgeschlossener unabhängiger Nachlese gebunden (Result `2898a72b…`,
|
||||
Originalintent `40e9cd55…`, separater Read `63e453fb…`). Die vorherige
|
||||
Verweigerung mit fehlenden Rollenbelegen bleibt als historischer lokaler Test
|
||||
nachgewiesen. Ein Zeitvertrauen oder durchgehende Heartbeats sind durch den
|
||||
Paarabschluss ausdrücklich nicht bewiesen.
|
||||
|
||||
Der Operator prüft die unveränderten öffentlichen Vorbereitungsbelege
|
||||
`c3077acf-12da-410e-9f55-e75a1cd0a75f`, deren getrennten Ed25519-Zeitschlüssel,
|
||||
Gerätebindung und tatsächlich gelesene KVM-Plattform. Die ursprüngliche
|
||||
Vorbereitung bleibt mit `roles_qualified=false` unverändert. Die akzeptierte
|
||||
Betriebsannahme ist ausdrücklich
|
||||
`active_guest_no_pause_save_restore_snapshot_migration_host_suspend`; das ist
|
||||
keine physikalische Kalibrierung und keine automatische Überwachung dieser
|
||||
Betriebsannahme.
|
||||
|
||||
Der neue Agent ist an SHA256
|
||||
`0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c`
|
||||
und Buildreceipt `f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446`
|
||||
gebunden. Seine 202 Quellinputs sind durch `11717fab…` fixiert; das tatsächlich
|
||||
erweiterte Zeitmodul hat SHA256 `342494c4…`. Gegen die ursprüngliche Quelle
|
||||
`d8594c1e…` kamen die passive Sampling-Auswahl und deren neunte Prüfung hinzu.
|
||||
Der Helper bleibt `59675a3c…`, aus dem ursprünglichen Linkbeleg `04ed34e6…`
|
||||
und Quellbeleg `96b05fe1…`. Diese unterschiedlichen Provenienzen werden nicht
|
||||
gleichgesetzt. Der tatsächliche neue Paar-Payload verwendet für
|
||||
`qualification_sha256` und `manifest_sha256` jeweils den neuen Beleg `f04024f7…`;
|
||||
der alte Helper-Quellbeleg ist kein Ersatz dafür.
|
||||
|
||||
Bevor ein Fall erstellt werden kann, müssen ein abgeschlossener passiver
|
||||
Paarwechsel und unabhängig fixierte Originalbelege vorliegen. Für beide Rollen
|
||||
werden SCM-Status, PID, Kernel-Prozessgeburt, tatsächliches Konto, aktivierte
|
||||
Service-SID, gehaltener Prozesshandle, Imagepfad, Imagehash und native FileID
|
||||
verknüpft. Die alten numerischen 601-Proben bleiben ausdrücklich rohe
|
||||
Voraussetzungsbelege; sie qualifizieren kein Produktimage. Der Producer erzeugt
|
||||
öffentliche Rollen- und Plattformbelege und daraus das vorhandene strikte
|
||||
V2-Format mit genau beiden Rollen. Er behauptet weder signierte Laufzeitprüfung
|
||||
noch physikalische Genauigkeit. Fehlende oder widersprüchliche Belege sperren.
|
||||
|
||||
## Geplanter Ablauf nach neuem realem Paar-Readback
|
||||
|
||||
Die folgenden Phasen sind **vorbereitet, nicht auf dem Ziel ausgeführt**:
|
||||
|
||||
1. Root bestätigt Original-Paarfall und Originalbeleg-Hashes; diese werden als
|
||||
konkrete Quellenkonstanten gebunden und nochmals geprüft.
|
||||
2. `prepare` liest ausschließlich öffentliche lokale Belege und erzeugt einen
|
||||
privaten, einmaligen Fall. `stage --case <id>` überträgt ausschließlich den
|
||||
fixierten Controller über den bestehenden bestätigten SSH-Transport.
|
||||
3. `install --case <id>` darf genau eine bisher fehlende feste öffentliche Datei
|
||||
veröffentlichen. Bereits vorhandene Datei, aktiver Marker oder Teilfall
|
||||
verweigern einen neuen Installationsversuch. Ein verlorener Antwortweg führt
|
||||
ausschließlich zu `read --case <id>`, nicht zu Wiederholung oder Rollback.
|
||||
4. Root liest den ursprünglichen Fall separat und prüft danach die echten
|
||||
passiven Agent-/Helper-Zeitbelege. Eine erfolgreiche Veröffentlichung allein
|
||||
setzt `clock_runtime_qualified` ausdrücklich nicht auf true.
|
||||
|
||||
## Begrenzte Wirkung und Erhaltungsnachweis
|
||||
|
||||
Der Controller verwendet ausschließlich die vorhandenen lesenden SCM-,
|
||||
Kernel-, FileID-, PKI-Metadaten- und Journalzeugen. Er importiert keine alten
|
||||
Stop-/Start-/Swap-/Repair-Phasen. Die aktuelle Prozessgeneration, beide Images,
|
||||
vier Code-/Policydateien, Konfiguration, Geräteidentität, Zertifikat,
|
||||
Schlüsselmetadaten, Telemetrieidentität, Sequenzmonotonie und leere
|
||||
Job-/Helper-Intents werden vor, während und nach der Veröffentlichung geprüft.
|
||||
Der private Schlüssel wird weder gelesen noch gehasht.
|
||||
|
||||
Eine neue private Bootstrap-Falldirectory wird nativ exklusiv mit geschützter
|
||||
SYSTEM-/Administrators-DACL angelegt. Alle Originalmarker werden create-only
|
||||
geschrieben und geflusht. Nur der öffentliche Helper-Stamm erhält bei Bedarf
|
||||
fehlende `0x001200a9`-Leserechte für beide **Service-SIDs**, ausschließlich für
|
||||
diesen Ordner, ohne Vererbung auf State/PKI/Ledger. Fremde oder weiter gehende
|
||||
Service-Rechte werden verweigert. Die Kandidatdatei erhält vor Veröffentlichung
|
||||
SYSTEM/Administrators-Vollzugriff und dieselben begrenzten Leser. Die feste
|
||||
Zieldatei wird nach durablem Publish-Intent mit einem gleichvolumigen,
|
||||
überschreibungsfreien Move veröffentlicht; anschließend müssen FileID, Hash
|
||||
und DACL unverändert sein. Keine allgemeine Stromausfall-Atomizität wird daraus
|
||||
abgeleitet. Teilzustände bleiben im Originalfall lesbar, ohne automatische
|
||||
Reparatur oder Rechte-Rücksetzung.
|
||||
|
||||
Unmittelbar vor der ersten Erstellung wird `install_not_before` aus der
|
||||
nativen VM-UTC gelesen und im ursprünglichen Intent sowie Ergebnis erhalten.
|
||||
Das ist eine Herkunftsuntergrenze für die nachfolgende separate Nachlese und
|
||||
den passiven Collector, keine eigenständige Uhrvertrauensbehauptung.
|
||||
|
||||
## Laden und tatsächliche Grenzen
|
||||
|
||||
Das vorhandene `signed_clock::native::SignedClock::open` lädt bei jedem Öffnen
|
||||
geschützte Settings, beweist den eigenen Dienstprozess und öffnet den festen
|
||||
Stamm sowie die maximal 16384 Byte große Datei über `PinnedFile`. Besitzer
|
||||
müssen SYSTEM/Administrators bleiben; zusätzliche Leser dürfen nur die
|
||||
festgelegte Lesemaske besitzen. Beide Images müssen zu den Settings passen.
|
||||
Die Prüfung bindet Dateiinhalt und FileID; spätere Rechecks öffnen denselben
|
||||
Namen erneut und verwerfen Austausch oder Änderungen. Fehlerhaft beobachtete
|
||||
Konfigurationen oder fehlgeschlagene Reads stellen alte Autorität nicht wieder
|
||||
her; geänderte Bytes derselben Generation gelten als Fork.
|
||||
|
||||
Im neuen Agenten versucht die passive Heartbeat-Schleife das Setup bei bisher
|
||||
fehlendem Profil erneut. Ein erster Pin benötigt daher nach Quellenvertrag
|
||||
keinen Dienstneustart. Das ist **noch kein VM-Nachweis**. Der Agent schreibt erst
|
||||
nach tatsächlich erfolgreichem `complete` pro Verbindung öffentliche historische
|
||||
`agent-time-sample.json` und `helper-time-sample.json` in sein bestehendes
|
||||
geschütztes State-Verzeichnis. Der Helper-State bleibt unverändert. Root muss
|
||||
diese Originalbelege noch für die tatsächlich installierten Rollen und
|
||||
Konfigurationsbytes prüfen. Ein Statusfile ersetzt kein aktuelles Job-Startgate.
|
||||
|
||||
## Tatsächlich lokal ausgeführt
|
||||
|
||||
- Python-Syntaxprüfung und geschlossene Sourceguards: PASS.
|
||||
- Sechs lokale Vertragsfälle: PASS. Sie prüfen die reinen Referenzbytes,
|
||||
fehlende Paarbelege, falsche Rollen/Images/Geburt/SID/FileID/Policy/Identität,
|
||||
create-only, begrenztes Lesen, Symlink- und Duplicate-JSON-Verweigerung.
|
||||
Positive In-Memory-Fixtures sind ausdrücklich keine native Qualifikation.
|
||||
- Beide erzeugten PowerShell-ASTs mit vorhandenem lokalem Parser: PASS.
|
||||
- Lokale ETS-Integer-/Bool-/String-Reproduktion sowie Objekt-/Arrayreihenfolge:
|
||||
PASS. Der unveränderte Vergleich aus `e6debe5` war unter Windows PowerShell 5
|
||||
unzureichend: ETS-verpacktes `System.Int32=1` konnte im Objektzweig zu `{}`
|
||||
werden. Der exakt übernommene Comparator aus der getrennt geprüften
|
||||
Clockquelle `90c2708c…` rekonstruiert CLR-Skalare vor dem Objektzweig als
|
||||
unadornierte Werte. Der Clockoperator hat diesen Vergleich außerdem tatsächlich
|
||||
gegen den vollständigen alten Livezustand und ETS-Positiv-/Negativfälle
|
||||
geprüft (`82c4ebe7…`). Das ist kein Profilinstallationsnachweis.
|
||||
- Die festgehaltenen öffentlichen Eingänge, rohen Rollenbelege und realen
|
||||
Quell-/Buildbelege werden vom Operator lokal erfolgreich gelesen. Die durch
|
||||
Root tatsächlich ausgeführten neun Linux- und neun Windows-Zeitmodulprüfungen
|
||||
sind über deren Originalbeleg-Hashes und exakte Testnamen angebunden.
|
||||
- `prepare` ohne reale Paarbelege: erwartete Verweigerung ohne angelegten Fall.
|
||||
|
||||
Im ursprünglichen lokalen Quellprüfstand noch nicht ausgeführt: Übertragung,
|
||||
ACL-Änderung, Konfigurationsinstallation,
|
||||
Produktdienst-Laden/Reopen auf der VM, signierte passive Laufzeitabnahme,
|
||||
WebUI-Genehmigung oder RMM-Job. Der damalige Transportausfall nach Notebook-Suspend war später im
|
||||
bestätigten Wartungsfenster behoben. Der vorbereitete Fall `570c7a86…` bleibt
|
||||
unverändert ohne neue Rollenbelege; der tatsächliche neue Paarbeleg ist4887.
|
||||
|
||||
## Tatsächlicher gebundener Vorbereitungsschritt und Transfer
|
||||
|
||||
Lokale Vorbereitung `ad9fd154-b2be-4f5d-9e17-65abb721ceaf` bestanden;
|
||||
Config-SHA256 `2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`,
|
||||
Manifest `0c9a3ffeed490757f7bd8c63d7e2ec28156212945094621f511e20679ce0b3b0`.
|
||||
Der getrennte Bindungsreview des Operators `a8d55b60…` hat bestanden.
|
||||
Erste tatsächliche Transferphase begann nach `2026-11-15T15:27:41Z`.
|
||||
Der fixierte Controller wurde einmalig übertragen und separat hashgeprüft;
|
||||
Originalantwort `stage-reply.json` im genannten privaten lokalen Fall,
|
||||
SHA256 `29f7654f766ebb53045832bb8c5ed6c83d2cbd96e0a5e1ce6df494cef0c026e6`.
|
||||
Noch kein Konfigurationsinstallations- oder Laufzeitnachweis aus diesem Schritt.
|
||||
|
||||
## Tatsächliche Installation: Teilzustand, nicht abgeschlossen
|
||||
|
||||
Der einmalige Installationsaufruf begann nach `2026-11-15T15:28:18Z`.
|
||||
Die VM hielt vor der ersten Erstellung die Originaluntergrenze
|
||||
`2026-11-15T15:28:24.1309868Z` im Intent fest. Der Bootstrap endete mit
|
||||
`IOException` an Controllerzeile294, dem einzigen
|
||||
`[IO.File]::Move($staged,$target)`. Der ursprüngliche sichere Fehlerbeleg
|
||||
`windows-client/system-pipe-upgrade/remote-error-b01d395c-9141-4bc6-ad70-1b67fb936881.json`
|
||||
enthält Exit1, Fehlerklasse und Zeile, keinen privaten Fehlertext. Die genaue
|
||||
I/O-Ursache ist damit noch nicht geklärt; es wird kein Sharing-/ACL- oder
|
||||
Antivirusproblem als bewiesen ausgegeben. Es gab keinen zweiten Installversuch.
|
||||
|
||||
Ein eigener ausschließlich lesender Originalaufruf begann nach
|
||||
`2026-11-15T15:28:37Z` und bestand. Originalantwort im privaten Fall
|
||||
`ad9fd154-b2be-4f5d-9e17-65abb721ceaf`:
|
||||
`read-51eea530-4155-42d7-9053-1008e84059b6-reply.json`, SHA256
|
||||
`93143fc05e7c814e9b164cd322abd411eee0dedcb485fbb5547a1db8f1975cd2`.
|
||||
Die feste Zieldatei ist **nicht vorhanden**. Der ursprüngliche Intent, aktive
|
||||
NoRetry-Marker, Directory-ACL-Intent und dessen Abschluss sowie der
|
||||
Publish-Intent sind vorhanden; ein `result.json` fehlt. Die nur für diesen
|
||||
Ordner erlaubten Service-Leserechte wurden somit gesetzt, die Konfiguration
|
||||
wurde nicht veröffentlicht. Originale FileIDs/Hashes/PKI-Metadaten, laufende
|
||||
Agent-/Helper-Prozessgenerationen, Jobfreiheit und Journalzeugen bestanden die
|
||||
lesende Erhaltungsprüfung.
|
||||
|
||||
Der Teilzustand bleibt unverändert; kein Retry, Rollback, Dienstwechsel oder
|
||||
RMM-Job wurde ausgeführt. Der passive Zeit-Collector wurde ausdrücklich
|
||||
**nicht** gestartet. `clock_runtime_qualified=false` bleibt bestehen. Nach dem
|
||||
bestätigten Wartungsfenster bis15:30UTC erfolgen keine weiteren VM-Aufrufe.
|
||||
Die gesonderte serverseitige `agent.update`-Inventar-Constraintkorrektur und
|
||||
anschließend frische Heartbeats/ACKs sowie echte signierte Zeitbelege bleiben
|
||||
getrennt zu prüfen. Eine spätere Fortsetzung benötigt zuerst eine lesende
|
||||
Ursachenklärung und einen konkret geprüften Vertrag für den ursprünglichen
|
||||
Teilfall; ein neuer Fall darf diesen Marker nicht umgehen.
|
||||
|
||||
## Unabhängiger lokaler Review des Move-Fehlers und fester Diagnosepfad
|
||||
|
||||
Der nachfolgende Review liest ausschließlich Quellen und vorhandene öffentliche
|
||||
Originalbelege auf dem Entwicklungsrechner. Kein Gast-/Serverzugriff, keine
|
||||
Installation, kein Retry und keine Freigabe wurden dabei ausgeführt.
|
||||
|
||||
Belegt ist der Ablauf bis zum Publish-Intent mit Kandidathash
|
||||
`2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b`,
|
||||
1177Bytes, Volume9815088561147542064 und FileID6d990300000003000000000000000000.
|
||||
Der spätere originale Read93143fc0… belegt das fehlende Ziel und fehlendes Resultat.
|
||||
Er fragt jedoch die Kandidatdatei selbst nicht ab. Ihr aktueller Bestand ist
|
||||
somit **nicht** nachgewiesen. Original-rootSDDL im Intent, ACL-done-SDDL und spätere
|
||||
rootSDDL sind bytegleich: die ACL-Phase wurde ausgeführt, ohne effektive Rechte
|
||||
zu ändern. Bestehende NoRetry-Marker bleiben bestehen.
|
||||
|
||||
Die genaue Ursache der IOException ist mit diesen Belegen nicht bestimmbar.
|
||||
Der alte Fehlerbeleg enthält weder HRESULT noch nativen Fehlercode. Die statisch
|
||||
geprüften WriteBytes-, FileIdentity- und FileVolume-Handles werden in `finally`
|
||||
geschlossen; ein eigener Handleleak ist daraus nicht belegt. Das rechtfertigt
|
||||
weder eine Sharing-Lockerung noch Dienststopp, ACL-Änderung, Antivirusausnahme,
|
||||
Copy/Delete-Fallback oder erneuten Move. Microsoft beschreibt für
|
||||
[File.Move](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move)
|
||||
mehrere IOException-Ursachen; die Regeln für vorhandene Handles stehen getrennt
|
||||
in [CreateFile](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew).
|
||||
Sharing, Defender oder ein konkreter Win32-Code bleiben hier ausdrücklich
|
||||
Hypothesen. Der ursprüngliche HRESULT darf aus späteren Lesefehlern nicht
|
||||
rückwirkend abgeleitet werden.
|
||||
|
||||
Der bestehende Pythonoperator hat deshalb einen **separaten, ausschließlich
|
||||
lesenden** Originalfallpfad `diagnose-partial` erhalten. Er bindet ausschließlich
|
||||
Fallad9fd154-b2be-4f5d-9e17-65abb721ceaf, dessen Manifest0c9a3ffe…,
|
||||
Originalgeneratora8d55b60…, Originalcontrollerd8b4fd4f… und Konfigurationshash2b4a….
|
||||
Die vorhandenen Marker und Originaldateien werden nicht geändert. `load_case`
|
||||
wird absichtlich nicht verwendet: dessen Generatorbindung darf nicht auf die
|
||||
neue Quelle umgedeutet werden. Ebenso wird keine neue Skript-SHA als ursprüngliche
|
||||
`request.script_sha256` ausgegeben. Der neue Reader hat eine eigene Source-SHA,
|
||||
die der kleine In-Memory-Launcher vor der Ausführung prüft; genau ausgeführte
|
||||
Readerbytes, Intent, rohe Antwort und separater Receipt werden ausschließlich
|
||||
in einem neuen lokalen700/600-Diagnosefall gespeichert.
|
||||
|
||||
Geplanter Aufruf, **hier nicht ausgeführt**, erst nach erneut ausdrücklich
|
||||
bestätigtem Zugang und dessen erfolgreichem Readback:
|
||||
|
||||
```sh
|
||||
python3 /home/kevin/Schreibtisch/Coding/rust-discovery-signed-clock/deploy/windows/time_profile_config.py diagnose-partial
|
||||
```
|
||||
|
||||
Kein `--case`: der Reader akzeptiert keine andere Fall-ID oder frei wählbare
|
||||
Pfade. Die lokalen Originalbelege liegen weiterhin im Agent-Updater-Worktree.
|
||||
Die geschützte aktuelle Zugangskonfiguration muss noch mindestens60s zulassen;
|
||||
sonst erfolgt kein SSHaufruf. Native PowerShell-AST-/VM-Ausführung dieses neuen
|
||||
Readers sind noch offen. Er enthält keine Publish-/ACL-/Serviceoperation und
|
||||
fragt weder Uhrqualität noch Dienst-Snapshot ab.
|
||||
|
||||
Der Reader liefert nur aktuelle Kandidat-/Zielidentität, Größe, Hash, DACLhash,
|
||||
Attribute und Zeiten sowie feste Originalmarker/active-Bindung und Root-SDDL.
|
||||
Aktuelle Lesefehler werden mit Exceptiontyp/HRESULT und nur bei passender
|
||||
HRESULT-Facility mit Win32-Code aufgezeichnet, ohne freien Fehlertext. Diese
|
||||
Nummern gehören ausschließlich zum **neuen Leseversuch**. Er setzt immer
|
||||
`old_move_hresult_unknown=true`, `retry_authorized=false`,
|
||||
`installation_verified=false` und `clock_runtime_qualified=false`.
|
||||
|
||||
Das Ergebnis ist Grundlage einer späteren Entscheidung, keine Retryerlaubnis:
|
||||
|
||||
- Kandidat unverändert und Ziel fehlt: Veröffentlichung weiterhin nicht erfolgt;
|
||||
im nächsten aktiven Wartungsfenster anhand des Originalzustands mit einem
|
||||
überprüften Finalisierungsbefehl fertigstellen. Das MVP-/Profilvorhaben ist
|
||||
bereits beauftragt; dafür keine pauschale zusätzliche Chatgenehmigung verlangen.
|
||||
- Ziel vorhanden: weder Move noch Install erneut aufrufen; zuerst Ziel-/Kandidat-
|
||||
FileID-/Hash-/ACLbindung und tatsächliche Laufzeitwirkung getrennt beurteilen.
|
||||
- Fehlender/veränderter Kandidat, widersprüchliche Marker, andere Dateiidentität
|
||||
oder Lesefehler: Teilzustand erhalten, keine automatische Rekonstruktion,
|
||||
Löschung oder Rechte-/Dienständerung.
|
||||
|
||||
Lokal tatsächlich bestanden: Pythoncompile, bestehende Sourceguards und acht
|
||||
Vertragsfälle, davon zwei neue für den geschlossenen Reader und seine exakte
|
||||
Source-/Intent-/Receiptbindung ohne Legacy-Hashadoption. Der Transport ist dabei
|
||||
vollständig gemockt; dies ist kein nativer Befund. Die Kontrollbelege des alten
|
||||
fehlgeschlagenen Installationsfalls bleiben bytegleich erhalten. Ein konkreter
|
||||
Publikationsfix wurde mangels belegter nativer Fehlerursache nicht erfunden.
|
||||
@@ -1,55 +0,0 @@
|
||||
# Windows: fester passiver mTLS-Zeitrouteprobe
|
||||
|
||||
Stand2026-11-15: Quelle und lokaler Windows-Cross-Link fertig, **noch keine native Ausführung**. Dieser enge Fixture dient als HTTP-/Broker-Endpunktnachweis vor dem erhaltenden passiven Paarupgrade. Er ist kein installierter Dienstrollen-, Trusted-Clock-, SignedSync-/Ready- oder Jobnachweis.
|
||||
|
||||
`crates/agent-windows/examples/time_route_probe.rs` verwendet ausschließlich die bestehende Geräteidentität der Windows-VM. Gerätecert/-key bleiben in den festen vorhandenen Statepfaden und werden nur intern für den gemeinsamen `https_channel::mtls_client` gelesen. Private Keybytes werden weder ausgegeben noch gehasht oder in Evidence kopiert; der zusätzliche rohe Zwischenbuffer wird nach Clientbau gelöscht. Es gibt kein PFX, Enrollment, neues Gerät, frei wählbares Netzwerkziel, Shellkommando oder Zertifikats-/Namensprüfungs-Bypass. Domain/SAN/SNI, Projekt-CA, TCP-Ziel88.99.80.202:443 und `/agent/v1/time-attestation` bleiben fest. Der Pool wird für die drei Aufrufe wiederverwendet.
|
||||
|
||||
Der Fixture läuft nur als tatsächlich berechtigter Bootstrapadministrator ohne Threadimpersonation. Er behauptet ausdrücklich keine LocalService-/SYSTEM-Ausführung. Eigener fester Fallpfad: `C:\ProgramData\RustDiscoveryBootstrap\time-route\<kanonische UUID>`, darin vor Start genau `TimeRouteProbe.exe`, `context.json`, `time-public-key.json`. Die beiden Kontrollpfade müssen Root-/Administrators-/SYSTEM-geschützt sein. Der tatsächliche EXE-Pfad muss zum eigenen Fall passen; `intent.json` wird create-only **vor** dem ersten Netzwerkaufruf geschrieben. Nach verlorenem Ergebnis werden ausschließlich Originaldateien gelesen, nicht derselbe Lauf wiederholt.
|
||||
|
||||
Die bestehende passive Agentkonfiguration und der bisherige öffentliche Peerpin sind fest an ihre Originalhashes aus14fb gebunden. Die Geräte-/Tenant-/Enrollment-/Assignment-/Jobpublickeybindung stammt aus diesem geschützten Peerpin; Agent-/Asset-ID sind fest. Deshalb ist dieser Fixture absichtlich für den Stand **vor** dem Paarupgrade vorgesehen. Ein später geänderter Peerpin wird nicht still adaptiert. Der echte separate öffentliche Zeitpin ist SHA256 `c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2`, unabhängig vom konkreten Jobkey geprüft. Private Signierdateien wurden nicht gelesen.
|
||||
|
||||
## Feste Protokollfälle und begrenzte Aussage
|
||||
|
||||
Je Aufruf wird eine neue eigene256-Bit-CSPRNG-Nonce verwendet, mit eigener zufälliger Prozessinkarnation und dem fest gebundenen Kontext. Positive Antwort: HTTP200, exakte kanonische Codec-/Signaturbytes, strikte Ed25519-Prüfung mit dem echten öffentlichen Zeitkey, kompletter Originalrequesthash einschließlich Nonce/Context, Serverinstanz/-boot, Key-ID/-generation und begrenzte signierte Qualitätsfelder. Verwendet wird der vorhandene `DalekVerifier`; kein neuer Algorithmus und keine vorgetäuschte `Sample`-/Calibration-/Clockkonstruktion.
|
||||
|
||||
Die beiden weiteren festen Fälle verändern ausschließlich den Tenant zur bekannten anderen Test-Tenant-ID (erwartet403) beziehungsweise die zuvor von Root gelesene aktuelle Connectiongeneration auf deren Vorgänger (erwartet409). Kein Helperrequest, Job-, Grant-, UI-, MCP-, Sync-/Enrollment- oder TimeSetterpfad. Jede Antwort ist begrenzt; drei feste Requests, jeweils höchstens3s. Diese Transporttimeoutgrenze ist **keine** behauptete1s-/100ms-Clockqualifikation. Clock-/Dienstrollen-/SyncReady-Nachweis bleibt ausdrücklich false.
|
||||
|
||||
Nur öffentliche Requests/Signaturantworten, Status-/Hashmetadaten und feste Scopefelder gelangen in den eigenen create-only Fall. Statische „keine Jobs/Grants“-Scopefelder ersetzen keinen unabhängigen tatsächlichen Serverzählersnapshot. Root muss vor/nach dieselben geschlossenen Windows-/Linux-/Policy-/Grantzähler und erhaltene PKI-/DB-/Lockidentitäten separat vergleichen. Erst dieser gekoppelte Beleg darf den Endpunkt als tatsächlich passiv abgenommen ausweisen.
|
||||
|
||||
## Noch fehlende echte Kontextdatei
|
||||
|
||||
Es wurde **keine** `context.json` mit Dummywerten erzeugt. Root liefert nach Gatewaydeployment den tatsächlichen frischen DB-/Bootbeleg; Deployment kann die Verbindungsgeneration ändern. Die enge Datei hat ausschließlich folgende Pflichtfelder:
|
||||
|
||||
| Feld | Bedeutung |
|
||||
| --- | --- |
|
||||
| `schema_version` | exakt1 |
|
||||
| `case_id` | exakte eigene kanonische Fall-UUID |
|
||||
| `connection_generation` | tatsächlich aktuell aus der Server-DB, größer1 |
|
||||
| `windows_boot_id` | tatsächliche aktuelle DB-`connection_boot_id` |
|
||||
| `server_boot_id` | tatsächliche aktuelle permanente Serverboot-ID |
|
||||
| `server_context_evidence_sha256` | unveränderlicher Root-Originalbeleg dieser frischen Abfrage |
|
||||
| `binding_sha256` | SHA256 der vorhandenen typisiert serialisierten öffentlichen Gerätebindung |
|
||||
|
||||
Der spätere feste Root-Operator muss Originalbeleg und frisch gerenderte Datei sowie tatsächliches Gateway-/Brokerdeployment vor Ausführung prüfen. Eine beliebige Callerboolean genügt nicht. Der Probe selbst prüft Serverantwort und Kontextbindung; diese vorgelagerte Provenienz ist zusätzlich Root-verantwortet. Der einzelne geplante CLI-Aufruf lautet strukturell `TimeRouteProbe.exe probe <eigene UUID>`; hier **nicht ausgeführt**.
|
||||
|
||||
## Tatsächlich lokal qualifiziert
|
||||
|
||||
Unveränderlicher Fall `time-route-fixture-qualification-3fdf513e-197b-41ab-b161-9dfc2adc94da`, exakt203 öffentliche Compilerinputs: der erhaltene c467-Produktcheckpoint202 plus genau dieses neue Example. Aktueller fremder Updater-WIP wurde bewusst nicht in diesen Fixture übernommen; es gibt keine Behauptung,203 entspräche dem gesamten gegenwärtigen Workspace. Inputmanifest `1c4ed151efacc60bc3487356fcbdca0b665a02da9b7ceef7454d5eaa4f310d47`; Fixturequelle `808ef3a3fe21ca100fae38250c40c0738c3e4076c686c642776f0aa2bc891d9c`; Receipt `fce8c42cce33a35be1ee0468c97010ac3797a713668503783e449d30ea538678`.
|
||||
|
||||
Rustfmt nur dieses Example (`skip_children`), Windows-Examplecheck, Clippy mit `-D warnings` und Release-Link PASS. Offline-Docker, Quellen nur lesbar, eigene private Targets, keine Credentials-Mounts. Keine zusätzlichen Tests oder VM-Abfragen ausgeführt; vorherige tatsächliche Linux-Codec-/Servernachweise werden separat durch Root gebunden, nicht durch diesen Cross-Build ersetzt.
|
||||
|
||||
`TimeRouteProbe.exe`:19172660Bytes, AMD64-PE, SHA256 `4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088`, Modus0500/ein Hardlink. Enger Readonly-Capabilitymanifest-SHA256 `22ca87604e942b91e68981f694934bc8c933c5fb5ab5858f27a2d3884d64df42`. Der neue Produktpaarbeleg26dc/5967 und dessen Modulquelle d859 bleiben unverändert; dieses Example installiert oder startet keinen Agenten.
|
||||
|
||||
Offen: unabhängiger Fixture-Review, echtes Gateway-/Brokerdeployment und dessen frische Kontextprovenienz, einmalige native Ausführung mit200/403/409, separater lesender Originalfallnachweis und tatsächliche Erhaltungs-/Nulljobwitnesses. Erst danach ist dieser Endpunktgate für die nächste getrennte passive Paarwartung verfügbar. Windows-MVP-Wirkungsabnahmen bleiben offen.
|
||||
|
||||
## Native passive Protokollabnahme
|
||||
|
||||
Tatsächlich anschließend auf der Windows-VM bestanden: genau ein fester
|
||||
HTTP200/403/409-Lauf mit echter Signatur-/vollständiger Kontextprüfung und Exit0,
|
||||
sowie separater Originalfallread mit bytegleicher Antwort. Fall68b841a5-784f-4a34-a8a4-060b267713f0;
|
||||
Runreplyc556747f75987f8d6ced477086cfd77edfb00f2ac74a99b6e721f3c278ecc28a,
|
||||
Runpreservation04bb81f781656f9e695225885b5088d498d1ebe5708a95db563dd6321525617a,
|
||||
Readpreservatione9ef65dc101505919bcba00e1a214d752f44154d6b3f5789c27234551e01e9b9.
|
||||
Details und die ehrlichen Grenzen des ersetzten alten Abschlusslesers stehen in
|
||||
`windows-time-route-operator.md`. Keine Dienstrolle/Clockfrische/SyncReady oder
|
||||
Jobwirkung durch diese Fixture bewiesen.
|
||||
@@ -1,121 +0,0 @@
|
||||
# Fester passiver Windows-Zeitroutennachweis
|
||||
|
||||
Quellenstand 2026-11-15: `deploy/windows/time_route_context.py` liest ausschließlich
|
||||
öffentliche aktuelle Installationsmetadaten nach dem getrennten Gatewaydeployment.
|
||||
`deploy/windows/time_route_acceptance.py` bereitet die bereits gebaute feste
|
||||
`TimeRouteProbe.exe` vor und besitzt ausschließlich die getrennten Phasen
|
||||
`stage`, `run` und `read`. Keine Phase verändert RMM-Dienste, Geräteidentitäten,
|
||||
Zeitdienst, Richtlinien oder Jobgenehmigungen.
|
||||
|
||||
Der Collector bleibt mit `DEPLOYMENT_RESULT_SHA=None` geschlossen. Der Operator
|
||||
bleibt mit `CONTEXT_GATE=None` geschlossen. Der Operator darf erst den tatsächlich
|
||||
abgelesenen Collectorfall und dessen BelegSHA binden. Keine Beispielkontexte,
|
||||
Dummykeys oder Kalibrierungszahlen ersetzen diese Daten. Vor Stage und Run wird
|
||||
exakt derselbe aktuelle öffentliche Kontext erneut gelesen. Ein Generations-,
|
||||
Boot- oder Gatewaywechsel verlangt eine gesonderte Bewertung; kein automatischer
|
||||
Retry und keine Umdeutung eines alten Belegs.
|
||||
|
||||
Die feste SQL-Transaktion ist `READ ONLY` und liest die aktive Windowsinstallation
|
||||
mit Enrollment, Assignment, Verbindungsgeneration, Windows-Boot und Capabilities.
|
||||
Zusätzlich werden tatsächlicher Serverboot und Gatewayimage/-identität vor/nach
|
||||
verglichen. Weder SQL-Zugangsdaten noch Geräteschlüssel werden gelesen oder
|
||||
exportiert. Auf Windows verwendet ausschließlich die geprüfte EXE den bestehenden
|
||||
Geräte-mTLS-Schlüssel intern, wie in `windows-time-route-fixture.md` beschrieben.
|
||||
|
||||
Die beiden Windows-Verzeichnisse für Nutzlast und Steuerbelege sind getrennt,
|
||||
damit die EXE zu Beginn genau ihre drei festen Eingabedateien vorfindet. Alle
|
||||
Steuerbelege entstehen neu; ein verlorener Run ist ausschließlich lesbar. Der
|
||||
Controller hält sein gestartetes Prozessobjekt mit Kernelhandle, wartet auf das
|
||||
tatsächliche Ende und begrenzt ausschließlich diesen eigenen Prozess bei Timeout.
|
||||
Die tatsächliche positive Signatur-/Kontextantwort sowie HTTP 403 und 409 müssen
|
||||
im unveränderten Bericht stehen. Die ursprünglichen sechs nativen Windowsfelder,
|
||||
Journalidentität und geschlossenen Servergates werden vor/nach separat geprüft.
|
||||
Diese Abnahme beweist Transport und kryptografische Kontextbindung, keine
|
||||
Dienstrolle, Timerqualität, aktuelle Clockfreigabe oder Jobwirkung.
|
||||
|
||||
Lokal tatsächlich ausgeführt: Pythoncompile, beide Quellguards, geschlossene
|
||||
Deployment-/Kontextgates, exakte groß-/kleinschreibungssensitive Aktionsgrenze und
|
||||
Prüfung gegen die PowerShell-Aliaskollision `H`. Alle bestanden. Originalfall
|
||||
`a324c4e5-d1a9-495e-aba8-cb755a174e98` unter
|
||||
`devstate/windows-time-route-source/`; ReceiptSHA
|
||||
`de5fdf7f01b0d0a40c4c8def16eaf87efc8bce2696d35e2097c9e394d52510ad`.
|
||||
Native PowerShell-AST, unabhängiger Quellenreview, tatsächliche Kontextablesung,
|
||||
Stage, Run und anschließender eigener Read sind hier noch nicht ausgeführt.
|
||||
Der Operator führt diese Schritte nicht automatisch aus.
|
||||
|
||||
## Tatsächliche native lesende Vorbereitung
|
||||
|
||||
Nach ausdrücklicher Rootdelegation wurde auf der vorhandenen Windows-VM die
|
||||
PowerShell-5.1-Quelle ausschließlich im Speicher mit `Parser.ParseInput` geparst.
|
||||
Tatsächlich: PowerShell5.1.26100.9818, null AST-Fehler, Controller nicht ausgeführt.
|
||||
Keine Stage-/Route-/Dienstaktion. Davor und danach lief ausschließlich der bereits
|
||||
angenommene originale14fb-`finish`-Leser mit seinen bestehenden passiven Journal- und
|
||||
SYSTEM-State-Probes: alle sechs stabilen nativen Felder und Journalidentität
|
||||
unverändert, Sequenz monoton. Diese Probes rufen keine Clock-/Snapshotoperation
|
||||
auf; sie ersetzen keinen Zeitrollen- oder aktuellen Frischebeweis.
|
||||
|
||||
Eigener unveränderlicher Fall
|
||||
`devstate/windows-time-route-native-readonly/a6d61a92-b7f3-4a8d-9df0-569941ab7ccd`,
|
||||
ReceiptSHA `44504007fa7d0379e608375181b926ff2a20ae248cfeb2fb51d127b858b3536d`.
|
||||
ScriptSHA bleibt `4c88fdf36f22b0273baaa08bf522bfefbf8482b45317ef852c0e0a331a1fbef2`.
|
||||
Deployment-/Kontextgates bleiben geschlossen, Stage und Route weiterhin offen.
|
||||
|
||||
## Tatsächliche passive Route und separater Read bestanden
|
||||
|
||||
Root hat den tatsächlichen erfolgreichen Unterfall
|
||||
`continue-backend-v1/result.json` mit SHA
|
||||
`3017634f101ee8aff62988f195ccb3a7a8b9e03eaa48b8fb339af9ceb3ad2b4b`
|
||||
und separater Nachlese gebunden. Der alte fehlgeschlagene Deploymentfall bleibt
|
||||
unverändert fehlgeschlagen. Collectorfall68b841a5-784f-4a34-a8a4-060b267713f0,
|
||||
Receipt658fa5ffa63c6e412237f5feb718b745bb560230f17c54e437ad8bd98e9ad65b,
|
||||
Kontext3c0e4ff3b16b86fb4e98d2ff163686305ea533570c40ae3bef1270ab89648ed3:
|
||||
tatsächliche aktuelle Geräte-/Tenant-/Generation-/Bootbindung und Gatewayimage.
|
||||
Die ungenutzte doppelte Deploymentpfadkonstante wurde entfernt.
|
||||
|
||||
Stage meldete tatsächlich Erfolg, bevor der nachgelagerte alte14fb-finish-
|
||||
Leser nach180s ohne Antwort abbrach. Das ist kein erfolgreicher Originalwitness.
|
||||
Eine direkte lesende Diagnose antwortete sofort, keine laufenden Probeprozesse.
|
||||
Der erste Agentname dieser Diagnose war falsch; `present=false` für
|
||||
`RustDiscoveryAgent` ist kein Ausfall des tatsächlichen `RmmDiscoveryWindows`.
|
||||
Keine Stage wurde wiederholt und bis dahin kein HTTP-Probelauf gestartet.
|
||||
|
||||
Auf ausdrückliche Rootanweisung ersetzte die Fortsetzung den hängenden früheren
|
||||
Upgradeabschlussleser durch dessen vorhandene reine FileID-/SCM-/Kernelprimitive,
|
||||
ohne Journal-/Clock-/Snapshotaufruf. Die ersten umfangreichen Readerbytes
|
||||
überschritten als EncodedCommand die Windows-Kommandozeilengrenze; der Reader
|
||||
wurde danach als feste hashgebundene Nutzlast über stdin übermittelt. Auch dieser
|
||||
Fehler lag vor jedem Probestart. Originalbelege wurden nicht überschrieben.
|
||||
Die Fortsetzung liegt als enge `direct()`-Funktion im bestehenden Operator;
|
||||
keine weitere Operator-Datei entstand. Tatsächlich ausgeführte Quelle ist im
|
||||
Originalfall als `executed-direct-operator.py` unverändert gesichert.
|
||||
|
||||
Der einzige tatsächliche TimeRouteProbe-Lauf ergab:
|
||||
|
||||
- HTTP200, echte Ed25519-Signatur, kompletter eigener Nonce-/Request-/Kontextbezug.
|
||||
- HTTP403 für den fest abweichenden Tenant.
|
||||
- HTTP409 für die vorherige Verbindungsgeneration.
|
||||
- Tatsächliches Kernelprozessende mit Exit0, kein Timeout, stderr leer.
|
||||
|
||||
Runreply `c556747f75987f8d6ced477086cfd77edfb00f2ac74a99b6e721f3c278ecc28a`,
|
||||
Erhaltungsbeleg `04bb81f781656f9e695225885b5088d498d1ebe5708a95db563dd6321525617a`.
|
||||
Separater Read `read-direct-6f2e1bc2-e26c-4dfb-a642-06a6a154ef5c` bestätigt
|
||||
bytegleichen gespeicherten Runreply und neuen Erhaltungsbeleg
|
||||
`e9ef65dc101505919bcba00e1a214d752f44154d6b3f5789c27234551e01e9b9`.
|
||||
Tatsächlicher ReportSHA9f1635c19c801f95c9828e9e31071a487b430f105a61977ee2d60f076f3d3623,
|
||||
ExitfileSHA6d131d2796936913f53286573e56f7fb3e515d04ebbd55ae9d6794440e6053b5.
|
||||
|
||||
Direkt vor/nach Run und Read unverändert: laufende ursprüngliche Dienste mit
|
||||
Kernel-PID/Geburt/Image/Konto, ursprüngliche config/PKI/Publicpin-Bytes,
|
||||
DateiIDs/ACLs und Privatekeymetadaten ohne Keyread, native Telemetriedateiidentität
|
||||
sowie aktuelle Helper-DB-/Lockdateiidentitäten. Deren alte FileID/Geburt stimmen
|
||||
ebenfalls; die historischen ACL-Digests aus dem anderen Probe sind abweichend
|
||||
und werden ausdrücklich nicht als erfolgreicher Altvergleich ausgegeben.
|
||||
Aktuelle direkte ACL-Metadaten sind vor/nach identisch. Geschlossene Windows-
|
||||
Job-/Outbox-/Permitzähler bleiben0; Linux31/31/27 und Rootpolicy unverändert.
|
||||
Der alte umfassende Journalabschlussleser bleibt als Timeout offen; es wurde
|
||||
keine erneute Journalintegritätsprüfung behauptet.
|
||||
|
||||
Dies ist ausschließlich eine tatsächliche passive mTLS-/Signatur-/Kontextabnahme.
|
||||
Dienstrollen-Zeitauthorität, Clockfrische, SyncReady und Jobwirkungen bleiben
|
||||
weiterhin unbewiesen und geschlossen. Kein Agentpaarwechsel oder VM-Neustart
|
||||
war Bestandteil dieses Schrittes.
|
||||
@@ -79,72 +79,3 @@ aktuelle Runtime-/Control-/Stateidentitäten, Receipt
|
||||
Unabhängiger Quellenreview des Schema-/Bracket-/Constructorfencedeltas ebenfalls
|
||||
ohne konkreten Befund abgeschlossen. Keine Windows-Rollen-/Zeitkonfiguration,
|
||||
kein RMM-Job oder Effektgate wurde dadurch aktiviert.
|
||||
|
||||
## Tatsächliche öffentliche Vorbereitungsdaten, keine Konfiguration
|
||||
|
||||
Lokaler Fall `windows-time-profile-public-preparation/c3077acf-12da-410e-9f55-e75a1cd0a75f`
|
||||
bindet den tatsächlich selektiv gelesenen KVM-/Hypervclock-Plattformbeleg94ae865e…,
|
||||
den echten öffentlichen Zeitpin c31d31d2…, die unveränderte öffentliche14fb-
|
||||
Gerätebindung und das tatsächliche202-Input-Produktpaar26dc/5967. Receipt
|
||||
`97e4db147f31f3cff134d2bc596d7d73ea5330b8b5a87971f215bb03a9751391`,
|
||||
Provenienz `1c0db66cd0692024f68bddd71949692d274380a86e4b880fea0756479ceb5d0c`.
|
||||
Timekey und konkreter Jobkey sind verschieden. Keine private Signierdatei gelesen.
|
||||
|
||||
Der ausdrücklich gelieferte öffentliche Plattformoriginalbeleg hat Modus0664;
|
||||
der vorhandene0600-Pinloader wies ihn zuerst erwartungsgemäß ab. Originalbytes
|
||||
und Modus wurden nicht geändert. Die bekannte SHA94ae bindet ausschließlich eine
|
||||
neue eigene0600-Kopie innerhalb dieses lokalen700-Falls; sie wird nicht als schon
|
||||
provisionierter geschützter Zielpin ausgegeben. Keine zusätzliche Operatorquelle
|
||||
oder Toolinstallation entstanden.
|
||||
|
||||
Dieser Fall ist ausdrücklich **keine** `time-attestation.json`. Für die beiden
|
||||
Schema2-`qualification_sha256` fehlen noch tatsächliche Dienst-/Prozess-/Imagebelege
|
||||
der neuen Produktimages. Der frühere Rawcapture-Probe601… ist ein anderes Image
|
||||
und ersetzt diese Bindung nicht. Nach der getrennten passiven Paarwartung dürfen
|
||||
die tatsächlichen neuen LocalService-/SYSTEM-Kernel-/Servicebelege mit vorhandenen
|
||||
Source-, Rawcapture- und Plattformbelegen verbunden werden. Erst danach wird die
|
||||
echte V2-Konfiguration erstellt; Runtimefrische und Genehmigungen folgen getrennt.
|
||||
|
||||
## Zeitprüfung bei ausgeschalteten Jobs am 15. November 2026
|
||||
|
||||
Die Konsole der laufenden VM bestätigte, dass weder der Jobschalter noch die
|
||||
Jobbindung konfiguriert waren. Die Zeitprofildatei war noch nicht installiert.
|
||||
Die bisherige Runtime übersprang bei ausgeschalteten Jobs auch den gesamten
|
||||
signierten Zeitvergleich. Damit konnte die geplante Rollenprüfung über diesen
|
||||
passiven Dienststand nicht beginnen.
|
||||
|
||||
Im neuen Quellstand prüft der Agent am Heartbeat, ob das geschützte Zeitprofil
|
||||
vorliegt. Erst dann beginnen Agent und Helper den vorhandenen Vergleich mit
|
||||
eigenen Challenges. Für den passiven Betrieb beträgt die Pause zwischen
|
||||
Vergleichen pro Rolle 30 Sekunden. Die Datei allein belegt keine Zeitqualität.
|
||||
Beide Rollen prüfen Pin, Gerätebindung, Signatur und Fristen. Der Jobschalter,
|
||||
die JobClock und die Genehmigung bleiben getrennt. Ein Fehler beim Start des
|
||||
passiven Vergleichs lässt Heartbeats und Inventar weiterlaufen.
|
||||
|
||||
Neun gezielte Prüfungen bestanden erst lokal und dann auf der Cloud-Linux-VM
|
||||
als UID 65534 (Exit 0, 15 weitere Tests gefiltert, Ergebnis-SHA-256
|
||||
`3424b0f916f0c9e68ed24d8ee0adeeb5feb5e8e834f63cfcbaadc5e45b06f840`).
|
||||
Die neue Prüfung umfasst Profilauswahl und Abfrageintervall. Der Windows-Crossbuild
|
||||
der Librarytests und Clippy mit allen Windows-Targets und `system-helper`
|
||||
bestanden. Die installierten Dienstbinärdateien haben eigene Versionsnachweise.
|
||||
|
||||
Dieselben neun Tests liefen danach aus dem gebauten Windows-Testbinary auf der
|
||||
Windows-11-VM. Die Namensliste der bestandenen Tests stimmte mit der auf der
|
||||
Cloud-Linux-VM überein. Ergebnis: AMD64, Exit 0, neun bestanden, null
|
||||
fehlgeschlagen oder übersprungen, 42 weitere gefiltert. Quittung
|
||||
`39c76e698f5dd351096d1deed40cddbcc1a6677f93457b48ad4a4c3cedb36e88`.
|
||||
Der native Testprozess prüfte die Logik mit Testdaten. Der signierte
|
||||
Zeitvergleich in den beiden installierten Dienstprozessen ist eine eigene
|
||||
offene Abnahme.
|
||||
|
||||
Für den Nachweis aus den laufenden Diensten hält der Agent je passiver Verbindung
|
||||
den ersten vollständig geprüften Zeitvergleich pro Rolle fest. Im Agent-State
|
||||
entstehen `agent-time-sample.json` und `helper-time-sample.json`. Die
|
||||
SYSTEM-Beobachtung setzt die authentifizierte positive Antwort des Helpers auf
|
||||
`TimeComplete` voraus. Beide Belege enthalten Rolle, Agent-PID, Windows-Boot,
|
||||
Verbindungsgeneration, Verifier-Inkarnation, Beobachtungszeit und die SHA-256-Werte
|
||||
der Anfrage und der empfangenen Antwort. Der Agent veröffentlicht sie beim
|
||||
Heartbeat aus dem Zustand der jeweiligen Verbindung. Diese historischen Daten
|
||||
werden bei der Jobfreigabe und der Prüfung der aktuellen Zeit nie eingelesen.
|
||||
Der erweiterte Code bestand den Windows-Alltargets-Clippycheck. Die tatsächlichen
|
||||
Belegdateien der installierten Rollen stehen noch aus.
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"os": "Linux",
|
||||
"hostname": "synthetic-codec-only",
|
||||
"architecture": "x86_64",
|
||||
"root_total_bytes": 2,
|
||||
"root_available_bytes": 1,
|
||||
"root_available_inodes": 1,
|
||||
"collection_started_at": "2026-11-15T12:00:00Z",
|
||||
"collection_completed_at": "2026-11-15T12:00:00Z",
|
||||
"observations": [
|
||||
{
|
||||
"scope": "linux.agent_update.catalog",
|
||||
"source_id": "agent:cached-release-catalog-v1",
|
||||
"observed_at": "2026-11-15T12:00:00Z",
|
||||
"quality": "valid",
|
||||
"completeness": "complete",
|
||||
"truncated": false,
|
||||
"error_code": null,
|
||||
"data": {
|
||||
"schema_version": 1,
|
||||
"source_id": "mtls:release-catalog-v1",
|
||||
"checked_at": "2026-11-15T10:00:00Z",
|
||||
"status": "available",
|
||||
"candidate": {
|
||||
"release_id": "11111111-1111-4111-8111-111111111111",
|
||||
"release_sequence": 8,
|
||||
"version": "0.1.8",
|
||||
"manifest_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"keyring_generation": 4
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
|
||||
it('shows actual check time separately from later inventory cache reading without actions or requests', () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
|
||||
try {
|
||||
const device = { inventory: JSON.parse(readFileSync(new URL('../../tests/agent_update/catalog-check-inventory.json', import.meta.url),'utf8')) };
|
||||
const html = renderToStaticMarkup(<CatalogCheckNotice device={device}/>);
|
||||
for (const expected of ['2026-11-15T10:00:00Z', '2026-11-15T12:00:00Z', '0.1.8', 'available', 'keine Installation']) expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(button|form|input|script)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
device.inventory.observations[0]!.data.candidate.version = '<script>approve()</script>';
|
||||
expect(renderToStaticMarkup(<CatalogCheckNotice device={device}/>)).toContain('role="alert"');
|
||||
expect(renderToStaticMarkup(<CatalogCheckNotice device={{inventory:{}}}/>)).toBe('');
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { RecordValue } from './api';
|
||||
|
||||
function object(value: unknown): RecordValue | null { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : null; }
|
||||
const exact = (value: RecordValue, keys: string[]) => Object.keys(value).every(key => keys.includes(key));
|
||||
const date = (value: unknown): value is string => typeof value === 'string' && value.length <= 40 && Number.isFinite(Date.parse(value));
|
||||
const positive = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0;
|
||||
export function CatalogCheckNotice({ device }: { device: unknown }) {
|
||||
const inventory = object(object(device)?.inventory), entries = inventory?.observations;
|
||||
if (!Array.isArray(entries)) return null;
|
||||
const matches = entries.map(object).filter(entry => entry?.scope === 'linux.agent_update.catalog');
|
||||
if (!matches.length) return null;
|
||||
const invalid = <p role="alert">Gespeicherter Releasekatalogcheck ist ungültig; kein Updatebeleg.</p>;
|
||||
if (matches.length !== 1) return invalid;
|
||||
const entry = matches[0]!, report = object(entry.data);
|
||||
if (!report || entry.source_id !== 'agent:cached-release-catalog-v1' || entry.completeness !== 'complete' || entry.truncated !== false || !date(entry.observed_at)
|
||||
|| !exact(report, ['schema_version', 'source_id', 'checked_at', 'status', 'candidate']) || report.schema_version !== 1 || report.source_id !== 'mtls:release-catalog-v1'
|
||||
|| !date(report.checked_at) || Date.parse(report.checked_at) > Date.parse(entry.observed_at) + 1000) return invalid;
|
||||
const status = report.status, candidate = object(report.candidate), available = status === 'available' || status === 'current';
|
||||
if (!(available || status === 'not_configured' || status === 'unavailable') || entry.quality !== (available ? 'valid' : status === 'not_configured' ? 'unknown' : 'error')) return invalid;
|
||||
if (available ? !candidate || !exact(candidate, ['release_id', 'release_sequence', 'version', 'manifest_sha256', 'keyring_generation'])
|
||||
|| typeof candidate.release_id !== 'string' || !/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(candidate.release_id)
|
||||
|| !positive(candidate.release_sequence) || !positive(candidate.keyring_generation) || typeof candidate.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(candidate.version)
|
||||
|| typeof candidate.manifest_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(candidate.manifest_sha256) : Object.hasOwn(report, 'candidate')) return invalid;
|
||||
return <aside aria-label="Gespeicherter Releasekatalogcheck"><h4>Passiver Releasekatalogcheck</h4>
|
||||
<p>Status: {String(status)} · geprüft: <time>{report.checked_at}</time></p><p>Cache im Inventar gelesen: <time>{entry.observed_at}</time></p>
|
||||
{candidate && <p>Release: {String(candidate.version)} · Sequenz {String(candidate.release_sequence)}<br/>Manifest SHA-256: <code>{String(candidate.manifest_sha256)}</code></p>}
|
||||
<p>Katalogmetadaten; keine Installation oder Ausführungserlaubnis.</p></aside>;
|
||||
}
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
@@ -98,7 +97,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string;
|
||||
return <section><h2>Geräte und gespeichertes Inventar</h2><p>Präsenz, Datenfrische und fachliche Gesundheit sind unabhängig. „unreachable“ bedeutet nicht „ausgeschaltet“.</p><ErrorBox error={list.error}/>
|
||||
{!list.data ? <p>Lade Geräte …</p> : <><PageStatus data={list.data}/><div className="table"><table><thead><tr><th>Fest auswählen</th><th>Gerät / Asset-ID</th><th>Präsenz / Gesundheit</th><th>Quelle / Qualität</th><th>Erhebung / Alter / Empfang</th></tr></thead><tbody>{list.data.items.map(d => { const id = objectId(d, 'asset'); return <tr key={id}><td><input aria-label={`Ziel ${id}`} type="checkbox" checked={selected.includes(id)} onChange={e => setSelected(e.target.checked ? [...selected, id] : selected.filter(v => v !== id))}/></td><td><button className="link" onClick={() => setAsset(id)}>{typeof d.hostname === 'string' ? d.hostname : id}</button><small>{id}</small></td><td>{stringField(d, 'presence')} / {stringField(d, 'health')}<small>Kontakt: {stringField(d, 'last_contact_at')}</small></td><td>{stringField(d, 'source_id')} / {stringField(d, 'quality')}<small>{stringField(d, 'completeness')}</small></td><td>{stringField(d, 'observed_at')}<small>Alter: <Age value={d.observed_at}/> · empfangen: {stringField(d, 'received_at')}</small></td></tr>; })}</tbody></table></div>{!list.data.items.length && <p>Keine sichtbaren Geräte in diesem Listenabschnitt.</p>}<button disabled={!cursor} onClick={() => setCursor(null)}>Erste Seite</button> <button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste Seite</button></>}
|
||||
<p>Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}</p>
|
||||
{asset && <article><h3>Inventardetail {asset}</h3><ErrorBox error={detail.error}/>{detail.data && <><CatalogCheckNotice device={detail.data}/><JsonView value={detail.data} label="Inventar, Capabilities, Metriken, Dienste, Software, Updates, Logs und Quellen (soweit geliefert)"/></>}<AdminControl auth={auth} path={tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}/revocation`)} permission="devices:revoke" title="Geräteidentität widerrufen" warning="ACHTUNG: Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Kein Entfernen aus einer Liste, kein Rollback. Wiederaufnahme erfordert einen gesonderten sicheren Enrollment-/Recoveryprozess." done={detail.reload}/></article>}
|
||||
{asset && <article><h3>Inventardetail {asset}</h3><ErrorBox error={detail.error}/>{detail.data && <JsonView value={detail.data} label="Inventar, Capabilities, Metriken, Dienste, Software, Updates, Logs und Quellen (soweit geliefert)"/>}<AdminControl auth={auth} path={tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}/revocation`)} permission="devices:revoke" title="Geräteidentität widerrufen" warning="ACHTUNG: Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Kein Entfernen aus einer Liste, kein Rollback. Wiederaufnahme erfordert einen gesonderten sicheren Enrollment-/Recoveryprozess." done={detail.reload}/></article>}
|
||||
</section>;
|
||||
}
|
||||
const initialParameters: Record<Action, RecordValue> = {
|
||||
|
||||
Reference in New Issue
Block a user