Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6c4037d07 |
Generated
-1
@@ -2263,7 +2263,6 @@ dependencies = [
|
||||
"tokio-tungstenite 0.28.0",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -785,8 +785,38 @@ pub(crate) fn msi_test_job() -> JobPayload {
|
||||
}
|
||||
}
|
||||
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
|
||||
write_report(state, PROBE_FILE, ".helper-probe.pending", value)
|
||||
}
|
||||
|
||||
/// A historical observation by the agent. The helper lane calls this only after
|
||||
/// the authenticated peer has acknowledged its own signature verification.
|
||||
pub fn record_verified_time(
|
||||
state: &Path,
|
||||
request: &rmm_time_attestation::Request,
|
||||
response_sha256: &str,
|
||||
observed_at: chrono::DateTime<chrono::Utc>,
|
||||
) -> Result<()> {
|
||||
use sha2::{Digest, Sha256};
|
||||
let (filename, pending) = match request.context.role {
|
||||
rmm_time_attestation::Role::Agent => ("agent-time-sample.json", ".agent-time.pending"),
|
||||
rmm_time_attestation::Role::SystemHelper => {
|
||||
("helper-time-sample.json", ".helper-time.pending")
|
||||
}
|
||||
};
|
||||
let value = json!({
|
||||
"schema_version": 1, "agent_pid": std::process::id(), "observed_at": observed_at,
|
||||
"role": request.context.role, "windows_boot_id": request.context.windows_boot_id,
|
||||
"connection_generation": request.context.connection_generation,
|
||||
"verifier_incarnation": request.context.verifier_incarnation,
|
||||
"request_sha256": format!("{:x}", Sha256::digest(serde_json::to_vec(request)?)),
|
||||
"response_sha256": response_sha256
|
||||
});
|
||||
write_report(state, filename, pending, &value)
|
||||
}
|
||||
|
||||
fn write_report(state: &Path, name: &str, pending: &str, value: &serde_json::Value) -> Result<()> {
|
||||
native::private_path(state, true)?;
|
||||
let path = state.join(PROBE_FILE);
|
||||
let path = state.join(name);
|
||||
if path.try_exists()? {
|
||||
native::private_path(&path, false)?;
|
||||
}
|
||||
@@ -794,7 +824,7 @@ fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
|
||||
ensure!(bytes.len() <= 8192, "HELPER_PROBE_REPORT_LIMIT");
|
||||
// One fixed create-only staging file bounds even interrupted-report state.
|
||||
// A leftover from a killed process is refused; it is never overwritten.
|
||||
let temporary = state.join(".helper-probe.pending");
|
||||
let temporary = state.join(pending);
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
|
||||
@@ -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::*;
|
||||
@@ -177,6 +176,7 @@ struct TimeRefresh {
|
||||
clock: rmm_agent_windows::signed_clock::RuntimeClock,
|
||||
helper: Option<rmm_agent_windows::helper_runtime::Client>,
|
||||
tasks: Vec<tokio::task::JoinHandle<()>>,
|
||||
samples: Vec<Arc<std::sync::OnceLock<VerifiedTimeSample>>>,
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
impl Drop for TimeRefresh {
|
||||
@@ -189,6 +189,30 @@ impl Drop for TimeRefresh {
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
struct VerifiedTimeSample {
|
||||
request: rmm_time_attestation::Request,
|
||||
response_hash: String,
|
||||
observed_at: chrono::DateTime<Utc>,
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
impl VerifiedTimeSample {
|
||||
fn new(request: rmm_time_attestation::Request, response_hash: String) -> Self {
|
||||
Self {
|
||||
request,
|
||||
response_hash,
|
||||
observed_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
fn persist(&self, state: &Path) -> Result<()> {
|
||||
rmm_agent_windows::helper_runtime::record_verified_time(
|
||||
state,
|
||||
&self.request,
|
||||
&self.response_hash,
|
||||
self.observed_at,
|
||||
)
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
async fn time_response(
|
||||
client: &reqwest::Client,
|
||||
address: std::net::SocketAddr,
|
||||
@@ -412,8 +436,6 @@ struct Agent {
|
||||
identity: EnrollmentResponse,
|
||||
ca: Vec<u8>,
|
||||
journal: Journal,
|
||||
certificates: RotationStore,
|
||||
key_files: ProtectedKeyFiles,
|
||||
boot: String,
|
||||
instance: String,
|
||||
started: Instant,
|
||||
@@ -458,9 +480,13 @@ impl Agent {
|
||||
identity: &crate::certificate_rotation::DeviceIdentity,
|
||||
) -> Result<()> {
|
||||
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
|
||||
if !self.config.enable_jobs {
|
||||
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
|
||||
// Presence opts into sampling only. Each role opens and verifies the
|
||||
// protected profile and signed response itself before accepting time.
|
||||
let Some(mode) = SamplingMode::configured(self.config.enable_jobs, Path::new(CONFIG_PATH))?
|
||||
else {
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let client = crate::https_channel::mtls_client(
|
||||
self.config.connect_address,
|
||||
&self.ca,
|
||||
@@ -480,6 +506,17 @@ impl Agent {
|
||||
let own_stop = stop.clone();
|
||||
let own_http = client.clone();
|
||||
let address = self.config.connect_address;
|
||||
// Only the connection owner publishes observations. Dropping it also
|
||||
// discards unfinished samples, so an old worker cannot overwrite a newer report.
|
||||
let sample_slot =
|
||||
|| (mode == SamplingMode::Passive).then(|| Arc::new(std::sync::OnceLock::new()));
|
||||
let own_receipt = sample_slot();
|
||||
let helper_receipt = helper.as_ref().and_then(|_| sample_slot());
|
||||
let samples = own_receipt
|
||||
.iter()
|
||||
.chain(helper_receipt.iter())
|
||||
.cloned()
|
||||
.collect();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
while !own_stop.load(Ordering::SeqCst) {
|
||||
let result = async {
|
||||
@@ -489,18 +526,18 @@ impl Agent {
|
||||
let request = own_clock.begin(generation)?;
|
||||
let bytes = time_response(&own_http, address, &request).await?;
|
||||
ensure!(!own_stop.load(Ordering::SeqCst), "TIME_CONNECTION_CLOSED");
|
||||
own_clock.complete(generation, &bytes)
|
||||
own_clock.complete(generation, &bytes)?;
|
||||
if let Some(slot) = own_receipt.as_ref().filter(|s| s.get().is_none()) {
|
||||
let hash = format!("{:x}", Sha256::digest(&bytes));
|
||||
let _ = slot.set(VerifiedTimeSample::new(request, hash));
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = own_clock.close_generation(generation);
|
||||
}
|
||||
tokio::time::sleep(if result.is_ok() {
|
||||
Duration::from_millis(20)
|
||||
} else {
|
||||
Duration::from_millis(500)
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(mode.interval(result.is_ok())).await;
|
||||
}
|
||||
let _ = own_clock.close_generation(generation);
|
||||
}));
|
||||
@@ -515,18 +552,20 @@ impl Agent {
|
||||
!helper_stop.load(Ordering::SeqCst),
|
||||
"TIME_CONNECTION_CLOSED"
|
||||
);
|
||||
time_helper.time_complete(generation, bytes).await
|
||||
let pending = helper_receipt.as_ref().filter(|s| s.get().is_none());
|
||||
let report =
|
||||
pending.map(|slot| (slot, format!("{:x}", Sha256::digest(&bytes))));
|
||||
time_helper.time_complete(generation, bytes).await?;
|
||||
if let Some((slot, hash)) = report {
|
||||
let _ = slot.set(VerifiedTimeSample::new(request, hash));
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = time_helper.time_close(generation).await;
|
||||
}
|
||||
tokio::time::sleep(if result.is_ok() {
|
||||
Duration::from_millis(20)
|
||||
} else {
|
||||
Duration::from_millis(500)
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(mode.interval(result.is_ok())).await;
|
||||
}
|
||||
let _ = time_helper.time_close(generation).await;
|
||||
}));
|
||||
@@ -537,6 +576,7 @@ impl Agent {
|
||||
clock,
|
||||
helper,
|
||||
tasks,
|
||||
samples,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -1216,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 {
|
||||
@@ -1232,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={}",
|
||||
@@ -1503,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(
|
||||
@@ -1521,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,
|
||||
@@ -1554,7 +1583,9 @@ impl Agent {
|
||||
);
|
||||
self.clock = self.clock.for_generation(generation);
|
||||
#[cfg(feature = "system-helper")]
|
||||
self.start_time_refresh(generation, &identity)?;
|
||||
if self.config.enable_jobs {
|
||||
self.start_time_refresh(generation, &identity)?;
|
||||
}
|
||||
self.queue_inventory(generation)?;
|
||||
self.queue_update_observation(generation)?;
|
||||
self.replay(&channel, generation).await?;
|
||||
@@ -1571,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));
|
||||
@@ -1657,22 +1687,16 @@ 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
|
||||
&& self.time_refresh.is_none()
|
||||
&& self.start_time_refresh(generation, &identity).is_err()
|
||||
{
|
||||
// An absent or unreadable profile must never take passive
|
||||
// inventory offline. Retry setup at the next heartbeat.
|
||||
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
|
||||
}
|
||||
let payload = Payload::Heartbeat(Heartbeat {
|
||||
instance_id: self.instance.clone(),
|
||||
uptime_seconds: self.started.elapsed().as_secs(),
|
||||
@@ -1689,6 +1713,14 @@ impl Agent {
|
||||
)?;
|
||||
channel.poll(poll).await?;
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
if let Some(refresh) = &mut self.time_refresh {
|
||||
let state = &self.config.state_directory;
|
||||
refresh.samples.retain(|slot| {
|
||||
slot.get()
|
||||
.is_none_or(|sample| sample.persist(state).is_err())
|
||||
});
|
||||
}
|
||||
heartbeat = Instant::now();
|
||||
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
|
||||
}
|
||||
@@ -1707,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();
|
||||
@@ -1781,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};
|
||||
@@ -1795,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,
|
||||
|
||||
@@ -10,6 +10,29 @@ use uuid::Uuid;
|
||||
const SECOND_NS: u64 = 1_000_000_000;
|
||||
const MAX_BASE_ERROR_NS: u64 = 10_000_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SamplingMode {
|
||||
Passive,
|
||||
Jobs,
|
||||
}
|
||||
impl SamplingMode {
|
||||
pub fn configured(jobs: bool, profile: &std::path::Path) -> std::io::Result<Option<Self>> {
|
||||
if jobs {
|
||||
return Ok(Some(Self::Jobs));
|
||||
}
|
||||
Ok(profile.try_exists()?.then_some(Self::Passive))
|
||||
}
|
||||
|
||||
pub fn interval(self, verified: bool) -> std::time::Duration {
|
||||
use std::time::Duration;
|
||||
match (self, verified) {
|
||||
(Self::Passive, _) => Duration::from_secs(30),
|
||||
(Self::Jobs, true) => Duration::from_millis(20),
|
||||
(Self::Jobs, false) => Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
|
||||
fn decode(value: &str) -> Result<[u8; 32]> {
|
||||
ensure!(
|
||||
@@ -1137,6 +1160,30 @@ pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClo
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn passive_sampling_requires_a_profile_and_uses_heartbeat_cadence() {
|
||||
let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let profile = dir.join("time-attestation.json");
|
||||
assert_eq!(SamplingMode::configured(false, &profile).unwrap(), None);
|
||||
assert_eq!(
|
||||
SamplingMode::configured(true, &profile).unwrap(),
|
||||
Some(SamplingMode::Jobs)
|
||||
);
|
||||
std::fs::write(&profile, b"{}").unwrap();
|
||||
assert_eq!(
|
||||
SamplingMode::configured(false, &profile).unwrap(),
|
||||
Some(SamplingMode::Passive)
|
||||
);
|
||||
for verified in [false, true] {
|
||||
assert_eq!(
|
||||
SamplingMode::Passive.interval(verified),
|
||||
std::time::Duration::from_secs(30)
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
fn sample(ns: u64) -> Sample {
|
||||
Sample {
|
||||
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
|
||||
|
||||
@@ -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
|
||||
== [
|
||||
|
||||
@@ -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,697 +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,
|
||||
};
|
||||
#[test]
|
||||
fn private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe() {
|
||||
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() {
|
||||
// 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,
|
||||
|
||||
@@ -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,189 +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=None
|
||||
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)
|
||||
@@ -1,102 +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=None
|
||||
DEPLOYMENT_PATH='/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/result.json'
|
||||
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/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,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.
|
||||
@@ -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,34 +1,5 @@
|
||||
# Übergabe — Linux-MVP abgeschlossen, Windows wird fortgesetzt
|
||||
|
||||
**15. November 2026.** Der permanente Server betreibt das neue Zeit-Gateway. Migration 15, TLS und Historienvergleich sind abgenommen. Der nächste Windows-Nachweis ist der signierte Abruf mit der Geräteidentität. [Bereitstellungsbeleg](server-time-gateway-deploy.md)
|
||||
|
||||
**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,45 +1,5 @@
|
||||
# Tatsächlicher Implementierungsstand
|
||||
|
||||
## 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,7 +10,6 @@ Pfad bleiben dort sofort relevant.
|
||||
|
||||
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
||||
| --- | --- | --- |
|
||||
| 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,112 +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` |
|
||||
@@ -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.
|
||||
+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. | Zertifikatsrotation und Widerruf noch getrennt auf Windows abnehmen. |
|
||||
| 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. Echter Chronyprovider, einmaliger genehmigter Neustart/Pin, Brokerstart und zwei echte Ed25519-Signaturen samt Container-PID0/Root-Deny bestanden. | Sichere W32Time-Dienstidentitätsbindung erwies sich auf dieser VM als nicht qualifizierbar. Genehmigte Alternative löst den Entwurfsblocker; HTTPS/mTLS-Zeitroute, neue Paarinstallation, geschützte öffentliche Zeitkonfiguration und zwei unabhängig bereite Windowsrollen bleiben native Integrationsarbeit. Keine erfundene Timerkalibrierung. |
|
||||
| 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. | 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: [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,43 +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.
|
||||
@@ -1,61 +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.
|
||||
Reference in New Issue
Block a user