diff --git a/Cargo.lock b/Cargo.lock index 7e7bdf8..a2ec760 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -70,6 +70,45 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -181,6 +220,15 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -468,6 +516,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "deranged" version = "0.5.9" @@ -1310,7 +1372,7 @@ dependencies = [ "js-sys", "p256", "p384", - "pem", + "pem 3.0.6", "rand 0.8.8", "rsa", "serde", @@ -1430,6 +1492,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "mio" version = "1.2.4" @@ -1441,6 +1509,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -1502,6 +1580,15 @@ dependencies = [ "libm", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1620,6 +1707,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -1913,6 +2010,20 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem 4.0.0", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2101,6 +2212,32 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-agent-windows" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "fs2", + "futures-util", + "prost", + "rand 0.9.5", + "rcgen", + "reqwest", + "rmm-domain", + "rmm-protocol", + "rusqlite", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "sha2 0.10.9", + "tokio", + "tokio-tungstenite 0.28.0", + "uuid", + "windows-sys 0.61.2", +] + [[package]] name = "rmm-domain" version = "0.1.0" @@ -2254,6 +2391,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2835,6 +2981,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -3618,6 +3775,34 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yoke" version = "0.8.4" @@ -3638,7 +3823,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -3679,7 +3864,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a86937c..dec2728 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" exclude = ["crates/oidc-auth"] -members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent", "crates/privileged-helper"] +members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-windows", "crates/agent", "crates/privileged-helper"] [workspace.package] version = "0.1.0" diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml new file mode 100644 index 0000000..1697c38 --- /dev/null +++ b/crates/agent-windows/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "rmm-agent-windows" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +chrono.workspace = true +futures-util.workspace = true +prost.workspace = true +rand.workspace = true +reqwest.workspace = true +rustls.workspace = true +rustls-pemfile.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +tokio.workspace = true +tokio-tungstenite.workspace = true +uuid.workspace = true +rmm-domain = { path = "../domain" } +rmm-protocol = { path = "../protocol" } +rusqlite = { version = "0.32.1", features = ["bundled"] } +fs2 = "0.4.3" +rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] } diff --git a/crates/agent-windows/src/journal.rs b/crates/agent-windows/src/journal.rs new file mode 100644 index 0000000..6e3c02e --- /dev/null +++ b/crates/agent-windows/src/journal.rs @@ -0,0 +1,138 @@ +use anyhow::{Result, ensure}; +use fs2::FileExt; +use prost::Message; +use rmm_protocol::Envelope; +use rusqlite::{Connection, OptionalExtension, params}; +use std::{fs::OpenOptions, path::Path}; + +pub struct Journal { + db: Connection, + _lock: std::fs::File, +} +impl Journal { + pub fn open(directory: &Path) -> Result { + ensure!(directory.is_dir(), "STATE_DIRECTORY_REQUIRED"); + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(directory.join("agent.lock"))?; + lock.try_lock_exclusive()?; + let db = Connection::open(directory.join("telemetry.sqlite"))?; + db.execute_batch( + "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; + CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL); + INSERT OR IGNORE INTO metadata VALUES('sequence',0); + CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);", + )?; + ensure!( + db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok", + "JOURNAL_INTEGRITY" + ); + Ok(Self { db, _lock: lock }) + } + pub fn next_sequence(&mut self) -> Result { + let tx = self.db.transaction()?; + let sequence: i64 = + tx.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| { + r.get(0) + })?; + let next = sequence + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?; + tx.execute("UPDATE metadata SET value=?1 WHERE key='sequence'", [next])?; + tx.commit()?; + Ok(u64::try_from(next)?) + } + pub fn save(&self, envelope: &Envelope) -> Result<()> { + // This slice never deletes a durable event to make room for telemetry. + // At the fixed cap it stops collecting until concrete ACKs release room. + ensure!(self.count()? < 8, "TELEMETRY_BACKPRESSURE"); + ensure!( + matches!( + envelope.payload, + Some(rmm_protocol::Payload::InventorySnapshot(_)) + ), + "PASSIVE_INVENTORY_ONLY" + ); + let bytes = envelope.encode_to_vec(); + ensure!(bytes.len() <= 512 * 1024, "TELEMETRY_LIMIT"); + self.db.execute( + "INSERT INTO events(id,payload) VALUES(?1,?2)", + params![envelope.message_id, bytes], + )?; + Ok(()) + } + pub fn events(&self) -> Result> { + let mut q = self + .db + .prepare("SELECT payload FROM events ORDER BY rowid")?; + q.query_map([], |r| r.get::<_, Vec>(0))? + .map(|v| Ok(Envelope::decode(v?.as_slice())?)) + .collect() + } + pub fn count(&self) -> Result { + Ok(self + .db + .query_row("SELECT count(*) FROM events", [], |r| r.get(0))?) + } + pub fn ack(&self, message_id: &str) -> Result<()> { + // Unknown IDs have no effect. An HTTP status never calls this function. + self.db + .execute("DELETE FROM events WHERE id=?1", [message_id])?; + Ok(()) + } + pub fn pin_identity(&self, id: &str) -> Result<()> { + self.db + .execute_batch("CREATE TABLE IF NOT EXISTS identity(agent TEXT PRIMARY KEY)")?; + let old: Option = self + .db + .query_row("SELECT agent FROM identity", [], |r| r.get(0)) + .optional()?; + if let Some(old) = old { + ensure!(old == id, "JOURNAL_IDENTITY_MISMATCH"); + } else { + self.db.execute("INSERT INTO identity VALUES(?1)", [id])?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn durable_reopen_ack_identity_and_single_process() { + let directory = + std::env::temp_dir().join(format!("rmm-windows-journal-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&directory).unwrap(); + let mut j = Journal::open(&directory).unwrap(); + assert!(Journal::open(&directory).is_err()); + j.pin_identity("a").unwrap(); + assert!(j.pin_identity("b").is_err()); + let first = j.next_sequence().unwrap(); + let e = Envelope { + message_id: uuid::Uuid::new_v4().to_string(), + sequence: first, + payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())), + ..Default::default() + }; + j.save(&e).unwrap(); + drop(j); + let mut j = Journal::open(&directory).unwrap(); + assert!(j.next_sequence().unwrap() > first); + assert_eq!(j.events().unwrap()[0].message_id, e.message_id); + j.ack("unrelated").unwrap(); + assert_eq!(j.count().unwrap(), 1); + j.ack(&e.message_id).unwrap(); + assert_eq!(j.count().unwrap(), 0); + let heartbeat = Envelope { + payload: Some(rmm_protocol::Payload::Heartbeat(Default::default())), + ..Default::default() + }; + assert!(j.save(&heartbeat).is_err()); + drop(j); + std::fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs new file mode 100644 index 0000000..77d6a0c --- /dev/null +++ b/crates/agent-windows/src/lib.rs @@ -0,0 +1,10 @@ +//! First Windows slice: passive observations and durable telemetry only. +//! No executor, startgrant consumer or privileged helper is advertised. +pub mod journal; +#[cfg(windows)] +pub mod native; +#[cfg(windows)] +pub mod service; + +pub const SERVICE_NAME: &str = "RmmDiscoveryWindows"; +pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"]; diff --git a/crates/agent-windows/src/main.rs b/crates/agent-windows/src/main.rs new file mode 100644 index 0000000..c0f0521 --- /dev/null +++ b/crates/agent-windows/src/main.rs @@ -0,0 +1,32 @@ +#[cfg(windows)] +#[path = "../../agent/src/https_channel.rs"] +mod https_channel; +#[cfg(windows)] +mod runtime; +#[cfg(windows)] +#[path = "../../agent/src/transport.rs"] +mod transport; +#[cfg(windows)] +#[path = "../../agent/src/wire_channel.rs"] +mod wire_channel; +#[cfg(windows)] +mod certificate_rotation { + // 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, + pub private_key_pem: Vec, + } +} +#[cfg(windows)] +fn main() { + if runtime::main().is_err() { + eprintln!("Windows passive agent stopped: INITIALIZATION_OR_TRANSPORT_FAILURE"); + std::process::exit(1); + } +} +#[cfg(not(windows))] +fn main() { + eprintln!("This binary requires native Windows."); + std::process::exit(1); +} diff --git a/crates/agent-windows/src/native.rs b/crates/agent-windows/src/native.rs new file mode 100644 index 0000000..97d956a --- /dev/null +++ b/crates/agent-windows/src/native.rs @@ -0,0 +1,253 @@ +//! Read-only Windows APIs. Boot identity comes from Win32_OperatingSystem's +//! LastBootUpTime, never from the lifetime of this agent process. +use anyhow::{Context, Result, ensure}; +use chrono::Utc; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration}; +use windows_sys::Win32::{ + Foundation::LocalFree, + Security::{ + self, ACCESS_ALLOWED_ACE, ACL, + Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT}, + DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, + }, + Storage::FileSystem::{FILE_ATTRIBUTE_REPARSE_POINT, GetDiskFreeSpaceExW}, + System::{Registry::*, SystemInformation::*}, +}; +pub fn wide(value: impl AsRef) -> Vec { + value.as_ref().encode_wide().chain(Some(0)).collect() +} +fn sid_string(sid: *mut c_void) -> Result { + let mut text = ptr::null_mut(); + // SAFETY: SID was returned by the Windows security API; API allocates text. + ensure!( + unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0, + "SID_CONVERSION" + ); + let mut len = 0; + unsafe { + while *text.add(len) != 0 { + len += 1; + } + } + let result = String::from_utf16(unsafe { std::slice::from_raw_parts(text, len) })?; + unsafe { + LocalFree(text.cast()); + } + Ok(result) +} +pub fn service_sid() -> Result { + let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME)); + let mut sid_len = 0; + let mut domain_len = 0; + let mut use_type = 0; + unsafe { + Security::LookupAccountNameW( + ptr::null(), + account.as_ptr(), + ptr::null_mut(), + &mut sid_len, + ptr::null_mut(), + &mut domain_len, + &mut use_type, + ); + } + ensure!( + sid_len > 0 && sid_len <= 256 && domain_len <= 256, + "SERVICE_SID_REQUIRED" + ); + let mut sid = vec![0u8; sid_len as usize]; + let mut domain = vec![0u16; domain_len as usize]; + ensure!( + unsafe { + Security::LookupAccountNameW( + ptr::null(), + account.as_ptr(), + sid.as_mut_ptr().cast(), + &mut sid_len, + domain.as_mut_ptr(), + &mut domain_len, + &mut use_type, + ) + } != 0, + "SERVICE_SID_LOOKUP" + ); + sid_string(sid.as_mut_ptr().cast()) +} +pub fn private_path(path: &Path, directory: bool) -> Result<()> { + use std::os::windows::fs::MetadataExt; + let metadata = std::fs::symlink_metadata(path)?; + ensure!( + metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 + && metadata.is_dir() == directory, + "PRIVATE_PATH_TYPE" + ); + let allowed = [ + "S-1-5-18".to_owned(), + "S-1-5-32-544".to_owned(), + service_sid()?, + ]; + let name = wide(path); + let mut owner = ptr::null_mut(); + let mut dacl: *mut ACL = ptr::null_mut(); + let mut descriptor = ptr::null_mut(); + // SAFETY: API writes pointers into one allocated descriptor, released below. + let status = unsafe { + GetNamedSecurityInfoW( + name.as_ptr(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &mut owner, + ptr::null_mut(), + &mut dacl, + ptr::null_mut(), + &mut descriptor, + ) + }; + ensure!(status == 0, "PRIVATE_PATH_SECURITY"); + let result = (|| { + ensure!( + !owner.is_null() && !dacl.is_null(), + "PRIVATE_PATH_NULL_DACL" + ); + let owner = sid_string(owner)?; + ensure!( + allowed.contains(&owner) || (!directory && owner == "S-1-5-19"), + "PRIVATE_PATH_OWNER" + ); + ensure!(unsafe { (*dacl).AceCount } > 0, "PRIVATE_PATH_EMPTY_DACL"); + for n in 0..unsafe { (*dacl).AceCount } { + let mut ace = ptr::null_mut(); + ensure!( + unsafe { Security::GetAce(dacl, u32::from(n), &mut ace) } != 0, + "PRIVATE_PATH_ACE" + ); + let ace = unsafe { &*ace.cast::() }; + ensure!( + ace.Header.AceType == 0 + && usize::from(ace.Header.AceSize) >= std::mem::size_of::(), + "PRIVATE_PATH_ACE_TYPE" + ); + let sid = ptr::addr_of!(ace.SidStart).cast_mut().cast(); + ensure!( + allowed.contains(&sid_string(sid)?), + "PRIVATE_PATH_BROAD_ACL" + ); + } + Ok(()) + })(); + unsafe { + LocalFree(descriptor.cast()); + } + result +} +fn registry_string(name: &str) -> Result { + let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); + let name = wide(name); + let mut bytes = vec![0u16; 2048]; + let mut size = (bytes.len() * 2) as u32; + ensure!( + unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + name.as_ptr(), + RRF_RT_REG_SZ, + ptr::null_mut(), + bytes.as_mut_ptr().cast(), + &mut size, + ) + } == 0, + "OS_REGISTRY" + ); + ensure!( + size >= 2 && size as usize <= bytes.len() * 2, + "OS_REGISTRY_SIZE" + ); + Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?) +} +pub fn snapshot() -> Result { + let started = Utc::now(); + let mut hostname = vec![0u16; 256]; + let mut len = hostname.len() as u32; + ensure!( + unsafe { GetComputerNameExW(ComputerNameDnsHostname, hostname.as_mut_ptr(), &mut len) } + != 0, + "HOSTNAME_QUERY" + ); + let hostname = String::from_utf16(&hostname[..len as usize])?; + let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\"); + let mut available = 0; + let mut total = 0; + let mut free = 0; + ensure!( + unsafe { GetDiskFreeSpaceExW(volume.as_ptr(), &mut available, &mut total, &mut free) } != 0, + "VOLUME_QUERY" + ); + ensure!(total > 0 && available <= total, "VOLUME_VALUES"); + let product = registry_string("ProductName")?; + let display = registry_string("DisplayVersion")?; + let build = registry_string("CurrentBuildNumber")?; + let os = format!("{product}; DisplayVersion={display}; Build={build}"); + let completed = Utc::now(); + Ok( + json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null, + "collection_started_at":started,"collection_completed_at":completed, + "observations":[ + {"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}}, + {"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}}, + {"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null} + ]}), + ) +} +pub async fn boot_id() -> Result { + // Fixed passive query only. Never interpolates a job or caller-supplied code. + // Avoid Win32_Product: it can cause MSI consistency checks and repairs. + let executable = Path::new(&std::env::var("SystemRoot")?) + .join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let mut command = tokio::process::Command::new(executable); + command.args(["-NoLogo","-NoProfile","-NonInteractive","-Command","$ErrorActionPreference='Stop'; (Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)"]); + command.kill_on_drop(true); + let output = tokio::time::timeout(Duration::from_secs(15), command.output()).await??; + ensure!( + output.status.success() && output.stdout.len() <= 128 && output.stderr.is_empty(), + "BOOT_TIME_QUERY" + ); + let text = std::str::from_utf8(&output.stdout)?.trim(); + ensure!( + (17..=19).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit()), + "BOOT_TIME_FORMAT" + ); + let mut bytes: [u8; 16] = Sha256::digest(format!("rmm.windows.boot.cim.ticks.v1:{text}")) + .as_slice()[..16] + .try_into()?; + bytes[6] = (bytes[6] & 15) | 0x80; + bytes[8] = (bytes[8] & 63) | 0x80; + Ok(uuid::Uuid::from_bytes(bytes).to_string()) +} + +#[cfg(test)] +mod tests { + #[test] + fn native_inventory_has_real_windows_sources_and_no_fake_inodes() { + let v = super::snapshot().unwrap(); + assert!(v["root_total_bytes"].as_u64().unwrap() > 0); + assert!(v["root_available_inodes"].is_null()); + assert!(!v["hostname"].as_str().unwrap().is_empty()); + assert!( + v["observations"] + .as_array() + .unwrap() + .iter() + .all(|o| o["scope"].as_str().unwrap().starts_with("windows.")) + ); + } + #[tokio::test] + async fn boot_identity_survives_independent_native_queries() { + assert_eq!( + super::boot_id().await.unwrap(), + super::boot_id().await.unwrap() + ); + } +} diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs new file mode 100644 index 0000000..869f753 --- /dev/null +++ b/crates/agent-windows/src/runtime.rs @@ -0,0 +1,343 @@ +use anyhow::{Result, ensure}; +use chrono::Utc; +use rcgen::{CertificateParams, DnType, KeyPair}; +use rmm_agent_windows::{CAPABILITIES, journal::Journal, native}; +use rmm_protocol::*; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::{ + fs, + path::{Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, + time::{Duration, Instant}, +}; +use uuid::Uuid; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Config { + server_name: String, + connect_address: std::net::SocketAddr, + ca_file: PathBuf, + state_directory: PathBuf, + enrollment_token_file: PathBuf, + transport: String, +} +fn create_private(path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + file.write_all(bytes)?; + file.sync_all()?; + native::private_path(path, false) +} +fn protected_read(path: &Path, max: usize) -> Result> { + native::private_path(path, false)?; + ensure!( + fs::metadata(path)?.len() <= max as u64, + "PRIVATE_FILE_LIMIT" + ); + Ok(fs::read(path)?) +} +async fn enrollment(config: &Config, ca: &[u8]) -> Result { + let state = &config.state_directory; + let identity = state.join("identity.json"); + if identity.try_exists()? { + return Ok(serde_json::from_slice(&protected_read(&identity, 32768)?)?); + } + let key_path = state.join("device.key"); + let key = if key_path.try_exists()? { + KeyPair::from_pem(std::str::from_utf8(&protected_read(&key_path, 16384)?)?)? + } else { + let key = KeyPair::generate()?; + create_private(&key_path, key.serialize_pem().as_bytes())?; + key + }; + let mut parameters = CertificateParams::default(); + parameters + .distinguished_name + .push(DnType::CommonName, "new-windows-device"); + let csr = parameters.serialize_request(&key)?.pem()?; + let token = String::from_utf8(protected_read(&config.enrollment_token_file, 128)?)? + .trim() + .to_owned(); + ensure!( + token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()), + "ENROLLMENT_TOKEN_FORMAT" + ); + let client = reqwest::Client::builder() + .https_only(true) + .tls_built_in_root_certs(false) + .add_root_certificate(reqwest::Certificate::from_pem(ca)?) + .resolve(&config.server_name, config.connect_address) + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(20)) + .build()?; + let response = client + .post(format!( + "https://{}:{}/agent/v1/enroll", + config.server_name, + config.connect_address.port() + )) + .json(&EnrollmentRequest { + token, + csr_pem: csr, + }) + .send() + .await?; + let bytes = crate::https_channel::bounded_body(response, 32768, "application/json").await?; + let identity: EnrollmentResponse = serde_json::from_slice(&bytes)?; + Uuid::parse_str(&identity.agent_id)?; + Uuid::parse_str(&identity.asset_id)?; + // The server consumes the token once; a lost response is an explicit recovery + // gate. No automatic re-enrollment or replacement identity is attempted. + create_private( + &state.join("device.pem"), + identity.certificate_pem.as_bytes(), + )?; + create_private( + &state.join("identity.json"), + &serde_json::to_vec(&identity)?, + )?; + fs::remove_file(&config.enrollment_token_file)?; + Ok(identity) +} +struct Agent { + config: Config, + identity: EnrollmentResponse, + ca: Vec, + journal: Journal, + boot: String, + instance: String, + started: Instant, +} +impl Agent { + fn envelope(&mut self, generation: u64, payload: Payload) -> Result { + Ok(Envelope { + protocol_major: 1, + protocol_minor: 0, + message_id: Uuid::new_v4().to_string(), + agent_id: self.identity.agent_id.clone(), + enrollment_generation: 1, + connection_generation: generation, + boot_id: self.boot.clone(), + sequence: self.journal.next_sequence()?, + observed_at: Utc::now().timestamp_millis(), + payload: Some(payload), + }) + } + fn queue_inventory(&mut self, generation: u64) -> Result<()> { + if self.journal.count()? > 0 { + return Ok(()); + } + let data = serde_json::to_vec(&native::snapshot()?)?; + ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT"); + let envelope = self.envelope( + generation, + Payload::InventorySnapshot(InventorySnapshot { + snapshot_id: Uuid::new_v4().to_string(), + scope: "windows.base".into(), + schema_version: 1, + chunk_index: 0, + chunk_count: 1, + sha256: Sha256::digest(&data).to_vec(), + data, + completeness: "partial".into(), + }), + )?; + self.journal.save(&envelope) + } + async fn session(&mut self, stop: &AtomicBool) -> Result<()> { + let hello = self.envelope( + 0, + Payload::ClientHello(ClientHello { + agent_version: env!("CARGO_PKG_VERSION").into(), + capabilities: CAPABILITIES.iter().map(|v| v.to_string()).collect(), + }), + )?; + 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, + self.config.connect_address, + &self.ca, + &identity, + hello, + ) + .await?; + let reply = tokio::time::timeout(Duration::from_secs(20), channel.receive()).await??; + ensure!( + reply.agent_id == self.identity.agent_id + && reply.enrollment_generation == 1 + && reply.protocol_major == 1 + && reply.protocol_minor == 0, + "SERVER_HELLO_BINDING" + ); + let Some(Payload::ServerHello(server)) = reply.payload else { + anyhow::bail!("SERVER_HELLO_REQUIRED") + }; + let generation = server.connection_generation; + ensure!( + generation > 0 && server.max_message_bytes == rmm_domain::MAX_MESSAGE as u32, + "SERVER_LIMITS" + ); + self.queue_inventory(generation)?; + let mut replay = Instant::now() - Duration::from_secs(10); + let mut inventory = 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)); + while !stop.load(Ordering::SeqCst) { + tokio::select! { + _=tick.tick()=>{}, + message=channel.receive()=>{ + let message=message?; + ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==1 && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING"); + match message.payload { + Some(Payload::Ack(ack))=>self.journal.ack(&ack.message_id)?, + // There is deliberately no acceptance/start path. A stale + // or malicious offer cannot activate an unimplemented job. + Some(Payload::JobOffer(_)|Payload::ExecutionPermit(_))=>anyhow::bail!("UNSUPPORTED_EXECUTION_CAPABILITY"), + _=>anyhow::bail!("UNSUPPORTED_SERVER_MESSAGE") + } + } + } + if heartbeat.elapsed() >= heartbeat_after { + let payload = Payload::Heartbeat(Heartbeat { + instance_id: self.instance.clone(), + uptime_seconds: self.started.elapsed().as_secs(), + }); + let h = self.envelope(generation, payload)?; + channel.send(&h).await?; + if channel.uses_https() { + let poll = self.envelope( + generation, + Payload::Heartbeat(Heartbeat { + instance_id: self.instance.clone(), + uptime_seconds: self.started.elapsed().as_secs(), + }), + )?; + channel.poll(poll).await?; + } + heartbeat = Instant::now(); + heartbeat_after = Duration::from_millis(rand::random_range(27000..33000)); + } + if replay.elapsed() >= Duration::from_secs(5) { + for mut event in self.journal.events()? { + event.connection_generation = generation; + channel.send(&event).await?; + } + replay = Instant::now(); + } + if inventory.elapsed() >= Duration::from_secs(86400) { + self.queue_inventory(generation)?; + inventory = Instant::now(); + } + } + Ok(()) + } +} +fn service_run(stop: &'static AtomicBool) -> Result<()> { + let arguments: Vec = std::env::args().skip(1).collect(); + ensure!( + arguments.len() == 3 && arguments[0] == "--service" && arguments[1] == "--config", + "SERVICE_ARGUMENTS" + ); + let path = Path::new(&arguments[2]); + ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED"); + let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?; + native::private_path(&config.state_directory, true)?; + ensure!( + crate::https_channel::server_name()? == config.server_name, + "SERVER_NAME" + ); + let ca = protected_read(&config.ca_file, 32768)?; + for child in fs::read_dir(&config.state_directory)? { + let child = child?; + native::private_path(&child.path(), false)?; + } + let journal = Journal::open(&config.state_directory)?; + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .worker_threads(2) + .build()?; + runtime.block_on(async move { + let identity = enrollment(&config, &ca).await?; + journal.pin_identity(&identity.agent_id)?; + let boot = native::boot_id().await?; + let mut agent = Agent { + config, + identity, + ca, + journal, + boot, + instance: Uuid::new_v4().to_string(), + started: Instant::now(), + }; + let mut backoff = 1; + while !stop.load(Ordering::SeqCst) { + let start = Instant::now(); + let _ = agent.session(stop).await; + if start.elapsed() > Duration::from_secs(60) { + backoff = 1; + } + let delay = crate::https_channel::retry_delay(backoff); + backoff = (backoff + 1).min(6); + let until = Instant::now() + delay; + while !stop.load(Ordering::SeqCst) && Instant::now() < until { + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + Ok(()) + }) +} +pub fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + if args == ["--help"] { + println!( + "Development Windows passive service. --service --config ABSOLUTE_PATH. No job executor or approval bypass." + ); + return Ok(()); + } + if args == ["--native-probe"] { + let runtime = tokio::runtime::Runtime::new()?; + let boot = runtime.block_on(native::boot_id())?; + let inventory = native::snapshot()?; + println!( + "{}", + serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false}) + ); + return Ok(()); + } + ensure!( + args.first().map(String::as_str) == Some("--service"), + "UNKNOWN_ARGUMENT" + ); + ensure!( + args.len() == 3 && args[1] == "--config", + "SERVICE_ARGUMENTS" + ); + let config: Config = serde_json::from_slice(&protected_read(Path::new(&args[2]), 32768)?)?; + // Shared transport reads its one DNS identity. Set it before SCM dispatch + // creates its service thread and before any Tokio/collector threads exist. + unsafe { + std::env::set_var("RMM_SERVER_NAME", &config.server_name); + } + ensure!( + crate::https_channel::server_name()? == config.server_name, + "SERVER_NAME" + ); + rmm_agent_windows::service::dispatch(service_run) +} diff --git a/crates/agent-windows/src/service.rs b/crates/agent-windows/src/service.rs new file mode 100644 index 0000000..64b485c --- /dev/null +++ b/crates/agent-windows/src/service.rs @@ -0,0 +1,84 @@ +//! Native SCM lifecycle. This service has no privileged action endpoint. +use anyhow::{Result, ensure}; +use std::{ + ptr, + sync::{ + OnceLock, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; +use windows_sys::Win32::System::Services::*; +static STOP: AtomicBool = AtomicBool::new(false); +static HANDLE: AtomicUsize = AtomicUsize::new(0); +type Runner = fn(&'static AtomicBool) -> Result<()>; +static RUN: OnceLock = OnceLock::new(); +fn status(state: u32, exit: u32) { + let handle = HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE; + if handle.is_null() { + return; + } + let value = SERVICE_STATUS { + dwServiceType: SERVICE_WIN32_OWN_PROCESS, + dwCurrentState: state, + dwControlsAccepted: if state == SERVICE_RUNNING { + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN + } else { + 0 + }, + dwWin32ExitCode: exit, + dwServiceSpecificExitCode: 0, + dwCheckPoint: 0, + dwWaitHint: if state == SERVICE_STOP_PENDING { + 15000 + } else { + 0 + }, + }; + unsafe { + SetServiceStatus(handle, &value); + } +} +unsafe extern "system" fn control( + code: u32, + _event: u32, + _data: *mut std::ffi::c_void, + _context: *mut std::ffi::c_void, +) -> u32 { + if code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN { + STOP.store(true, Ordering::SeqCst); + status(SERVICE_STOP_PENDING, 0); + } + 0 +} +unsafe extern "system" fn service_main(_count: u32, _args: *mut *mut u16) { + let name = crate::native::wide(crate::SERVICE_NAME); + let handle = + unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) }; + if handle.is_null() { + return; + } + HANDLE.store(handle as usize, Ordering::SeqCst); + status(SERVICE_RUNNING, 0); + let result = RUN.get().expect("SCM runner initialized")(&STOP); + // Error details never enter the Windows event log: paths may contain secrets. + status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 }); +} +pub fn dispatch(run: Runner) -> Result<()> { + ensure!(RUN.set(run).is_ok(), "SCM_ALREADY_INITIALIZED"); + let mut name = crate::native::wide(crate::SERVICE_NAME); + let table = [ + SERVICE_TABLE_ENTRYW { + lpServiceName: name.as_mut_ptr(), + lpServiceProc: Some(service_main), + }, + SERVICE_TABLE_ENTRYW { + lpServiceName: ptr::null_mut(), + lpServiceProc: None, + }, + ]; + ensure!( + unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0, + "SCM_DISPATCH_FAILED" + ); + Ok(()) +} diff --git a/deploy/browser/cloud_apt_acceptance.cjs b/deploy/browser/cloud_apt_acceptance.cjs index 0c73bc9..40769d7 100644 --- a/deploy/browser/cloud_apt_acceptance.cjs +++ b/deploy/browser/cloud_apt_acceptance.cjs @@ -5,7 +5,7 @@ const crypto = require('node:crypto'); const { isDeepStrictEqual: equal } = require('node:util'); const { chromium } = require('../../web/node_modules/playwright'); const root = path.resolve(__dirname, '../..'); -const assert = v => { if (!v) throw new Error('APT UI contract mismatch'); }; +const assert = v => { if (!v) { const error = new Error('APT UI contract mismatch'); Error.captureStackTrace(error, assert); throw error; } }; function readPrivate(file) { const s = fs.lstatSync(file); assert(s.isFile() && !s.isSymbolicLink() && s.uid === process.getuid() && (s.mode & 0o777) === 0o600 && s.size < 1048576); @@ -80,7 +80,12 @@ function checkAction(p, expected) { assert(pending.approval_state === 'pending_approval' && pending.job_count === 0 && pending.execution_state === null); await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen' }).click(); const plan = JSON.parse(await detail.locator('pre').innerText()); - assert(equal(plan, expected.plan) && plan.jobs.length === 1 && plan.resolved_targets.length === 1); + // Submission changes request metadata, never the fixed plan bytes/jobs. + // Require the new pending state explicitly and compare EVERY other field. + const { approval_state: currentState, ...currentPlan } = plan; + const { approval_state: preparedState, ...preparedPlan } = expected.plan; + assert(currentState === 'pending_approval' && preparedState === null); + assert(equal(currentPlan, preparedPlan) && plan.jobs.length === 1 && plan.resolved_targets.length === 1); assert(crypto.createHash('sha256').update(Buffer.from(plan.plan_payload_bytes)).digest('hex') === plan.plan_hash); const p = plan.jobs[0].payload; checkAction(p, expected); assert(p.agent_id === expected.agent_id && p.asset_id === expected.asset_id && p.tenant_id === expected.tenant_id && Date.parse(p.start_before) > Date.now()); diff --git a/deploy/cloud_apt_retry.py b/deploy/cloud_apt_retry.py index 8b38a16..719c7ca 100644 --- a/deploy/cloud_apt_retry.py +++ b/deploy/cloud_apt_retry.py @@ -58,6 +58,40 @@ def upgrade_agent(payload): return dict(binary_sha256=payload['sha256'], state_preserved_before_start=True, package_effects=False, backup=str(backup)) +def stored_attempt_evidence(payload): + """Read only already persisted evidence; no live collector/package command.""" + import sqlite3 + import re + base = Path('/var/lib/rmm-apt-transaction'); active = base/'active' + context = json.loads((active/'context.json').read_text()) + require(context['job_id'] == payload['job_id'] and context['attempt_id'] == payload['attempt_id'], 'exact stored attempt required') + result = dict(files={}, records={}, context=context) + for name in ('hook-armed.json','native-prechecks.json','sandbox-ready.json','sandbox-result.json','launch.json'): + path = active/name + result['files'][name] = dict(exists=path.exists(), symlink=path.is_symlink()) + if path.is_file() and not path.is_symlink(): result['records'][name] = json.loads(path.read_text()) + for name in ('bootstrap-attempt-rmm-apt-fixture-install-1.0.json','bootstrap-retry-rmm-apt-fixture-install-1.0.json', + 'acceptance-rmm-apt-fixture-install-1.0.json','pending-acceptance-rmm-apt-fixture-install-1.0.json'): + path = base/name + result['files'][name] = dict(exists=path.exists(), symlink=path.is_symlink(), sha256=hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None) + with sqlite3.connect('file:/var/lib/rmm-helper/consumption.sqlite?mode=ro', uri=True) as db: + row = db.execute('SELECT c.result,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?', (context['grant_id'],)).fetchone() + result['ledger'] = dict(result=json.loads(row[0]) if row[0] else None, outcome=json.loads(row[1]) if row[1] else None, + consumed=db.execute('SELECT count(*) FROM consumed').fetchone()[0], unresolved=db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0]) + result['logs'] = {} + for name in ('dpkg.log','term.log','history.log'): + path = base/'log'/name + if path.is_file() and not path.is_symlink(): + raw = path.read_bytes(); require(len(raw) <= 1024*1024, 'bounded stored log') + text = raw.decode('utf-8', errors='replace') + result['logs'][name] = dict(sha256=hashlib.sha256(raw).hexdigest(), size=len(raw), + fixture_states=re.findall(r'\bstatus (not-installed|half-installed|unpacked|half-configured|installed|triggers-pending|triggers-awaited) rmm-mvp-test(?::all)? (1\.[01])\b', text), + configure_record=bool(re.search(r'\bconfigure rmm-mvp-test(?::all)?\b', text)), + setup_message='Setting up rmm-mvp-test (1.0)' in text, + dpkg_error='dpkg: error' in text) + return result + + def switch_endpoint(payload): import sqlite3 os.umask(0o077) diff --git a/deploy/windows/CLIENT.md b/deploy/windows/CLIENT.md new file mode 100644 index 0000000..a7beee4 --- /dev/null +++ b/deploy/windows/CLIENT.md @@ -0,0 +1,65 @@ +# Windows-Client: erster nativer Entwicklungsstand + +Stand 2026-11-13, Spezifikation 1.9. 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`. + +## Tatsächlich nachgewiesen + +`rmm-agent-windows` als eigene Plattform-Crate mit gemeinsamen Domain-/Protobuf- +Verträgen und direkt wiederverwendeten WSS-/HTTPS-/TLS-Modulen des Linux-Agenten. +Isolierter Docker-Crossbuild mit Rust 1.99.1 für `x86_64-pc-windows-gnu`: +Debug und Release erfolgreich; Windows-target Clippy über alle Targets mit +`-D warnings` erfolgreich. Zwei gezielte Domain-Tests prüfen die unveränderte +Linux-Validierung, Windows ohne erfundene Inodes und abgewiesene Plattformmischung. +Das sind ergänzende lokale Prüfungen, keine nativen Windows-Dienstnachweise. + +Releaseartefakt SHA256 +`31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37` +auf der tatsächlichen Windows-11-Pro-VM (Version 10.0.26300, x64) gestartet: +`--native-probe` erfolgreich. Hostname und Systemvolume tatsächlich über Win32 +lesbar; Bootkennung aus `Win32_OperatingSystem.LastBootUpTime` abgeleitet statt +bei jedem Agentstart neu erzeugt. Inodes ausdrücklich `null`/nicht anwendbar. +Keine Schlüssel oder realen Hostnamen in der veröffentlichten Probeausgabe. + +Binärtransfer über bestehendes, hostkeygeprüftes SFTP mit SHA256-Nachprüfung. +Große PowerShell-Console-JSON-Eingaben waren als Bootstraptransport ungeeignet +(Timeout/Console-Reader-Ausnahme); deshalb nur kleine zeilenbegrenzte Metadaten +über stdin. SSH-/Hostkeyprüfung und Reverse-Portgrenzen bleiben unverändert. +Artefaktverzeichnisse werden nach Hash neu angelegt, keine vorhandene Identität +oder Historie gelöscht. Private Evidenz: `devstate/windows-client/`. + +## Implementiert, Dienst-/Online-Abnahme noch offen + +- Nativer SCM-Dienstlebenszyklus, vorgesehen als `LocalService` mit eigenem + Service-SID-Zugriff auf Zustand und ausschließlich lesbarem Programm/Config. +- Windows prüft Owner/DACL und verweigert Reparse-Points/breite ACLs. Geräteschlüssel + werden nur auf Windows erzeugt; Enrollment über CA- und namensgeprüftes TLS, + danach mTLS. Ein verlorener Enrollmentnachweis löst keinen Identitätsreset aus. +- SQLite mit FULL-Synchronisierung, Prozesssperre, monotoner persistenter Sequenz, + konkretem ACK und begrenzter Telemetriequeue. Kein Löschen für Platzgewinn. +- Separate `windows.base`-Beobachtungen mit Erhebungszeit/Quelle/Qualität; Server + bindet den Scope an die authentisierte Verbindung und deren Capability. + Geräte-API zeigt die gespeicherte Quelle statt eines festen Linuxlabels. +- Ausschließlich `windows.base/1` und `heartbeat/1` werden angeboten. + **Kein Jobexecutor, keine PowerShell-Jobfähigkeit, kein privilegierter Helper.** + Angebote/Startgrants werden verweigert. Es gibt keine Genehmigungsabkürzung. + +Dieser erste Entwicklungsbuild ist **unsigniert**. Kein produktiver signierter +Installer/MSVC-Supportnachweis, keine Zertifikatsrotations-/Widerrufs-/Proxy- oder +Windows-Paket-/Dienstaktionsabnahme. Native Testprogramme sowie die tatsächliche +SCM-/Enrollment-/mTLS-/Inventarstrecke sind zum Zeitpunkt dieses Abschnitts noch +offen. Ein erfolgreicher Crossbuild bzw. `--native-probe` ersetzt sie nicht. + +## Ausgeführte und geplante Befehle + +Tatsächlich ausgeführt: Docker-Build und gezielte Rust-Prüfungen oben sowie +`python3 deploy/windows/client_bootstrap.py upload-agent --artifact ` +und `python3 deploy/windows/client_bootstrap.py probe` gegen ausschließlich den +Windows-Gast. Keine RMM-Jobs oder Genehmigungen wurden dabei erzeugt. + +Geplant, noch nicht als bestanden behauptet: native Testprogramme und +`Install-PassiveClient.ps1` über `client_bootstrap.py install`, anschließend +zwei frische Heartbeats, korrekt zugeordnetes Inventar und Tenant-B-Verweigerung. +Installation ist create-only; bei Teilfehlern Zustand inspizieren und erhalten, +nicht blind neu enrollen oder den Bootstrap wiederholen. diff --git a/deploy/windows/Install-PassiveClient.ps1 b/deploy/windows/Install-PassiveClient.ps1 new file mode 100644 index 0000000..553319a --- /dev/null +++ b/deploy/windows/Install-PassiveClient.ps1 @@ -0,0 +1,83 @@ +# Development bootstrap only. No RMM jobs, privileged helper or execution bypass. +# Run through the pinned SSH transport as the bootstrap administrator. +$ErrorActionPreference = 'Stop' +$p = $global:RmmBootstrapPayload +if ($null -eq $p) { throw 'Bootstrap payload required through the pinned launcher' } +if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.token -notmatch '^[0-9a-f]{64}$') { throw 'Invalid bootstrap metadata' } +$serviceName = 'RmmDiscoveryWindows' +$application = 'C:\Program Files\RustDiscovery' +$root = 'C:\ProgramData\RustDiscovery' +$state = Join-Path $root 'state' +$source = 'C:\ProgramData\RustDiscoveryBootstrap\' + $p.sha256 + '\rmm-agent-windows.exe' +if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) { throw 'Service already exists: preserve identity and inspect instead of reinstalling' } +if ((Test-Path -LiteralPath $application) -or (Test-Path -LiteralPath $root)) { throw 'Existing client state must be preserved' } +if ((Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) { throw 'Artifact hash mismatch' } +$ca = [Convert]::FromBase64String($p.ca) +if ($ca.Length -lt 100 -or $ca.Length -gt 32768) { throw 'CA size' } +$administrators = New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544') +$system = New-Object Security.Principal.SecurityIdentifier('S-1-5-18') +function Protect-Directory([string]$Path, $ServiceSid, [string]$Rights) { + $acl = New-Object Security.AccessControl.DirectorySecurity + $acl.SetAccessRuleProtection($true, $false) + $acl.SetOwner($administrators) + foreach ($sid in @($administrators, $system)) { + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))) + } + if ($null -ne $ServiceSid) { + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($ServiceSid, $Rights, 'ContainerInherit,ObjectInherit', 'None', 'Allow'))) + } + Set-Acl -LiteralPath $Path -AclObject $acl +} +function Protect-ReadFile([string]$Path, $ServiceSid) { + $acl = New-Object Security.AccessControl.FileSecurity + $acl.SetAccessRuleProtection($true, $false) + $acl.SetOwner($administrators) + foreach ($sid in @($administrators, $system)) { + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow'))) + } + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($ServiceSid, 'ReadAndExecute', 'Allow'))) + Set-Acl -LiteralPath $Path -AclObject $acl +} +New-Item -ItemType Directory -Path $application | Out-Null +New-Item -ItemType Directory -Path $root | Out-Null +Protect-Directory $application $null 'ReadAndExecute' +Protect-Directory $root $null 'ReadAndExecute' +Copy-Item -LiteralPath $source -Destination (Join-Path $application 'rmm-agent-windows.exe') +$binary = '"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"' +$sc = Join-Path $env:WINDIR 'System32\sc.exe' +# New-Service passes the quoted image path directly to SCM, avoiding native +# PowerShell 5.1 command-line quoting of a path containing spaces. Keep it manual +# until the account has been narrowed; it is never started as LocalSystem. +New-Service -Name $serviceName -BinaryPathName $binary -StartupType Manual | Out-Null +& $sc config $serviceName start= auto obj= 'NT AUTHORITY\LocalService' | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'SCM service identity configuration failed' } +& $sc sidtype $serviceName unrestricted | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'SCM service SID configuration failed' } +$serviceSid = (New-Object Security.Principal.NTAccount('NT SERVICE', $serviceName)).Translate([Security.Principal.SecurityIdentifier]) +Protect-Directory $application $serviceSid 'ReadAndExecute' +Protect-Directory $root $serviceSid 'ReadAndExecute' +New-Item -ItemType Directory -Path $state | Out-Null +Protect-Directory $state $serviceSid 'Modify' +$caPath = Join-Path $root 'server-ca.pem' +[IO.File]::WriteAllBytes($caPath, $ca) +Protect-ReadFile $caPath $serviceSid +# Only this one-use token is writable by the service so it can remove the copy. +$tokenPath = Join-Path $state 'enrollment.token' +[IO.File]::WriteAllText($tokenPath, $p.token, (New-Object Text.UTF8Encoding($false))) +$address = @([Net.Dns]::GetHostAddresses('discovery.ease-technologies.de') | Where-Object {$_.AddressFamily -eq [Net.Sockets.AddressFamily]::InterNetwork})[0] +if ($null -eq $address) { throw 'Server DNS has no IPv4 address' } +$config = [ordered]@{ + server_name = 'discovery.ease-technologies.de' + connect_address = $address.ToString() + ':443' + ca_file = $caPath + state_directory = $state + enrollment_token_file = $tokenPath + transport = 'wss' +} +$configPath = Join-Path $root 'config.json' +[IO.File]::WriteAllText($configPath, ($config | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false))) +Protect-ReadFile $configPath $serviceSid +& $sc description $serviceName 'Rust Discovery development passive agent; no job executor' | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'Service description failed' } +Start-Service -Name $serviceName +[pscustomobject]@{installed=$true;service_name=$serviceName;service_identity='LocalService';service_sid=$serviceSid.Value;artifact_sha256=$p.sha256;no_job_executor=$true;no_reboot=$true} | ConvertTo-Json -Compress diff --git a/deploy/windows/client_bootstrap.py b/deploy/windows/client_bootstrap.py new file mode 100644 index 0000000..93565d3 --- /dev/null +++ b/deploy/windows/client_bootstrap.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Narrow SSH bootstrap for the Windows development guest. No RMM execution. + +Reads credentials only as protected JSON; all remote code is fixed here. +Private keys are generated by the Windows agent and never downloaded. +""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'deploy')) +import vm_mvp_acceptance as contract + +EVIDENCE = ROOT / 'devstate/windows-client' +REMOTE = r'C:\ProgramData\RustDiscoveryBootstrap' + + +def powershell(script, payload=None, timeout=60, remote_signed=False): + access = contract.protected_json(ROOT / 'credentials/windows-dev-access.json') + script = "try {\n"+script+"\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber} | ConvertTo-Json -Compress; exit 1}" + command = 'powershell.exe -NoLogo -NoProfile -NonInteractive ' + ('-ExecutionPolicy RemoteSigned ' if remote_signed else '') + '-EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode('ascii') + result = subprocess.run(access['ssh_prefix'] + [command], input=(json.dumps(payload or {})+'\n').encode(), capture_output=True, timeout=timeout) + if result.returncode: + print(json.dumps({'bootstrap_returncode':result.returncode,'stdout_bytes':len(result.stdout),'stderr_bytes':len(result.stderr)})) + failure=EVIDENCE/'bootstrap-private-last-error.json' + fd=os.open(failure,os.O_CREAT|os.O_TRUNC|os.O_WRONLY,0o600) + with os.fdopen(fd,'w') as out:json.dump({'stdout':result.stdout.decode('utf-8',errors='replace'),'stderr':result.stderr.decode('utf-8',errors='replace')},out) + # Exact stderr can contain private paths, command arguments and tokens. + try: + report=json.loads(result.stdout.decode('utf-8-sig')) + if report.get('bootstrap_error'): + print(json.dumps({'bootstrap_error':True,'error_id':report.get('error_id'),'line':report.get('line')})) + except (ValueError,AttributeError):pass + raise RuntimeError('WINDOWS_BOOTSTRAP_FAILED_' + str(result.returncode)) + return json.loads(result.stdout.decode('utf-8-sig')) + + +UPLOAD = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine() | ConvertFrom-Json) +if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin))\.exe|Install-PassiveClient\.ps1)$') {throw 'Artifact allowlist'} +$root='C:\ProgramData\RustDiscoveryBootstrap' +if (!(Test-Path -LiteralPath $root)) { + New-Item -ItemType Directory -Path $root | Out-Null + $acl=New-Object Security.AccessControl.DirectorySecurity + $acl.SetAccessRuleProtection($true,$false) + foreach($sid in @('S-1-5-18','S-1-5-32-544')) { + $s=New-Object Security.Principal.SecurityIdentifier($sid) + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($s,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))) + } + $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544'))) + Set-Acl -LiteralPath $root -AclObject $acl +} +if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'} +$version=Join-Path $root $p.sha256 +if (!(Test-Path -LiteralPath $version)) {New-Item -ItemType Directory -Path $version | Out-Null} +$path=Join-Path $version $p.name +if (Test-Path -LiteralPath $path) {throw 'Artifact already exists'} +[pscustomobject]@{prepared=$true;sha256=$p.sha256} | ConvertTo-Json -Compress +''' +VERIFY_UPLOAD = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine() | ConvertFrom-Json) +if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin))\.exe|Install-PassiveClient\.ps1)$') {throw 'Artifact allowlist'} +$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name +$hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() +if ($hash -cne $p.sha256) {throw 'Artifact hash'} +[pscustomobject]@{uploaded=$true;sha256=$hash;size=(Get-Item -LiteralPath $path).Length} | ConvertTo-Json -Compress +''' +PROBE = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine() | ConvertFrom-Json) +if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'} +$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\rmm-agent-windows.exe' +$raw=& $path --native-probe +if ($LASTEXITCODE -ne 0) {throw 'Native probe failed'} +$probe=$raw | ConvertFrom-Json +$os=Get-CimInstance Win32_OperatingSystem -Property Caption,Version,OSArchitecture +[pscustomobject]@{probe=$probe;os_caption=$os.Caption;os_version=$os.Version;architecture=$os.OSArchitecture;native_execution=$true} | ConvertTo-Json -Depth 8 -Compress +''' +TEST = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine() | ConvertFrom-Json) +if ($p.kind -notin @('lib','bin')) {throw 'Test allowlist'} +if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'} +$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\windows-tests-'+$p.kind+'.exe' +$out=& $path --test-threads=1 2>&1 +$code=$LASTEXITCODE +$summary=@($out | Where-Object {"$_" -match '^test result: '}) +if (!$summary) {throw 'No native test summary'} +[pscustomobject]@{exit_code=$code;native_execution=$true;summary=($summary -join ' ')} | ConvertTo-Json -Compress +''' + + +def record(name, evidence): + EVIDENCE.mkdir(mode=0o700, parents=True, exist_ok=True) + EVIDENCE.chmod(0o700) + path=EVIDENCE/name + fd=os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fd,'w') as out: + json.dump(evidence,out,indent=2) + out.flush(); os.fsync(out.fileno()) + return path + + +def upload(path, name): + data=Path(path).read_bytes() + digest=hashlib.sha256(data).hexdigest() + metadata=dict(name=name,sha256=digest) + powershell(UPLOAD,metadata,timeout=60) + access=contract.protected_json(ROOT/'credentials/windows-dev-access.json') + prefix=access['ssh_prefix'] + args=['sftp']+[part for part in prefix[1:-1] if part!='-T']+['-b','-',prefix[-1]] + remote='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+name + batch='put '+json.dumps(str(Path(path).resolve()))+' '+json.dumps(remote)+'\n' + transferred=subprocess.run(args,input=batch.encode(),capture_output=True,timeout=120) + if transferred.returncode:raise RuntimeError('WINDOWS_SFTP_UPLOAD_FAILED') + result=powershell(VERIFY_UPLOAD,metadata,timeout=60) + record(name+'.'+result['sha256']+'.uploaded.json',result) + pointer=EVIDENCE/(name+'.latest.json') + fd=os.open(pointer,os.O_CREAT|os.O_TRUNC|os.O_WRONLY,0o600) + with os.fdopen(fd,'w') as out:json.dump(result,out) + return result + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('action',choices=['upload-agent','upload-lib-tests','upload-bin-tests','upload-installer','install','install-after-nonstart','probe','test-lib','test-bin']) + parser.add_argument('--artifact',type=Path) + args=parser.parse_args() + if args.action.startswith('upload-'): + if args.artifact is None: parser.error('--artifact required') + name={'upload-agent':'rmm-agent-windows.exe','upload-lib-tests':'windows-tests-lib.exe','upload-bin-tests':'windows-tests-bin.exe','upload-installer':'Install-PassiveClient.ps1'}[args.action] + result=upload(args.artifact,name) + print(json.dumps(result)) + elif args.action in ('install','install-after-nonstart'): + import remote_client_bootstrap as cloud + artifact=contract.protected_json(EVIDENCE/'rmm-agent-windows.exe.latest.json') + installer=contract.protected_json(EVIDENCE/'Install-PassiveClient.ps1.latest.json') + # A create-once local checkpoint prevents creating a second token after + # an ambiguous remote bootstrap. Inspect/preserve Windows state instead. + if args.action=='install-after-nonstart': + previous=contract.protected_json(EVIDENCE/'install-nonstart-after-policy.json') + contract.require(not any(previous[k] for k in ('client_root','application_root','service')) and previous['machine_policy']=='Undefined' and previous['user_policy']=='Undefined','verified_bootstrap_nonstart_required') + checkpoint='installation-started.json' if args.action=='install' else 'installation-after-nonstart-started.json' + record(checkpoint,{'artifact_sha256':artifact['sha256'],'installer_sha256':installer['sha256'],'new_windows_guest_only':True,'process_execution_policy':'RemoteSigned' if args.action=='install-after-nonstart' else 'unchanged'}) + material=cloud.rpc('server.conf',cloud.server,{'action':'enroll'}) + script="$p=([Console]::In.ReadLine() | ConvertFrom-Json);$path='C:\\ProgramData\\RustDiscoveryBootstrap\\"+installer['sha256']+"\\Install-PassiveClient.ps1'; if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+installer['sha256']+"') {throw 'Installer hash'}; $global:RmmBootstrapPayload=$p; & $path" + # Pass one small JSON line on stdin, never arguments/environment/logs. + record(checkpoint+'.enrollment-token-hash.json',{'token_sha256':hashlib.sha256(material['token'].encode()).hexdigest(),'one_use':True}) + result=powershell(script,{'sha256':artifact['sha256'],'token':material['token'],'ca':material['ca']},timeout=90,remote_signed=args.action=='install-after-nonstart') + record('installed.json',result);print(json.dumps(result)) + elif args.action=='probe': + artifact=contract.protected_json(EVIDENCE/'rmm-agent-windows.exe.latest.json') + result=powershell(PROBE,{'sha256':artifact['sha256']},timeout=60);record('native-probe-'+artifact['sha256']+'.json',result) + print(json.dumps({k:v for k,v in result.items() if k!='probe'}|{'jobs_supported':result['probe']['jobs_supported']})) + else: + kind=args.action.removeprefix('test-') + artifact=contract.protected_json(EVIDENCE/('windows-tests-'+kind+'.exe.latest.json')) + result=powershell(TEST,{'kind':kind,'sha256':artifact['sha256']},timeout=120) + record(args.action+'.json',result);print(json.dumps(result)) + if result['exit_code']!=0:raise RuntimeError('NATIVE_WINDOWS_TEST_FAILED') + + +if __name__=='__main__': + try:main() + except Exception as error: + print(json.dumps({'error':type(error).__name__,'details_suppressed':True}));sys.exit(1) diff --git a/docs/handover.md b/docs/handover.md index 3618907..4998359 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -1,14 +1,16 @@ # Übergabe / Entwicklungspause — 2026-11-12 -**Aktueller Arbeitsstand 2026-11-13:** Neuer signierter einmaliger APT- -Wiederaufnahmevertrag implementiert und lokal geprüft; aktualisierter Helper/ -Provider auf Cloud-VM installiert, echter Readonly-Sandboxprobe bestanden. -Originalmarker/Fehlversuch und Sharedledger erhalten, kein Paketjob gestartet. -APT wieder gestoppt/Policy geschlossen; Agent und allgemeiner Helper aktiv. -Serverbuild läuft getrennt; Windows-Client parallel in Arbeit. Neueste Details -stehen oben in `implementation-status.md`. Die folgenden Zwischenstände sind -historische Snapshots. - +**Aktueller Arbeitsstand 2026-11-13:** Ein neuer separat WebUI-genehmigter +signierter APT-Versuch lief bis Hook armed / APT 0, Nachprüfung jedoch +`DPKG_INCONSISTENT`; gespeicherte Logs Fixture1.0 nur unpacked, kein Configure. +**unknown**, Sharedledger9/1unresolved, zentrale13/13/12, keine Acceptance. +Originalmarker/History sowie eigener Retrymarker erhalten. Keine weiteren +Paketjobs/Reparaturen/Markerresets. Rootpolicy geschlossen; signierter Abgleich +und begrenzte Configure-Korrektur offen. Windows-native Probe bestanden, +LocalService/mTLS/Heartbeat online; Inventar durch alten SQL-Scopecheck blockiert. +Identitäten/Journale erhalten; additive Windowsmigration als nächster Schritt. +Neueste genaue Nachweise oben in `implementation-status.md`. Ältere Abschnitte +sind abgeschlossene historische Snapshots. **Aktueller Folgestand 2026-11-13:** APT-100-Ursache durch separat WebUI-genehmigte Cloud-Diagnosen belegt: `--no-download` lieferte im echten v3-Hook `**ERROR**` diff --git a/docs/implementation-status.md b/docs/implementation-status.md index ec0bdce..4b9409e 100644 --- a/docs/implementation-status.md +++ b/docs/implementation-status.md @@ -1,5 +1,67 @@ # Tatsächlicher Implementierungsstand +## Neuer APT-Versuch: Hook/APT bestanden, Nachprüfung unknown — 2026-11-13 + +**Kein Paketerfolg und keine Linux-MVP-Abnahme.** Neuer fest gebundener +Schema-3-Versuch tatsächlich durch die dev/test-WebUI vorbereitet; separater +Freigabebrowser verglich zuerst irrtümlich auch das veränderliche +Antragsmetadatum `approval_state`. Er stoppte vor dem Klick; mehrfach gespeicherte +0/0/0 belegen keine Wirkung. Vergleich korrigiert: `null` vor Submit und +`pending_approval` danach ausdrücklich prüfen, **alle übrigen Felder und exakten +Plan-/Jobbytes unverändert vergleichen**. Derselbe bestehende Antrag wurde +anschließend einmal tatsächlich per UI genehmigt, kein weiterer Plan/Versuch. + +Vorher 0/0/0, danach **1/1/1**. Audit +`approval_origin=dev_test_browser_simulation`, `testsimulation=true`, +`simulated-testprincipal-a`, gebundener Planhash. Der neue Helper verifizierte +den ursprünglichen Fehler und signierten Auftrag, verschob den alten `active/` +in unveränderte Historie und schrieb einen eigenen Create-once-Retrymarker. +Ursprünglicher Marker weiterhin +`ec84aa4df8065f0b54b282bd273a6f342f07a6d47312289608389d05c7fb6053`. + +Native Sandbox-/Lock-/Syscallprüfungen bestanden, Hook tatsächlich armed, +**APT Exit 0**, kein Rebootflag. Gebundene unabhängige Nachprüfung verweigerte +jedoch `DPKG_INCONSISTENT`; Rootledger behält **unknown**, Zentrale zeigt +`unknown / SYNC_EFFECT_UNRESOLVED`. Gespeicherte dpkg-Logs belegen ausschließlich +`half-installed -> unpacked` für Fixture 1.0, keinen Configure-Aufruf. Kein +nativer Acceptancebeleg oder gestagter Ersatzbeleg. Vorhandene Logs nur gelesen, +keine neue Live-Paketdiagnose über SSH und kein Shell-APT/dpkg-Reparaturaufruf. + +Die konfigurierte Sperre `DPkg::ConfigurePending=false` trifft auf APTs +standardmäßiges `dpkg::selection::remove::approved=true`: dieser Pfad entfernt +explizite Configure-Aktionen und ergänzt sonst ConfigurePending. Das erklärt +den beobachteten Unpack-only-Lauf; Primärquelle: +[APT 2.7.14 dpkgpm.cc](https://github.com/Debian/apt/blob/2.7.14/apt-pkg/deb/dpkgpm.cc#L1626-L1657). +Eine begrenzte Korrektur muss explizites Configure des genehmigten Pakets +erhalten, **kein** allgemeines `--configure --pending` erlauben. Neue lokale +Regression und sichere gebundene Wiederherstellung des teilweise ausgeführten +Versuchs sind offen; kein blindes Retry/Upgrade/Noop gegen diesen Zustand. + +Zähler Linux **13 Jobs / 13 Outbox / 12 Grants, 1 unresolved**; Sharedledger +**9 consumed / 1 unresolved**, alle ursprünglichen Tombstones erhalten. +Neue Root-Testpolicy geschlossen, Helper bleiben zur unbekannten Wirkung und +zum signierten Abgleich erhalten. Geschützt: +`devstate/cloud-apt-retry/apt_install_retry/{checkpoint,stored-evidence,stored-log-evidence}.json`. + +## Windows: native Probe und erster Dienstkontakt — 2026-11-13 + +Neuer passiver Windows-Client mit gemeinsamem Domain-/Protobuf-/TLS-/WSS-/HTTPS- +Vertrag. GNU-x64-Crossbuild Debug/Release und Windows-target Clippy bestanden; +native Probe wirklich auf Windows 11 Pro 10.0.26300 x64 bestanden: Win32-Hostname, +Systemvolume, CIM-Bootkennung, keine erfundenen Inodes. Artefakt +`31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37`. +Anschließend tatsächlicher SCM-Dienst als **LocalService (S-1-5-19)** gestartet, +Geräteschlüssel ausschließlich im Gast erzeugt, Enrollmenttoken entfernt; +mTLS-Hello und frischer Heartbeat serverseitig online bestätigt. + +**Inventar noch nicht gespeichert:** native Integration deckte den alten +SQL-Check `source_id='linux.base'` auf. Additive Migration erforderlich; die +bestehende Windowsidentität und durable Inventarnachricht bleiben erhalten. +Native Windows-Testprogramme bislang nicht erfolgreich abgeschlossen. Kein +Jobexecutor/Helper, keine Jobcapability oder Genehmigungsabkürzung; erster Build +unsigniert. Notebook-Host weiterhin ausschließlich Entwicklung. Detailvertrag +und ausgeführte/geplante Befehle: `deploy/windows/CLIENT.md`. + ## Cloudserver und Linux-Agent aktualisiert, ohne neue Jobs — 2026-11-13 Versionierter Cloudserver-Sourceupload/ARM64-Releasebuild tatsächlich erfolgreich, diff --git a/docs/server-deployment.md b/docs/server-deployment.md index 11a2a3b..3c2d16e 100644 --- a/docs/server-deployment.md +++ b/docs/server-deployment.md @@ -4,6 +4,14 @@ Stand: 2026-11-13 · Spezifikation 1.9 · Linux-MVP weiterhin nicht abgenommen. ## Neuester APT-/Bootstrapstand +**Neuester Versuch:** Hook armed/APT 0, aber Fixture 1.0 laut gespeicherten Logs +nur unpacked, Nachprüfung `DPKG_INCONSISTENT`, Ergebnis **unknown**. Ledger9/1 +unresolved, zentrale13/13/12; Rootpolicy geschlossen, kein weiterer Paketversuch. +Windowsprobe bestanden, LocalService/mTLS/Heartbeat online, Inventar-SQL-Migration +offen. Aktuelle Details in `implementation-status.md`; folgende Zwischenstände +nicht als heutigen finalen Erfolg lesen. + + **Fortsetzung:** Signierter einzelner Retryvertrag implementiert, neue Helper-Sandboxreadiness auf Cloud-VM bestanden. Cloudserver und Linux-Agent identitäts-/journalbewahrend aktualisiert, Linux online/sync-ready. APT-Endpunkt