Compare commits

..
Author SHA1 Message Date
kevin_janssen b4dbeba9c6 docs: record native pipe v2 pair upgrade and preservation proof
Rust development slice / linux (push) Failing after 6s
2026-11-14 15:55:45 +01:00
kevin_janssen 68c1b11d0c docs: verify restored Windows access and preserved transport identity
Rust development slice / linux (push) Failing after 6s
2026-11-14 15:51:33 +01:00
kevin_janssen e7dcad9c10 Fix confirmed PowerShell history alias collision with a verified create-only console patch
Rust development slice / linux (push) Failing after 6s
2026-11-14 15:00:03 +01:00
kevin_janssen 900e19d471 Correct console account expiry binding without altering the completed server lease
Rust development slice / linux (push) Failing after 7s
2026-11-14 14:40:45 +01:00
kevin_janssen fc2d01d3c4 Record prepared pipe pair upgrade and separate expired development access recovery
Rust development slice / linux (push) Failing after 6s
2026-11-14 14:16:56 +01:00
kevin_janssen 330087c050 Record 23 plus 7 native Windows pipe-v2 unit results
Rust development slice / linux (push) Failing after 6s
2026-11-14 13:35:57 +01:00
kevin_janssen 3d152aee41 Add bounded v2 drain receipts for Windows helper response transport
Rust development slice / linux (push) Failing after 6s
2026-11-14 12:37:22 +01:00
kevin_janssen 7cf34c267d Complete preserving Windows component recovery with explicit native backups
Rust development slice / linux (push) Failing after 6s
2026-11-14 11:38:42 +01:00
kevin_janssen 1d8cdda1ab Record first replacement failure and preserved stopped Windows components
Rust development slice / linux (push) Failing after 6s
2026-11-14 11:20:09 +01:00
kevin_janssen 5a1de712cf Record failed native Windows clock candidate without weakening the job gate
Rust development slice / linux (push) Failing after 5s
2026-11-14 11:00:51 +01:00
kevin_janssen 0be13da6d7 Start existing Windows time service once with independent preservation evidence
Rust development slice / linux (push) Failing after 6s
2026-11-14 10:55:42 +01:00
kevin_janssen c4efe8a4b4 Record native profile acceptance and narrowly scoped dev transport recovery
Rust development slice / linux (push) Failing after 6s
2026-11-14 10:39:18 +01:00
kevin_janssen bbdfe59380 Index Linux-first Windows policy branch without changing runtime qualification
Rust development slice / linux (push) Failing after 6s
2026-11-14 10:20:00 +01:00
kevin_janssen 548996eb36 Record observed development tunnel limitation for post-MVP work
Rust development slice / linux (push) Failing after 6s
2026-11-14 09:45:49 +01:00
59 changed files with 3194 additions and 3600 deletions
+2 -2
View File
@@ -33,8 +33,8 @@ impl Binding {
);
ensure!(
j.action.validate()
&& j.action
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
&& (1..=3600).contains(&j.max_runtime_seconds)
&& (1..=262144).contains(&j.max_output_bytes)
&& j.not_before < j.start_before,
"INVALID_JOB"
);
-64
View File
@@ -40,7 +40,6 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
script_utf8: "printf 'Hello\\n'\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\n".into()),
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now - Duration::minutes(1),
@@ -171,69 +170,6 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
let mut changed = request;
changed.signature.truncate(63);
assert!(binding.verify(&changed, now).is_err());
// Changing only the process policy is a payload mutation, even with the
// same script/attempt and a still valid original signature.
let (_, mut request, mut permit, _) = fixture();
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
job.action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'Hello'\r\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\r\n".into()),
windows_execution_profile: None,
};
request.job_bytes = encode(&job).unwrap();
permit.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&permit).unwrap();
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
binding.verify(&request, now).unwrap();
if let Action::RunScript {
windows_execution_profile,
..
} = &mut job.action
{
*windows_execution_profile =
Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
}
request.job_bytes = encode(&job).unwrap();
assert!(binding.verify(&request, now).is_err());
permit.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&permit).unwrap();
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
binding.verify(&request, now).unwrap();
// The exact fixed Event Log source/window/limits are original signed bytes.
job.action = Action::QueryLogs {
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: now - chrono::Duration::hours(1),
until: now,
max_lines: 1000,
};
request.job_bytes = encode(&job).unwrap();
permit.action = job.action.name().into();
permit.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&permit).unwrap();
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
binding.verify(&request, now).unwrap();
let mut wrong_source = job.clone();
if let Action::QueryLogs { unit, .. } = &mut wrong_source.action {
*unit = "Security".into();
}
let mut changed = request.clone();
changed.job_bytes = encode(&wrong_source).unwrap();
assert!(binding.verify(&changed, now).is_err());
for (runtime, bytes) in [(9, 4096), (121, 4096), (10, 1023), (10, 65537)] {
let mut changed_job = job.clone();
changed_job.max_runtime_seconds = runtime;
changed_job.max_output_bytes = bytes;
let mut changed_permit = permit.clone();
changed_permit.max_runtime_seconds = runtime;
let mut changed = request.clone();
changed.job_bytes = encode(&changed_job).unwrap();
changed_permit.job_payload_hash = hash(&changed.job_bytes);
changed.permit_bytes = encode(&changed_permit).unwrap();
changed.signature = key.sign(&changed.permit_bytes).to_bytes().to_vec();
assert!(binding.verify(&changed, now).is_err());
}
}
#[cfg(unix)]
@@ -867,7 +867,6 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
-1
View File
@@ -605,7 +605,6 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+1 -1
View File
@@ -39,4 +39,4 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
+13 -178
View File
@@ -2,7 +2,7 @@
//! consumption are supplied by the shared core and the runtime, never bypassed.
use anyhow::{Result, ensure};
use rmm_agent_core::auth::Outcome;
use rmm_domain::jobs::{Action, JobPayload, WindowsExecutionProfile, hash};
use rmm_domain::jobs::{Action, JobPayload, hash};
use std::{
ffi::OsString,
fs::{File, OpenOptions},
@@ -11,41 +11,6 @@ use std::{
path::{Path, PathBuf},
sync::atomic::AtomicBool,
};
/// Implemented contract name only. Runtime publication still requires its own
/// native clock/boot/job qualification; this constant grants no capability.
pub const REMOTE_SIGNED_PROFILE_CAPABILITY: &str = "script.powershell.process_remote_signed/1";
fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
let Action::RunScript {
interpreter,
arguments,
windows_execution_profile,
..
} = &job.action
else {
anyhow::bail!("SCRIPT_REQUIRED")
};
ensure!(
job.execution_identity == "agent_service"
&& interpreter == "powershell"
&& job.action.validate(),
"WINDOWS_SCRIPT_PROFILE_BINDING"
);
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive"]
.into_iter()
.map(OsString::from)
.collect();
if let Some(WindowsExecutionProfile::PowerShell51RemoteSigned) = windows_execution_profile {
args.extend([
OsString::from("-ExecutionPolicy"),
OsString::from("RemoteSigned"),
]);
}
args.push(OsString::from("-File"));
args.push(path.as_os_str().into());
args.extend(arguments.iter().map(OsString::from));
Ok(args)
}
use windows_sys::Win32::{
Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
@@ -71,45 +36,10 @@ pub fn supported(job: &JobPayload) -> bool {
interpreter == "powershell" && powershell().is_ok()
}
Action::RefreshInventory { scope } => scope == "windows.base",
Action::QueryLogs { .. } => crate::event_log::for_job(job).is_ok(),
_ => false,
}
}
/// Each prepared operation retains its own typed binding; no non-script action
/// can fall through to inventory or borrow the PowerShell execution profile.
pub enum PreparedAction {
Script(Script),
Inventory,
EventLog(crate::event_log_job::Prepared),
}
impl PreparedAction {
pub fn prepare(
job: &JobPayload,
directory: &Path,
grant: uuid::Uuid,
request: &rmm_agent_core::auth::Request,
boot: uuid::Uuid,
) -> Result<Self> {
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
match &job.action {
Action::RunScript { .. } => Ok(Self::Script(Script::prepare(job, directory, grant)?)),
Action::RefreshInventory { scope } if scope == "windows.base" => Ok(Self::Inventory),
Action::QueryLogs { .. } => Ok(Self::EventLog(
crate::event_log_job::Prepared::prepare(job, directory, request, grant, boot)?,
)),
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
}
}
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
match self {
Self::Script(script) => script.run(job, cancel),
Self::Inventory => inventory(job),
Self::EventLog(log) => log.run(job, cancel),
}
}
}
pub struct Script {
executable: PathBuf,
path: PathBuf,
@@ -117,7 +47,6 @@ pub struct Script {
_file: File,
cwd: PathBuf,
arguments: Vec<OsString>,
profile: Option<WindowsExecutionProfile>,
}
impl Script {
/// Preparation creates only a protected copy of approved bytes, no child.
@@ -127,7 +56,7 @@ impl Script {
let Action::RunScript {
interpreter,
script_utf8,
windows_execution_profile,
arguments,
..
} = &job.action
else {
@@ -166,14 +95,18 @@ impl Script {
hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()),
"SCRIPT_BYTES_CHANGED"
);
let args = script_arguments(job, &path)?;
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"]
.into_iter()
.map(OsString::from)
.collect();
args.push(path.clone().into_os_string());
args.extend(arguments.iter().map(OsString::from));
Ok(Self {
executable: powershell()?,
path,
_file: file,
cwd: directory.to_path_buf(),
arguments: args,
profile: *windows_execution_profile,
})
}
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
@@ -182,7 +115,6 @@ impl Script {
let Action::RunScript {
script_utf8,
expected_stdout,
windows_execution_profile,
..
} = &job.action
else {
@@ -192,11 +124,6 @@ impl Script {
std::fs::read(&self.path)? == script_utf8.as_bytes(),
"SCRIPT_BYTES_CHANGED"
);
ensure!(
self.profile == *windows_execution_profile
&& self.arguments == script_arguments(job, &self.path)?,
"WINDOWS_SCRIPT_PROFILE_CHANGED"
);
let output = crate::process::run(
&self.executable,
&self.arguments,
@@ -232,17 +159,6 @@ impl Script {
} else {
""
};
let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
"execution_policy":"inherited","process_tree_bounded":true,
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted});
if self.profile.is_some() {
evidence["windows_execution_profile"] = serde_json::to_value(self.profile)?;
evidence["execution_policy"] = serde_json::json!("process_remote_signed_requested");
evidence["execution_policy_requested"] = serde_json::json!("RemoteSigned");
evidence["execution_policy_scope"] = serde_json::json!("process");
}
Ok(Outcome {
state: state.into(),
stdout: output.stdout,
@@ -251,7 +167,11 @@ impl Script {
output_truncated: output.truncated,
reboot_required: false,
error_code: code.into(),
evidence,
evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
"execution_policy":"inherited","process_tree_bounded":true,
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}),
})
}
}
@@ -280,88 +200,3 @@ pub fn inventory(job: &JobPayload) -> Result<Outcome> {
"observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
let mut job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'fixed'\r\n".into(),
arguments: vec!["-ExecutionPolicy".into(), "Bypass".into()],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::seconds(60),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let path = Path::new(r"C:\fixed state\approved.ps1");
let inherited = script_arguments(&job, path).unwrap();
assert_eq!(
inherited,
vec![
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-File",
r"C:\fixed state\approved.ps1",
"-ExecutionPolicy",
"Bypass"
]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()
);
if let Action::RunScript {
windows_execution_profile,
..
} = &mut job.action
{
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
}
let args = script_arguments(&job, path).unwrap();
assert_eq!(
args[..6],
[
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"RemoteSigned",
"-File"
]
.map(OsString::from)
);
assert_eq!(args[6], path.as_os_str()); // approved arguments remain AFTER -File
assert_ne!(inherited, args);
let mut unknown = serde_json::to_value(&job.action).unwrap();
unknown["windows_execution_profile"] = serde_json::json!("Bypass");
assert!(serde_json::from_value::<Action>(unknown).is_err());
for identity in ["root", "system"] {
job.execution_identity = identity.into();
assert!(script_arguments(&job, path).is_err());
}
job.execution_identity = "agent_service".into();
for other in ["posix_sh", "bash", "pwsh"] {
if let Action::RunScript { interpreter, .. } = &mut job.action {
*interpreter = other.into();
}
assert!(script_arguments(&job, path).is_err());
}
}
}
+4 -88
View File
@@ -1,5 +1,4 @@
//! Bounded, local, fixture-only Event Log provider. Only the authorized native
//! job worker may call the Windows provider; this module confers no authority.
//! Bounded, local, fixture-only live Event Log query; not wired into any job.
//!
//! EvtQuery/EvtRender have no per-call timeout. The monotonic deadline below is
//! cooperative between Win32 calls; the eventual executor must also supervise
@@ -13,9 +12,8 @@ use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use std::sync::atomic::AtomicBool;
pub use rmm_domain::jobs::{
WINDOWS_EVENT_LOG_FIXTURE_CHANNEL as CHANNEL, WINDOWS_EVENT_LOG_FIXTURE_PROVIDER as PROVIDER,
};
pub const CHANNEL: &str = "Application";
pub const PROVIDER: &str = "RustDiscovery-MVP-Test";
const MAX_BYTES: usize = 256 * 1024;
#[cfg(any(windows, test))]
const REPORT_RESERVE: usize = 256;
@@ -59,42 +57,7 @@ impl Query {
}
}
/// Pure job-to-provider binding. Never opens a channel or touches a bookmark.
pub fn for_job(job: &rmm_domain::jobs::JobPayload) -> Result<Query> {
use rmm_domain::jobs::{Action, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
let Action::QueryLogs {
unit,
since,
until,
max_lines,
} = &job.action
else {
anyhow::bail!("EVENT_LOG_ACTION_REQUIRED")
};
ensure!(
job.execution_identity == "agent_service"
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes),
"EVENT_LOG_JOB_BINDING"
);
let q = Query {
channel: CHANNEL.into(),
provider: PROVIDER.into(),
start_utc: *since,
end_utc: *until,
max_events: *max_lines,
max_output_bytes: job.max_output_bytes,
timeout_ms: 5000,
};
q.xpath()?;
Ok(q)
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[derive(Debug, Serialize)]
pub struct Event {
pub channel: String,
pub provider: String,
@@ -538,53 +501,6 @@ mod tests {
}
}
#[test]
fn job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits() {
use rmm_domain::jobs::{Action, JobPayload, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
let id = uuid::Uuid::new_v4();
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
let mut job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: Action::QueryLogs {
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: now,
until: now + chrono::Duration::hours(24),
max_lines: 1000,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::seconds(60),
max_runtime_seconds: 10,
max_output_bytes: 65536,
};
let q = for_job(&job).unwrap();
assert_eq!(
(q.channel.as_str(), q.provider.as_str()),
(CHANNEL, PROVIDER)
);
assert_eq!(q.max_output_bytes, 65536);
for identity in ["root", "system"] {
job.execution_identity = identity.into();
assert!(for_job(&job).is_err());
}
job.execution_identity = "agent_service".into();
for bytes in [1023, 65537] {
job.max_output_bytes = bytes;
assert!(for_job(&job).is_err());
}
job.max_output_bytes = 65536;
if let Action::QueryLogs { until, .. } = &mut job.action {
*until += chrono::Duration::nanoseconds(1);
}
assert!(for_job(&job).is_err());
}
#[test]
fn serialized_byte_budget_includes_xml_escaping_and_metadata() {
let q = request();
let mut report = Report::new(&q);
-778
View File
@@ -1,778 +0,0 @@
//! Fixed, authorized Event Log subprocess. A command-line mode is not a live
//! query API: the child authenticates its real SCM parent, original signed
//! request, protected public trust, and an already committed consumption/start.
//! Request/grant bytes remain in a private, create-once job file, never argv.
use crate::{event_log, native};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use rmm_agent_core::auth::{Binding, Outcome, Request};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
use serde::{Deserialize, Serialize};
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
mem::{size_of, size_of_val, zeroed},
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle, OwnedHandle},
},
path::{Path, PathBuf},
ptr,
sync::atomic::AtomicBool,
time::Duration,
};
use uuid::Uuid;
use windows_sys::Win32::{
Foundation::*,
Security::{self, *},
Storage::FileSystem::*,
System::{Diagnostics::ToolHelp::*, Services::*, Threading::*},
};
pub const MODE: &str = "--eventlog-worker";
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
const TICKET_LIMIT: u64 = 128 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct FileId {
volume: u64,
id: [u8; 16],
}
fn file_id(handle: HANDLE) -> Result<FileId> {
let mut info: FILE_ID_INFO = unsafe { zeroed() };
ensure!(
unsafe {
GetFileInformationByHandleEx(
handle,
FileIdInfo,
(&mut info as *mut FILE_ID_INFO).cast(),
size_of::<FILE_ID_INFO>() as u32,
)
} != 0,
"EVENT_LOG_FILE_ID"
);
Ok(FileId {
volume: info.VolumeSerialNumber,
id: info.FileId.Identifier,
})
}
fn owned(handle: HANDLE) -> Result<OwnedHandle> {
ensure!(
!handle.is_null() && handle != INVALID_HANDLE_VALUE,
"EVENT_LOG_HANDLE"
);
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
fn birth(handle: HANDLE) -> Result<u64> {
let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) };
ensure!(
unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0,
"EVENT_LOG_PROCESS_TIME"
);
Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime))
}
fn text(value: *const u16) -> Result<String> {
ensure!(!value.is_null(), "EVENT_LOG_NATIVE_STRING");
let mut length = 0;
while length < 32768 && unsafe { *value.add(length) } != 0 {
length += 1;
}
ensure!(length < 32768, "EVENT_LOG_NATIVE_STRING_SIZE");
Ok(String::from_utf16(unsafe {
std::slice::from_raw_parts(value, length)
})?)
}
fn process_image(handle: HANDLE) -> Result<PathBuf> {
let mut buffer = vec![0u16; 32768];
let mut len = buffer.len() as u32;
ensure!(
unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut len) } != 0,
"EVENT_LOG_PARENT_IMAGE"
);
Ok(String::from_utf16(&buffer[..len as usize])?.into())
}
struct Service(SC_HANDLE);
impl Drop for Service {
fn drop(&mut self) {
unsafe {
CloseServiceHandle(self.0);
}
}
}
fn agent_pid(image: &Path) -> Result<u32> {
let manager = Service(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
ensure!(!manager.0.is_null(), "EVENT_LOG_SCM");
let service = Service(unsafe {
OpenServiceW(
manager.0,
native::wide(crate::SERVICE_NAME).as_ptr(),
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS,
)
});
ensure!(!service.0.is_null(), "EVENT_LOG_AGENT_SERVICE");
let mut bytes = 0;
unsafe {
QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut bytes);
}
ensure!((1..=32768).contains(&bytes), "EVENT_LOG_AGENT_CONFIG_SIZE");
let mut storage = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
ensure!(
unsafe { QueryServiceConfigW(service.0, storage.as_mut_ptr().cast(), bytes, &mut bytes) }
!= 0,
"EVENT_LOG_AGENT_CONFIG"
);
let config = unsafe { &*storage.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
ensure!(
config.dwServiceType == SERVICE_WIN32_OWN_PROCESS
&& text(config.lpBinaryPathName)?
== format!("\"{}\" --service --config \"{CONFIG}\"", image.display())
&& text(config.lpServiceStartName)?.eq_ignore_ascii_case(r"NT AUTHORITY\LocalService"),
"EVENT_LOG_AGENT_CONFIG_BINDING"
);
let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() };
ensure!(
unsafe {
QueryServiceStatusEx(
service.0,
SC_STATUS_PROCESS_INFO,
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
size_of::<SERVICE_STATUS_PROCESS>() as u32,
&mut bytes,
)
} != 0
&& status.dwCurrentState == SERVICE_RUNNING
&& status.dwProcessId > 0,
"EVENT_LOG_AGENT_NOT_RUNNING"
);
Ok(status.dwProcessId)
}
fn token_info(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<usize>> {
let mut bytes = 0;
unsafe {
GetTokenInformation(token, class, ptr::null_mut(), 0, &mut bytes);
}
ensure!((1..=65536).contains(&bytes), "EVENT_LOG_TOKEN_SIZE");
let mut data = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
ensure!(
unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), bytes, &mut bytes) }
!= 0,
"EVENT_LOG_TOKEN"
);
Ok(data)
}
fn service_token(process: HANDLE) -> Result<()> {
let mut token = ptr::null_mut();
ensure!(
unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } != 0,
"EVENT_LOG_TOKEN_OPEN"
);
let token = owned(token)?;
let user = token_info(token.as_raw_handle(), TokenUser)?;
let mut service_sid = ptr::null_mut();
ensure!(
unsafe {
Security::Authorization::ConvertStringSidToSidW(
native::wide(native::service_sid()?).as_ptr(),
&mut service_sid,
)
} != 0,
"EVENT_LOG_SERVICE_SID"
);
struct Sid(PSID);
impl Drop for Sid {
fn drop(&mut self) {
unsafe {
LocalFree(self.0);
}
}
}
let service_sid = Sid(service_sid);
let mut ls = [0usize; 16];
let mut size = size_of_val(&ls) as u32;
ensure!(
unsafe {
CreateWellKnownSid(
WinLocalServiceSid,
ptr::null_mut(),
ls.as_mut_ptr().cast(),
&mut size,
)
} != 0
&& unsafe {
EqualSid(
(*user.as_ptr().cast::<TOKEN_USER>()).User.Sid,
ls.as_ptr().cast_mut().cast(),
)
} != 0,
"EVENT_LOG_LOCAL_SERVICE_REQUIRED"
);
let groups = token_info(token.as_raw_handle(), TokenGroups)?;
let g = unsafe { &*groups.as_ptr().cast::<TOKEN_GROUPS>() };
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
ensure!(
g.GroupCount <= 1024
&& offset + g.GroupCount as usize * size_of::<SID_AND_ATTRIBUTES>()
<= groups.len() * size_of::<usize>(),
"EVENT_LOG_TOKEN_GROUPS_SIZE"
);
let entries = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), g.GroupCount as usize) };
let mut admins = [0usize; 16];
let mut admin_bytes = size_of_val(&admins) as u32;
ensure!(
unsafe {
CreateWellKnownSid(
WinBuiltinAdministratorsSid,
ptr::null_mut(),
admins.as_mut_ptr().cast(),
&mut admin_bytes,
)
} != 0,
"EVENT_LOG_ADMIN_SID"
);
ensure!(
!entries
.iter()
.any(|entry| entry.Attributes & 0x0000_0004 != 0
&& unsafe { EqualSid(entry.Sid, admins.as_ptr().cast_mut().cast()) } != 0),
"EVENT_LOG_ADMINISTRATOR_FORBIDDEN"
);
// TOKEN_GROUPS enabled/deny-only bits from winnt.h, as in the pipe peer proof.
ensure!(
entries
.iter()
.any(|entry| entry.Attributes & 0x0000_0004 != 0
&& entry.Attributes & 0x0000_0010 == 0
&& unsafe { EqualSid(entry.Sid, service_sid.0) } != 0),
"EVENT_LOG_AGENT_SID_REQUIRED"
);
Ok(())
}
fn parent_pid() -> Result<u32> {
let snapshot = owned(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })?;
let mut entry: PROCESSENTRY32W = unsafe { zeroed() };
entry.dwSize = size_of::<PROCESSENTRY32W>() as u32;
let mut ok = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };
while ok != 0 {
if entry.th32ProcessID == std::process::id() {
return Ok(entry.th32ParentProcessID);
}
ok = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };
}
anyhow::bail!("EVENT_LOG_PARENT_UNVERIFIED")
}
fn open_private(path: &Path, share_write: bool) -> Result<File> {
ensure!(
path.is_absolute() && !path.to_string_lossy().starts_with(r"\\"),
"EVENT_LOG_LOCAL_PATH"
);
for parent in path.ancestors().skip(1) {
use std::os::windows::fs::MetadataExt;
ensure!(
std::fs::symlink_metadata(parent)?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT
== 0,
"EVENT_LOG_REPARSE_ANCESTOR"
);
}
native::private_path(path, false)?;
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | if share_write { FILE_SHARE_WRITE } else { 0 })
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
use std::os::windows::fs::MetadataExt;
ensure!(
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
"EVENT_LOG_REPARSE_FILE"
);
Ok(file)
}
fn read(file: &mut File, limit: u64) -> Result<Vec<u8>> {
ensure!(
file.metadata()?.len() <= limit,
"EVENT_LOG_PRIVATE_FILE_LIMIT"
);
let mut value = Vec::new();
file.take(limit + 1).read_to_end(&mut value)?;
ensure!(value.len() as u64 <= limit, "EVENT_LOG_PRIVATE_FILE_LIMIT");
Ok(value)
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Ticket {
request: Request,
parent_pid: u32,
parent_birth: u64,
boot: Uuid,
ledger: FileId,
}
#[derive(Deserialize)]
struct WorkerConfig {
state_directory: PathBuf,
job_binding_file: PathBuf,
enable_jobs: bool,
}
fn ticket_name(permit: &ExecutionPermitPayload) -> String {
format!("eventlog-{}.json", hash(permit.grant_id.as_bytes()))
}
/// Prepared data only. No query, worker or Evt handle exists before run.
pub struct Prepared {
path: PathBuf,
_file: File,
ticket_hash: String,
job_bytes: Vec<u8>,
}
impl Prepared {
pub fn prepare(
job: &JobPayload,
directory: &Path,
request: &Request,
grant: Uuid,
boot: Uuid,
) -> Result<Self> {
event_log::for_job(job)?;
native::require_local_service()?;
service_token(unsafe { GetCurrentProcess() })?;
let image = std::env::current_exe()?;
ensure!(
agent_pid(&image)? == std::process::id(),
"EVENT_LOG_REAL_AGENT_REQUIRED"
);
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
ensure!(
permit.grant_id == grant && !boot.is_nil(),
"EVENT_LOG_GRANT_BINDING"
);
native::private_path(directory, true)?;
let ledger = open_private(
&directory
.parent()
.context("EVENT_LOG_STATE_DIRECTORY")?
.join("consumption.sqlite"),
true,
)?;
let ticket = Ticket {
request: request.clone(),
parent_pid: std::process::id(),
parent_birth: birth(unsafe { GetCurrentProcess() })?,
boot,
ledger: file_id(ledger.as_raw_handle())?,
};
let bytes = serde_json::to_vec(&ticket)?;
ensure!(bytes.len() as u64 <= TICKET_LIMIT, "EVENT_LOG_TICKET_LIMIT");
let path = directory.join(ticket_name(&permit));
let mut writer = OpenOptions::new()
.create_new(true)
.write(true)
.share_mode(0)
.open(&path)?;
writer.write_all(&bytes)?;
writer.sync_all()?;
drop(writer);
let mut file = open_private(&path, false)?;
ensure!(
read(&mut file, TICKET_LIMIT)? == bytes,
"EVENT_LOG_TICKET_CHANGED"
);
Ok(Self {
path,
_file: file,
ticket_hash: hash(&bytes),
job_bytes: request.job_bytes.clone(),
})
}
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
event_log::for_job(job)?;
ensure!(
serde_json::from_slice::<serde_json::Value>(&self.job_bytes)?
== serde_json::to_value(job)?,
"EVENT_LOG_JOB_CHANGED"
);
let mut file = open_private(&self.path, false)?;
ensure!(
hash(&read(&mut file, TICKET_LIMIT)?) == self.ticket_hash,
"EVENT_LOG_TICKET_CHANGED"
);
let output = crate::process::run(
&std::env::current_exe()?,
&[MODE.into(), self.path.as_os_str().into()],
self.path.parent().context("EVENT_LOG_JOB_DIRECTORY")?,
job.max_runtime_seconds,
job.max_output_bytes as usize,
cancel,
)?;
if output.interrupted {
return Ok(Outcome::unknown(if output.cancelled {
"EVENT_LOG_CANCELLED_RESULT_UNKNOWN"
} else {
"EVENT_LOG_TIMEOUT_RESULT_UNKNOWN"
}));
}
ensure!(
output.exit_code == Some(0) && !output.truncated && output.stderr.is_empty(),
"EVENT_LOG_WORKER_RESULT_UNVERIFIED"
);
outcome(job, output.stdout)
}
}
fn consumed(
db: &rusqlite::Connection,
binding: &Binding,
ticket: &Ticket,
permit: &ExecutionPermitPayload,
) -> Result<()> {
let length: u64 = db.query_row("SELECT length(e.start) FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1", [permit.grant_id.to_string()], |r| r.get(0))?;
ensure!(length <= TICKET_LIMIT, "EVENT_LOG_START_SIZE");
type Row = (String, u64, String, String, bool, Vec<u8>, bool);
let row: Row = db.query_row("SELECT c.agent,c.generation,c.job,c.attempt,c.result IS NULL,e.start,e.outcome IS NULL FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[permit.grant_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?)))?;
ensure!(
row.0 == binding.agent_id.to_string()
&& row.1 == binding.enrollment_generation
&& row.2 == permit.job_id.to_string()
&& row.3 == permit.attempt_id.to_string()
&& row.4
&& row.6,
"EVENT_LOG_CONSUMPTION_BINDING"
);
let start: serde_json::Value = serde_json::from_slice(&row.5)?;
ensure!(
start["previous_boot_id"] == ticket.boot.to_string()
&& serde_json::to_vec(&serde_json::from_value::<Request>(
start["request"].clone()
)?)? == serde_json::to_vec(&ticket.request)?,
"EVENT_LOG_ORIGINAL_START_BINDING"
);
let identity: String = db.query_row(
"SELECT identity FROM windows_binding WHERE length(identity)<=512",
[],
|r| r.get(0),
)?;
ensure!(
identity
== format!(
"{}:{}:{}:{}:{}",
binding.tenant_id,
binding.asset_id,
binding.agent_id,
binding.enrollment_generation,
binding.assignment_version
),
"EVENT_LOG_LEDGER_BINDING"
);
Ok(())
}
fn validate_ticket_path(path: &Path, directory: &Path) -> Result<()> {
let name = path
.file_name()
.and_then(|s| s.to_str())
.context("EVENT_LOG_TICKET_NAME")?;
let hash_name = name
.strip_prefix("eventlog-")
.and_then(|s| s.strip_suffix(".json"))
.context("EVENT_LOG_TICKET_NAME")?;
ensure!(
path.parent() == Some(directory)
&& hash_name.len() == 64
&& hash_name
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
"EVENT_LOG_TICKET_PATH_BINDING"
);
Ok(())
}
/// Internal mode admission. Failure emits only the main executable's fixed
/// initialization error; no request, query XML or private Win32 error is logged.
pub fn worker(path: &Path) -> Result<()> {
native::require_local_service()?;
service_token(unsafe { GetCurrentProcess() })?;
let image = std::env::current_exe()?;
let actual_parent = parent_pid()?;
ensure!(
agent_pid(&image)? == actual_parent,
"EVENT_LOG_REAL_PARENT_REQUIRED"
);
let parent = owned(unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
0,
actual_parent,
)
})?;
let parent_birth = birth(parent.as_raw_handle())?;
ensure!(
process_image(parent.as_raw_handle())? == image
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
"EVENT_LOG_PARENT_INSTANCE"
);
service_token(parent.as_raw_handle())?;
crate::job_binding::check_admin_readonly(Path::new(CONFIG))?;
let mut config_file = open_private(Path::new(CONFIG), false)?;
let config: WorkerConfig = serde_json::from_slice(&read(&mut config_file, 32768)?)?;
ensure!(
config.enable_jobs && config.state_directory.is_absolute(),
"EVENT_LOG_JOBS_NOT_ENABLED"
);
let directory = config.state_directory.join("jobs");
native::private_path(&directory, true)?;
validate_ticket_path(path, &directory)?;
// Only the exact jobs leaf is read; PKI/keys and arbitrary private files
// cannot be passed to this mode, even by another LocalService process.
let mut ticket_file = open_private(path, false)?;
let ticket: Ticket = serde_json::from_slice(&read(&mut ticket_file, TICKET_LIMIT)?)?;
ensure!(
ticket.parent_pid == actual_parent && ticket.parent_birth == parent_birth,
"EVENT_LOG_PARENT_INSTANCE"
);
let binding = crate::job_binding::readonly_binding(&config.job_binding_file)?;
let clock = crate::clock::NativeClock::new();
let now = clock.now()?;
let (job, permit) = binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
let query = event_log::for_job(&job)?;
let expected = config
.state_directory
.join("jobs")
.join(ticket_name(&permit));
ensure!(path == expected, "EVENT_LOG_TICKET_PATH_BINDING");
let runtime = tokio::runtime::Runtime::new()?;
ensure!(
Uuid::parse_str(&runtime.block_on(native::boot_id())?)? == ticket.boot,
"EVENT_LOG_ORIGINAL_BOOT_REQUIRED"
);
let ledger_path = config.state_directory.join("consumption.sqlite");
let ledger_file = open_private(&ledger_path, true)?;
ensure!(
file_id(ledger_file.as_raw_handle())? == ticket.ledger,
"EVENT_LOG_LEDGER_FILE_CHANGED"
);
let db = rusqlite::Connection::open_with_flags(
&ledger_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.busy_timeout(Duration::from_millis(100))?;
let mut sqlite_handle: HANDLE = ptr::null_mut();
ensure!(
unsafe {
rusqlite::ffi::sqlite3_file_control(
db.handle(),
c"main".as_ptr(),
rusqlite::ffi::SQLITE_FCNTL_WIN32_GET_HANDLE,
(&mut sqlite_handle as *mut HANDLE).cast(),
)
} == rusqlite::ffi::SQLITE_OK
&& file_id(sqlite_handle)? == ticket.ledger,
"EVENT_LOG_CONNECTED_LEDGER_FILE"
);
db.execute_batch("PRAGMA query_only=ON; BEGIN;")?;
consumed(&db, &binding, &ticket, &permit)?;
// Per-grant durable CAS prevents worker re-entry after a lost child reply.
let marker = path.with_extension("started");
let mut once = OpenOptions::new()
.create_new(true)
.write(true)
.share_mode(0)
.open(&marker)?;
once.write_all(b"event-log-dispatch-v1\n")?;
once.sync_all()?;
native::private_path(&marker, false)?;
// File I/O, CIM and child scheduling cannot extend the signed start window.
let now = clock.now()?;
binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
ensure!(
agent_pid(&image)? == actual_parent
&& birth(parent.as_raw_handle())? == ticket.parent_birth
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
"EVENT_LOG_PARENT_CHANGED"
);
consumed(&db, &binding, &ticket, &permit)?;
let report = event_log::query(&query, &AtomicBool::new(false))?;
let bytes = serde_json::to_vec(&report)?;
ensure!(
bytes.len() <= job.max_output_bytes as usize,
"EVENT_LOG_OUTPUT_LIMIT"
);
std::io::stdout().lock().write_all(&bytes)?;
Ok(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WireReport {
channel: String,
provider: String,
start_utc: DateTime<Utc>,
end_utc: DateTime<Utc>,
quality: String,
completeness: String,
truncated: bool,
error_code: Option<String>,
win32_error: Option<u32>,
events: Vec<event_log::Event>,
bookmark_updated: bool,
deadline_enforcement: String,
}
fn outcome(job: &JobPayload, bytes: Vec<u8>) -> Result<Outcome> {
let q = event_log::for_job(job)?;
ensure!(
bytes.len() <= q.max_output_bytes as usize,
"EVENT_LOG_OUTPUT_LIMIT"
);
let report: WireReport = serde_json::from_slice(&bytes)?;
ensure!(
report.channel == q.channel
&& report.provider == q.provider
&& report.start_utc == q.start_utc
&& report.end_utc == q.end_utc
&& !report.bookmark_updated
&& report.events.len() <= q.max_events as usize
&& report.deadline_enforcement == "cooperative_between_win32_calls",
"EVENT_LOG_REPORT_BINDING"
);
let mut ids = std::collections::BTreeSet::new();
for event in &report.events {
ensure!(
event.channel == q.channel
&& event.provider == q.provider
&& event.record_id > 0
&& ids.insert(event.record_id)
&& event.created_utc >= q.start_utc
&& event.created_utc < q.end_utc
&& event.xml.len() <= 64 * 1024
&& !event.xml.contains('\0'),
"EVENT_LOG_EVENT_BINDING"
);
}
let complete =
report.completeness == "complete" && !report.truncated && report.error_code.is_none();
let partial = report.completeness == "partial"
&& report.truncated
&& matches!(
report.error_code.as_deref(),
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
);
let success =
report.quality == "valid" && report.win32_error.is_none() && (complete || partial);
let error =
report
.error_code
.as_deref()
.unwrap_or(if success { "" } else { "EVENT_LOG_INCOMPLETE" });
Ok(Outcome {
state: if success { "succeeded" } else { "failed" }.into(),
stdout: bytes,
stderr: vec![],
exit_code: None,
output_truncated: report.truncated,
reboot_required: false,
error_code: if success { String::new() } else { error.into() },
evidence: serde_json::json!({"postconditions_passed":success,
"source_id":rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE,
"channel":q.channel,"provider":q.provider,"start_utc":q.start_utc,"end_utc":q.end_utc,
"max_events":q.max_events,"max_output_bytes":q.max_output_bytes,
"quality":report.quality,"completeness":report.completeness,"truncated":report.truncated,
"error_code":report.error_code,"win32_error":report.win32_error,
"bookmark_updated":false,"execution_sid":"S-1-5-19","process_tree_bounded":true,
"cursor_status":"not_advanced_no_ack_contract","observed_at":Utc::now()}),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn job() -> JobPayload {
let id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: rmm_domain::jobs::Action::QueryLogs {
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: now,
until: now + chrono::Duration::minutes(5),
max_lines: 2,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::seconds(60),
max_runtime_seconds: 10,
max_output_bytes: 4096,
}
}
#[test]
fn ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves() {
let directory = Path::new(r"C:\ProgramData\RustDiscovery\state\jobs");
let leaf = format!("eventlog-{}.json", "a".repeat(64));
assert!(validate_ticket_path(&directory.join(&leaf), directory).is_ok());
for path in [
PathBuf::from(r"C:\ProgramData\RustDiscovery\state\device-key.pem"),
directory.join("..\\jobs").join(&leaf),
directory.join(format!("eventlog-{}.json", "A".repeat(64))),
directory.join(format!("eventlog-{}.json", "a".repeat(63))),
directory.join(format!("eventlog-{}.json:stream", "a".repeat(64))),
directory.join("other.json"),
] {
assert!(
validate_ticket_path(&path, directory).is_err(),
"{}",
path.display()
);
}
}
#[test]
fn event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success() {
let job = job();
let q = event_log::for_job(&job).unwrap();
let mut report = serde_json::json!({"channel":q.channel,"provider":q.provider,
"start_utc":q.start_utc,"end_utc":q.end_utc,"quality":"valid",
"completeness":"complete","truncated":false,"error_code":null,"win32_error":null,
"events":[],"bookmark_updated":false,"deadline_enforcement":"cooperative_between_win32_calls"});
assert_eq!(
outcome(&job, serde_json::to_vec(&report).unwrap())
.unwrap()
.state,
"succeeded"
);
for code in [
"EVENT_LOG_TIME_LIMIT",
"EVENT_LOG_CANCELLED",
"EVENT_LOG_API_ERROR",
] {
let mut partial = report.clone();
partial["truncated"] = true.into();
partial["completeness"] = "unknown".into();
partial["error_code"] = code.into();
assert_eq!(
outcome(&job, serde_json::to_vec(&partial).unwrap())
.unwrap()
.state,
"failed"
);
}
report["truncated"] = true.into();
report["completeness"] = "partial".into();
report["error_code"] = "EVENT_LOG_BYTE_LIMIT".into();
let bounded = outcome(&job, serde_json::to_vec(&report).unwrap()).unwrap();
assert_eq!(bounded.state, "succeeded");
assert!(bounded.output_truncated);
report["quality"] = "permission_denied".into();
report["win32_error"] = 5.into();
assert_eq!(
outcome(&job, serde_json::to_vec(&report).unwrap())
.unwrap()
.state,
"failed"
);
report["provider"] = "another-provider".into();
assert!(outcome(&job, serde_json::to_vec(&report).unwrap()).is_err());
}
}
+113 -24
View File
@@ -7,6 +7,7 @@ use rmm_agent_core::{
};
use rmm_domain::jobs::hash;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha2::{Digest, Sha256};
use std::{
ffi::c_void,
fs::File,
@@ -29,7 +30,13 @@ use windows_sys::Win32::{
};
pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper";
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v1";
// Framing v2 is deliberately a separate endpoint. Old peers cannot send a
// v1 call to this server or interpret the drain receipt as another reply.
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
const FRAME_HEADER_LEN: usize = 12;
const DRAIN_RECEIPT_LEN: usize = 56;
pub const FRAME_LIMIT: usize = 1024 * 1024;
pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4
const READ_MASK: u32 = 0x0012_00a9;
@@ -44,6 +51,7 @@ pub enum Stage {
ClientSendFrame,
ClientReadReply,
ClientReplyBinding,
ClientDrainReceipt,
ClientReport,
ServerConnect,
ServerReadHeader,
@@ -54,6 +62,7 @@ pub enum Stage {
ServerCallBinding,
ServerRecheckPeer,
ServerReply,
ServerDrainReceipt,
Unclassified,
}
impl Stage {
@@ -66,6 +75,7 @@ impl Stage {
Self::ClientSendFrame => "client_send_frame",
Self::ClientReadReply => "client_read_reply",
Self::ClientReplyBinding => "client_reply_binding",
Self::ClientDrainReceipt => "client_drain_receipt",
Self::ClientReport => "client_report",
Self::ServerConnect => "server_connect",
Self::ServerReadHeader => "server_read_header",
@@ -76,6 +86,7 @@ impl Stage {
Self::ServerCallBinding => "server_call_binding",
Self::ServerRecheckPeer => "server_recheck_peer",
Self::ServerReply => "server_reply",
Self::ServerDrainReceipt => "server_drain_receipt",
Self::Unclassified => "unclassified",
}
}
@@ -123,6 +134,8 @@ fn known_code(text: &str) -> Option<&'static str> {
"HELPER_FRAME_CAPACITY",
"HELPER_FRAME_EMPTY",
"HELPER_FRAME_LENGTH",
"HELPER_FRAME_VERSION",
"HELPER_DRAIN_RECEIPT",
"HELPER_HANDLE",
"HELPER_IMAGE_PARENT",
"HELPER_IMAGE_SIZE",
@@ -1189,27 +1202,60 @@ fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY");
Ok(writer.0)
}
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
let mut bytes = encode(value)?;
let mut header = u32::try_from(bytes.len())?.to_be_bytes();
transfer(pipe, &mut header, true, deadline)?;
transfer(pipe, &mut bytes, true, deadline)
fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
let mut header = [0; FRAME_HEADER_LEN];
header[..8].copy_from_slice(&FRAME_TAG);
header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes());
Ok(header)
}
fn frame_length(header: [u8; 4]) -> Result<usize> {
let len = u32::from_be_bytes(header) as usize;
fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
let mut header = frame_header(bytes.len())?;
transfer(pipe, &mut header, true, deadline)?;
transfer(pipe, bytes, true, deadline)
}
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
send_bytes(pipe, &mut encode(value)?, deadline)
}
fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
ensure!(header[..8] == FRAME_TAG, "HELPER_FRAME_VERSION");
let len = u32::from_be_bytes(header[8..].try_into()?) as usize;
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
Ok(len)
}
fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
let mut header = [0u8; 4];
let mut header = [0u8; FRAME_HEADER_LEN];
transfer(pipe, &mut header, false, deadline)?;
frame_length(header)
}
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
let mut bytes = vec![0u8; len];
transfer(pipe, &mut bytes, false, deadline)?;
Ok(serde_json::from_slice(&bytes)?)
Ok(bytes)
}
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?)
}
// This fixed-size receipt only acknowledges receipt of these transport bytes.
// It never acknowledges durable evidence, clears state, or permits an effect.
fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
let mut receipt = [0; DRAIN_RECEIPT_LEN];
receipt[..8].copy_from_slice(&DRAIN_TAG);
receipt[8..24].copy_from_slice(challenge.as_bytes());
receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes));
receipt
}
fn verify_drain_receipt(
receipt: &[u8; DRAIN_RECEIPT_LEN],
challenge: Uuid,
reply_bytes: &[u8],
) -> Result<()> {
ensure!(
*receipt == drain_receipt(challenge, reply_bytes),
"HELPER_DRAIN_RECEIPT"
);
Ok(())
}
pub struct Server {
@@ -1305,13 +1351,24 @@ impl Server {
peer.check().context(Stage::ServerRecheckPeer)?;
Ok(Some(Received { call, peer }))
}
pub fn reply(&self, value: &Reply) -> Result<()> {
send(
self.pipe.as_raw_handle(),
value,
Instant::now() + Duration::from_secs(5),
)
.context(Stage::ServerReply)
pub fn reply(&self, value: &Reply, peer: &mut PeerProof) -> Result<()> {
// Do not disconnect after WriteFile merely copied bytes into a pipe
// buffer. Wait for a receipt from the same fully pinned peer within
// the original reply deadline, without an unbounded FlushFileBuffers.
let deadline = Instant::now() + Duration::from_secs(5);
peer.check().context(Stage::ServerRecheckPeer)?;
let mut bytes = encode(value).context(Stage::ServerReply)?;
send_bytes(self.pipe.as_raw_handle(), &mut bytes, deadline).context(Stage::ServerReply)?;
let mut receipt = [0; DRAIN_RECEIPT_LEN];
transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline)
.context(Stage::ServerDrainReceipt)?;
verify_drain_receipt(&receipt, value.challenge, &bytes)
.context(Stage::ServerDrainReceipt)?;
peer.check().context(Stage::ServerRecheckPeer)?;
if Instant::now() >= deadline {
return Err(anyhow::anyhow!("HELPER_PIPE_TIMEOUT")).context(Stage::ServerDrainReceipt);
}
Ok(())
}
pub fn disconnect(&self) {
unsafe {
@@ -1345,7 +1402,9 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
.context(Stage::ClientHelperPeer)?;
send(pipe.as_raw_handle(), call, deadline).context(Stage::ClientSendFrame)?;
let len = length(pipe.as_raw_handle(), deadline).context(Stage::ClientReadReply)?;
let reply: Reply = body(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
let reply_bytes =
body_bytes(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
let reply: Reply = serde_json::from_slice(&reply_bytes).context(Stage::ClientReadReply)?;
peer.check().context(Stage::ClientHelperPeer)?;
if !(reply.schema_version == 1
&& reply.challenge == call.challenge
@@ -1366,6 +1425,11 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
) {
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
}
// Only a complete, authenticated, bound and operation-checked reply gets
// this receipt. Hash the received bytes, never a JSON re-serialization.
let mut receipt = drain_receipt(call.challenge, &reply_bytes);
transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)
.context(Stage::ClientDrainReceipt)?;
Ok(reply)
}
@@ -1388,12 +1452,21 @@ mod tests {
#[test]
fn untrusted_lengths_are_rejected_before_body_allocation() {
for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] {
assert!(frame_length(n.to_be_bytes()).is_err());
let mut header = [0; FRAME_HEADER_LEN];
header[..8].copy_from_slice(&FRAME_TAG);
header[8..].copy_from_slice(&n.to_be_bytes());
assert!(frame_length(header).is_err());
assert!(frame_header(n as usize).is_err());
}
assert_eq!(
frame_length((FRAME_LIMIT as u32).to_be_bytes()).unwrap(),
FRAME_LIMIT
);
let header = frame_header(FRAME_LIMIT).unwrap();
assert_eq!(frame_length(header).unwrap(), FRAME_LIMIT);
// Neither a v1 length prefix nor another framing version is accepted.
let mut old = [0; FRAME_HEADER_LEN];
old[..4].copy_from_slice(&1u32.to_be_bytes());
assert!(frame_length(old).is_err());
let mut foreign = header;
foreign[7] = b'1';
assert!(frame_length(foreign).is_err());
}
#[test]
fn protocol_does_not_accept_a_shell_operation() {
@@ -1417,6 +1490,22 @@ mod tests {
assert_eq!(diagnostic(&caller).code, "UNCLASSIFIED_IO_OR_CODEC");
let remote = remote_denial(Stage::ClientReplyBinding, "caller-payload-private-marker");
assert_eq!(diagnostic(&remote).code, "UNCLASSIFIED_REMOTE_DENIAL");
let challenge = Uuid::from_u128(1);
let raw = br#"{"a":1,"b":2}"#;
let receipt = drain_receipt(challenge, raw);
assert!(verify_drain_receipt(&receipt, challenge, raw).is_ok());
// Same JSON meaning, different exact bytes must not drain this reply.
assert!(verify_drain_receipt(&receipt, challenge, br#"{"b":2,"a":1}"#).is_err());
assert!(verify_drain_receipt(&receipt, Uuid::from_u128(2), raw).is_err());
for offset in [0, 7, 8, 23, 24, DRAIN_RECEIPT_LEN - 1] {
let mut changed = receipt;
changed[offset] ^= 1;
let error = verify_drain_receipt(&changed, challenge, raw)
.unwrap_err()
.context(Stage::ServerDrainReceipt);
assert_eq!(diagnostic(&error).code, "HELPER_DRAIN_RECEIPT");
assert_eq!(diagnostic(&error).stage, "server_drain_receipt");
}
}
#[test]
fn reconfigured_service_cannot_adopt_an_old_running_identity() {
+1 -1
View File
@@ -1179,7 +1179,7 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
match server.receive() {
Ok(Some(mut incoming)) => {
let reply = helper.handle(&incoming.call, &mut incoming.peer);
if let Err(error) = server.reply(&reply) {
if let Err(error) = server.reply(&reply, &mut incoming.peer) {
if let Some(sync) = &mut helper.sync {
sync.close();
}
-122
View File
@@ -1,122 +0,0 @@
//! Shared protected public signing binding; never learns trust from a worker ticket.
use crate::native;
use anyhow::{Context, Result, ensure};
use rmm_agent_core::auth::Binding;
use std::path::Path;
fn read_private(path: &Path, limit: u64) -> Result<Vec<u8>> {
use std::{fs::OpenOptions, io::Read, os::windows::fs::OpenOptionsExt};
use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ};
native::private_path(path, false)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
ensure!(file.metadata()?.len() <= limit, "BINDING_SIZE");
let mut bytes = Vec::new();
(&mut file).take(limit + 1).read_to_end(&mut bytes)?;
ensure!(bytes.len() as u64 <= limit, "BINDING_SIZE");
Ok(bytes)
}
pub fn check_admin_readonly(path: &Path) -> Result<()> {
use std::ptr;
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
self, ACCESS_ALLOWED_ACE, ACL,
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
},
};
unsafe fn sid(sid: Security::PSID) -> Result<String> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
"BINDING_SID"
);
let mut len = 0;
while unsafe { *raw.add(len) } != 0 {
len += 1;
ensure!(len < 256, "BINDING_SID_LIMIT");
}
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
unsafe {
LocalFree(raw.cast());
}
Ok(value)
}
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
// The immediate configuration directory must also deny agent replacement.
for (item, directory) in [
(path, false),
(path.parent().context("BINDING_PARENT")?, true),
] {
native::private_path(item, directory)?;
let mut owner = ptr::null_mut();
let mut dacl: *mut ACL = ptr::null_mut();
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetNamedSecurityInfoW(
native::wide(item).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, "BINDING_SECURITY");
let check = (|| -> Result<()> {
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
ensure!(
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
"BINDING_ADMIN_OWNER_REQUIRED"
);
for index in 0..unsafe { (*dacl).AceCount } {
let mut raw = ptr::null_mut();
ensure!(
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
"BINDING_ACE"
);
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& usize::from(ace.Header.AceSize)
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
"BINDING_ACE_TYPE"
);
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
}
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
check?;
}
Ok(())
}
pub fn readonly_binding(path: &Path) -> Result<Binding> {
check_admin_readonly(path)?;
let binding: Binding = serde_json::from_slice(&read_private(path, 8192)?)?;
ensure!(
!binding.tenant_id.is_nil()
&& !binding.agent_id.is_nil()
&& !binding.asset_id.is_nil()
&& binding.enrollment_generation > 0
&& binding.assignment_version > 0
&& binding.public_key_hex.len() == 64
&& binding
.public_key_hex
.bytes()
.all(|b| b.is_ascii_hexdigit()),
"JOB_BINDING_PROFILE"
);
Ok(binding)
}
-5
View File
@@ -4,9 +4,6 @@
pub mod actions;
#[cfg(windows)]
pub mod clock;
pub mod event_log;
#[cfg(windows)]
pub mod event_log_job;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_ipc;
#[cfg(all(windows, feature = "system-helper"))]
@@ -15,8 +12,6 @@ pub mod helper_runtime;
pub mod helper_system;
#[cfg(windows)]
pub mod inventory;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
#[cfg(windows)]
pub mod native;
+114 -26
View File
@@ -7,7 +7,7 @@ use rmm_agent_core::{
jobs, ledger,
reconcile::{self, SyncClock},
};
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension};
@@ -216,6 +216,104 @@ fn verified_window(
binding.verify(request, now + chrono::Duration::seconds(2))?;
Ok(result)
}
fn readonly_binding(path: &Path) -> Result<Binding> {
use std::ptr;
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
self, ACCESS_ALLOWED_ACE, ACL,
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
},
};
unsafe fn sid(sid: Security::PSID) -> Result<String> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
"BINDING_SID"
);
let mut len = 0;
while unsafe { *raw.add(len) } != 0 {
len += 1;
ensure!(len < 256, "BINDING_SID_LIMIT");
}
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
unsafe {
LocalFree(raw.cast());
}
Ok(value)
}
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
// The immediate configuration directory must also deny agent replacement.
for (item, directory) in [
(path, false),
(path.parent().context("BINDING_PARENT")?, true),
] {
native::private_path(item, directory)?;
let mut owner = ptr::null_mut();
let mut dacl: *mut ACL = ptr::null_mut();
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetNamedSecurityInfoW(
native::wide(item).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, "BINDING_SECURITY");
let check = (|| -> Result<()> {
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
ensure!(
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
"BINDING_ADMIN_OWNER_REQUIRED"
);
for index in 0..unsafe { (*dacl).AceCount } {
let mut raw = ptr::null_mut();
ensure!(
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
"BINDING_ACE"
);
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& usize::from(ace.Header.AceSize)
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
"BINDING_ACE_TYPE"
);
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
}
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
check?;
}
let binding: Binding = serde_json::from_slice(&protected_read(path, 8192)?)?;
ensure!(
!binding.tenant_id.is_nil()
&& !binding.agent_id.is_nil()
&& !binding.asset_id.is_nil()
&& binding.enrollment_generation > 0
&& binding.assignment_version > 0
&& binding.public_key_hex.len() == 64
&& binding
.public_key_hex
.bytes()
.all(|b| b.is_ascii_hexdigit()),
"JOB_BINDING_PROFILE"
);
Ok(binding)
}
fn import_legacy_inventory(journal: &mut Journal) -> Result<()> {
let original = {
let mut q = journal
@@ -586,8 +684,6 @@ impl Agent {
{
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
if rmm_agent_windows::actions::powershell().is_ok() {
// The process_remote_signed profile is implemented but remains
// unpublished until its separate native qualification passes.
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
}
}
@@ -1066,7 +1162,6 @@ impl Agent {
let directory = self.config.state_directory.join("jobs");
let work_offer = offer.clone();
let work_grant = grant.clone();
let original_boot = Uuid::parse_str(&self.boot)?;
let worker = tokio::task::spawn_blocking(move || {
let outcome = (|| -> Result<Outcome> {
if !fence.allows(generation, &clock)
@@ -1077,24 +1172,17 @@ impl Agent {
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
));
}
let prepared = match rmm_agent_windows::actions::PreparedAction::prepare(
&job,
&directory,
work_grant.grant_id,
&request,
original_boot,
) {
Ok(prepared) => prepared,
Err(_) => {
return Ok(jobs::no_start(
"failed",
if matches!(job.action, Action::RunScript { .. }) {
"SCRIPT_PREPARATION_FAILED"
} else {
"ACTION_PREPARATION_FAILED"
},
));
let script = if matches!(job.action, Action::RunScript { .. }) {
match rmm_agent_windows::actions::Script::prepare(
&job,
&directory,
work_grant.grant_id,
) {
Ok(script) => Some(script),
Err(_) => return Ok(jobs::no_start("failed", "SCRIPT_PREPARATION_FAILED")),
}
} else {
None
};
// File creation, pool scheduling and fsync never extend a start window.
if worker_cancel.load(Ordering::SeqCst) {
@@ -1108,7 +1196,11 @@ impl Agent {
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
));
}
prepared.run(&job, &worker_cancel)
if let Some(script) = script {
script.run(&job, &worker_cancel)
} else {
rmm_agent_windows::actions::inventory(&job)
}
})()
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
let _ = completed.blocking_send((work_offer, work_grant, outcome));
@@ -1455,10 +1547,6 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
}
pub fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some(rmm_agent_windows::event_log_job::MODE) {
ensure!(args.len() == 2, "EVENT_LOG_WORKER_ARGUMENTS");
return rmm_agent_windows::event_log_job::worker(Path::new(&args[1]));
}
if args == ["--help"] {
println!(
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
-1
View File
@@ -353,7 +353,6 @@ mod tests {
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
-1
View File
@@ -50,7 +50,6 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
script_utf8: "printf 'fixture only; never executed\\n'".into(),
arguments: vec![],
expected_stdout: Some("fixture only; never executed\n".into()),
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
-1
View File
@@ -594,7 +594,6 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+5 -266
View File
@@ -1,6 +1,5 @@
//! Version 1 codec: UTF-8 compact serde JSON of these structs, declaration field
//! order, explicit null legacy options (new opt-in fields omit None), ordered vectors,
//! UTC RFC3339 timestamps. Hash the
//! order, explicit null options, ordered vectors, UTC RFC3339 timestamps. Hash the
//! stored bytes, never a reconstructed API view. No floating point/map payloads.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
@@ -14,40 +13,6 @@ pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(value)
}
/// One explicitly qualified Event Log source, not an arbitrary channel/XPath.
pub const WINDOWS_EVENT_LOG_FIXTURE_SOURCE: &str =
"windows.eventlog.application.rustdiscovery-mvp-test";
pub const WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY: &str = "logs.windows.eventlog.fixture/1";
pub const WINDOWS_EVENT_LOG_FIXTURE_CHANNEL: &str = "Application";
pub const WINDOWS_EVENT_LOG_FIXTURE_PROVIDER: &str = "RustDiscovery-MVP-Test";
/// Fixed per-job Windows PowerShell 5.1 option, never a machine/GPO policy.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
pub enum WindowsExecutionProfile {
#[serde(rename = "powershell_51_remote_signed")]
PowerShell51RemoteSigned,
}
/// A missing field uses serde's default None. A present field must be the exact
/// string: null and serde's externally-tagged enum object form are not profiles.
pub fn deserialize_windows_execution_profile<'de, D>(
deserializer: D,
) -> Result<Option<WindowsExecutionProfile>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
"powershell_51_remote_signed" => {
Ok(Some(WindowsExecutionProfile::PowerShell51RemoteSigned))
}
_ => Err(serde::de::Error::unknown_variant(
&value,
&["powershell_51_remote_signed"],
)),
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
@@ -56,13 +21,6 @@ pub enum Action {
script_utf8: String,
arguments: Vec<String>,
expected_stdout: Option<String>,
#[serde(
default,
deserialize_with = "deserialize_windows_execution_profile",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "WindowsExecutionProfile")]
windows_execution_profile: Option<WindowsExecutionProfile>,
},
RefreshInventory {
scope: String,
@@ -141,10 +99,8 @@ impl Action {
script_utf8,
arguments,
expected_stdout,
windows_execution_profile,
} => {
matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell")
&& (windows_execution_profile.is_none() || interpreter == "powershell")
&& (interpreter != "powershell"
|| script_utf8.is_ascii()
|| script_utf8.starts_with('\u{feff}'))
@@ -168,8 +124,7 @@ impl Action {
} => {
unit(u)
&& since < until
&& *until - *since <= chrono::Duration::hours(24)
&& (u != WINDOWS_EVENT_LOG_FIXTURE_SOURCE || since.timestamp() >= 0)
&& (*until - *since).num_hours() <= 24
&& *max_lines > 0
&& *max_lines <= 1000
}
@@ -243,18 +198,6 @@ impl Action {
}
}
}
pub fn is_windows_event_log_fixture(&self) -> bool {
matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE)
}
/// The outer process budget includes authenticated worker startup/cleanup;
/// its inner Event Log calls retain their own cooperative <=5s deadline.
pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool {
(1..=3600).contains(&runtime_seconds)
&& (1..=262144).contains(&output_bytes)
&& (!self.is_windows_event_log_fixture()
|| ((10..=120).contains(&runtime_seconds)
&& (1024..=65536).contains(&output_bytes)))
}
/// Interpreter identity is part of the immutable action, never inferred at execution.
pub fn script_platform(&self) -> Option<&'static str> {
match self {
@@ -276,25 +219,15 @@ impl Action {
return false;
}
match self {
Self::RunScript {
interpreter,
windows_execution_profile,
..
} if interpreter == "powershell" => {
Self::RunScript { interpreter, .. } if interpreter == "powershell" => {
identity == "agent_service"
&& has("windows.base/1")
&& !has("linux.base/1")
&& has("rmm.sync.v1")
&& has("script.powershell/1")
&& (windows_execution_profile.is_none()
|| has("script.powershell.process_remote_signed/1"))
}
Self::RunScript {
windows_execution_profile,
..
} => {
windows_execution_profile.is_none()
&& self.script_platform() == Some("linux")
Self::RunScript { .. } => {
self.script_platform() == Some("linux")
&& has("linux.base/1")
&& !has("windows.base/1")
}
@@ -304,16 +237,6 @@ impl Action {
&& !(has("linux.base/1") && has("windows.base/1"))
&& (scope != "windows.base" || has("rmm.sync.v1"))
}
Self::QueryLogs { unit, .. }
if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE || has("windows.base/1") =>
{
identity == "agent_service"
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
&& has("windows.base/1")
&& !has("linux.base/1")
&& has("rmm.sync.v1")
&& has(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY)
}
Self::SetServiceState { state, .. }
if identity == "system" || has("windows.base/1") =>
{
@@ -573,7 +496,6 @@ mod tests {
script_utf8: "Write-Output 'hi'\r\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
let mut all = caps;
all.extend(["run_script".into(), "script.powershell/1".into()]);
@@ -583,7 +505,6 @@ mod tests {
script_utf8: "printf hi\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
let reboot = Action::Reboot {
reason: "fixed test".into(),
@@ -605,7 +526,6 @@ mod tests {
script_utf8: "Write-Output 'Hello'\r\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\r\n".into()),
windows_execution_profile: None,
};
let caps: Vec<String> = [
"windows.base/1",
@@ -681,7 +601,6 @@ mod tests {
script_utf8: "echo hi\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
assert_eq!(
String::from_utf8(encode(&a).unwrap()).unwrap(),
@@ -694,186 +613,6 @@ mod tests {
);
}
#[test]
fn windows_remote_signed_profile_is_optional_exact_and_capability_bound() {
let schema = schemars::schema_for!(Action).to_value();
let script_schema = schema["oneOf"]
.as_array()
.unwrap()
.iter()
.find(|variant| {
variant["properties"]
.get("windows_execution_profile")
.is_some()
})
.unwrap();
assert_eq!(
script_schema["properties"]["windows_execution_profile"],
serde_json::json!({"$ref":"#/$defs/WindowsExecutionProfile"})
);
assert!(
!script_schema["required"]
.as_array()
.unwrap()
.contains(&serde_json::json!("windows_execution_profile"))
);
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
let legacy = br#"{"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 'hi'\r\n","arguments":[],"expected_stdout":null}"#;
let mut action: Action = serde_json::from_slice(legacy).unwrap();
assert_eq!(encode(&action).unwrap(), legacy);
let inherited_hash = hash(legacy);
if let Action::RunScript {
windows_execution_profile,
..
} = &mut action
{
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
}
let encoded = encode(&action).unwrap();
assert_eq!(
String::from_utf8(encoded.clone()).unwrap(),
String::from_utf8(legacy[..legacy.len() - 1].to_vec()).unwrap()
+ r#","windows_execution_profile":"powershell_51_remote_signed"}"#
);
assert_ne!(hash(&encoded), inherited_hash);
assert_eq!(serde_json::from_slice::<Action>(&encoded).unwrap(), action);
let caps: Vec<String> = [
"windows.base/1",
"rmm.sync.v1",
"run_script",
"script.powershell/1",
"script.powershell.process_remote_signed/1",
]
.into_iter()
.map(str::to_string)
.collect();
assert!(action.validate());
assert!(action.available_for("agent_service", &caps));
for missing in 0..caps.len() {
let mut short = caps.clone();
short.remove(missing);
assert!(!action.available_for("agent_service", &short));
}
for identity in ["root", "system", "SYSTEM"] {
assert!(!action.available_for(identity, &caps));
}
let mut mixed = caps.clone();
mixed.push("linux.base/1".into());
assert!(!action.available_for("agent_service", &mixed));
for interpreter in ["posix_sh", "bash", "pwsh"] {
let mut invalid = action.clone();
if let Action::RunScript { interpreter: i, .. } = &mut invalid {
*i = interpreter.into();
}
assert!(!invalid.validate());
assert!(!invalid.available_for("agent_service", &caps));
assert!(!invalid.available_for("root", &["linux.base/1".into(), "run_script".into()]));
}
for profile in [
serde_json::Value::Null,
serde_json::json!(false),
serde_json::json!(1),
serde_json::json!([]),
serde_json::json!({}),
serde_json::json!({"powershell_51_remote_signed": null}),
serde_json::json!("bypass"),
serde_json::json!("RemoteSigned"),
serde_json::json!("powershell_7_remote_signed"),
] {
let mut bad = serde_json::to_value(&action).unwrap();
bad["windows_execution_profile"] = profile.clone();
assert!(serde_json::from_value::<Action>(bad).is_err(), "{profile}");
// An opt-in profile is also never metadata on another action.
assert!(
serde_json::from_value::<Action>(serde_json::json!({
"action":"refresh_inventory", "scope":"windows.base",
"windows_execution_profile":profile
}))
.is_err()
);
}
}
#[test]
fn windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes() {
let since = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let mut action = Action::QueryLogs {
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since,
until: since + chrono::Duration::hours(24),
max_lines: 1000,
};
let caps: Vec<String> = [
"windows.base/1",
"rmm.sync.v1",
"query_logs",
WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY,
]
.into_iter()
.map(str::to_string)
.collect();
assert!(action.validate());
assert!(action.available_for("agent_service", &caps));
assert!(action.valid_job_limits(10, 1024));
assert!(action.valid_job_limits(120, 65536));
for (runtime, bytes) in [(9, 1024), (121, 1024), (10, 1023), (10, 65537)] {
assert!(!action.valid_job_limits(runtime, bytes));
}
for i in 0..caps.len() {
let mut short = caps.clone();
short.remove(i);
assert!(!action.available_for("agent_service", &short));
}
for identity in ["root", "system", "SYSTEM"] {
assert!(!action.available_for(identity, &caps));
}
let mut mixed = caps.clone();
mixed.push("linux.base/1".into());
assert!(!action.available_for("agent_service", &mixed));
assert!(!action.available_for("root", &["linux.base/1".into(), "query_logs".into()]));
for unit in [
"Application",
"Security",
"windows.eventlog.application.other",
] {
let mut wrong = action.clone();
if let Action::QueryLogs { unit: u, .. } = &mut wrong {
*u = unit.into();
}
assert!(!wrong.available_for("agent_service", &caps));
}
if let Action::QueryLogs { until, .. } = &mut action {
*until += chrono::Duration::nanoseconds(1);
}
assert!(!action.validate());
let linux = Action::QueryLogs {
unit: "rmm-test.service".into(),
since,
until: since + chrono::Duration::hours(24),
max_lines: 1000,
};
assert_eq!(
String::from_utf8(encode(&linux).unwrap()).unwrap(),
r#"{"action":"query_logs","unit":"rmm-test.service","since":"2026-11-14T00:00:00Z","until":"2026-11-15T00:00:00Z","max_lines":1000}"#
);
assert!(linux.validate());
for identity in ["root", "agent_service"] {
assert!(linux.available_for(identity, &["linux.base/1".into(), "query_logs".into()]));
}
let mut too_long = linux;
if let Action::QueryLogs { until, .. } = &mut too_long {
*until += chrono::Duration::minutes(59);
}
assert!(!too_long.validate());
let pre_epoch = Action::QueryLogs {
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: DateTime::from_timestamp(-1, 0).unwrap(),
until: DateTime::from_timestamp(0, 0).unwrap(),
max_lines: 1,
};
assert!(!pre_epoch.validate());
}
#[test]
fn no_terminal_replay_or_unknown_restart() {
assert!(!JobState::Succeeded.allows(JobState::Running));
assert!(!JobState::Unknown.allows(JobState::Running));
@@ -481,7 +481,6 @@ fn signed_request() -> (
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now - chrono::Duration::seconds(1),
-1
View File
@@ -130,7 +130,6 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
script_utf8,
arguments,
expected_stdout,
windows_execution_profile: None,
} = &job.action
else {
anyhow::bail!("NOT_SCRIPT")
-1
View File
@@ -750,7 +750,6 @@ mod tests {
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
-1
View File
@@ -33,7 +33,6 @@ fn fixture() -> (
script_utf8: "printf 'Hello World\\n'".into(),
arguments: vec![],
expected_stdout: Some("Hello World\n".into()),
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now - chrono::Duration::seconds(60),
@@ -432,7 +432,6 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
-1
View File
@@ -518,7 +518,6 @@ mod tests {
script_utf8: "printf hello\\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: c.issued_at,
-231
View File
@@ -191,8 +191,6 @@ pub async fn event(
ensure!(r.stdout == expected.as_bytes(), "expected output mismatch");
}
}
script_profile_evidence(&payload.action, &evidence)?;
windows_event_log_success_evidence(&payload, r, &evidence)?;
if matches!(payload.action, Action::Reboot { .. }) {
crate::synchronization::verify_reboot_success(
tx, tenant, agent, e, &payload, r, &evidence,
@@ -226,226 +224,6 @@ pub async fn event(
.await?;
Ok(())
}
fn windows_event_log_success_evidence(
job: &JobPayload,
result: &JobResult,
evidence: &Value,
) -> Result<()> {
if !job.action.is_windows_event_log_fixture() {
return Ok(());
}
let Action::QueryLogs {
unit,
since,
until,
max_lines,
} = &job.action
else {
anyhow::bail!("fixed event log action required")
};
let observed_since: chrono::DateTime<Utc> = serde_json::from_value(
evidence
.get("start_utc")
.cloned()
.context("event log start missing")?,
)?;
let observed_until: chrono::DateTime<Utc> = serde_json::from_value(
evidence
.get("end_utc")
.cloned()
.context("event log end missing")?,
)?;
let complete = evidence.get("completeness") == Some(&json!("complete"))
&& evidence.get("truncated") == Some(&json!(false))
&& evidence.get("error_code") == Some(&Value::Null);
let partial = evidence.get("completeness") == Some(&json!("partial"))
&& evidence.get("truncated") == Some(&json!(true))
&& matches!(
evidence.get("error_code").and_then(Value::as_str),
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
);
ensure!(
!result.reboot_required
&& evidence.get("truncated") == Some(&json!(result.output_truncated))
&& job.execution_identity == "agent_service"
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& evidence.get("source_id") == Some(&json!(unit))
&& evidence.get("channel") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_CHANNEL))
&& evidence.get("provider") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_PROVIDER))
&& observed_since == *since
&& observed_until == *until
&& evidence.get("max_events") == Some(&json!(max_lines))
&& evidence.get("max_output_bytes") == Some(&json!(job.max_output_bytes))
&& evidence.get("quality") == Some(&json!("valid"))
&& evidence.get("win32_error") == Some(&Value::Null)
&& evidence.get("bookmark_updated") == Some(&json!(false))
&& evidence.get("process_tree_bounded") == Some(&json!(true))
&& evidence.get("execution_sid") == Some(&json!("S-1-5-19"))
&& (complete || partial),
"fixed Windows Event Log evidence mismatch"
);
Ok(())
}
// The profile records the requested process option, never an effective GPO policy.
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
if let Action::RunScript {
script_utf8,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
..
} = action
{
ensure!(
evidence.get("windows_execution_profile")
== Some(&json!("powershell_51_remote_signed"))
&& evidence.get("execution_policy")
== Some(&json!("process_remote_signed_requested"))
&& evidence.get("execution_policy_requested") == Some(&json!("RemoteSigned"))
&& evidence.get("execution_policy_scope") == Some(&json!("process"))
&& evidence.get("script_sha256") == Some(&json!(hash(script_utf8.as_bytes()))),
"requested Windows process profile evidence mismatch"
);
}
Ok(())
}
#[cfg(test)]
mod script_profile_tests {
use super::*;
#[test]
fn windows_event_log_success_binds_request_and_keeps_limit_partial_honest() {
let id = Uuid::new_v4();
let now = Utc::now();
let job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: Action::QueryLogs {
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: now - Duration::hours(1),
until: now,
max_lines: 1000,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + Duration::minutes(1),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let evidence = json!({"source_id":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"channel":"Application","provider":"RustDiscovery-MVP-Test","start_utc":now-Duration::hours(1),"end_utc":now,"max_events":1000,"max_output_bytes":4096,"quality":"valid","completeness":"complete","truncated":false,"error_code":null,"win32_error":null,"bookmark_updated":false,"process_tree_bounded":true,"execution_sid":"S-1-5-19"});
let result = JobResult::default();
windows_event_log_success_evidence(&job, &result, &evidence).unwrap();
for conflicting in [
JobResult {
reboot_required: true,
..Default::default()
},
JobResult {
output_truncated: true,
..Default::default()
},
] {
assert!(windows_event_log_success_evidence(&job, &conflicting, &evidence).is_err());
}
for field in [
"source_id",
"channel",
"provider",
"start_utc",
"end_utc",
"max_events",
"max_output_bytes",
"quality",
"win32_error",
"bookmark_updated",
"process_tree_bounded",
"execution_sid",
] {
let mut bad = evidence.clone();
bad[field] = json!("different");
assert!(
windows_event_log_success_evidence(&job, &result, &bad).is_err(),
"{field}"
);
}
for code in [
"EVENT_LOG_EVENT_LIMIT",
"EVENT_LOG_BYTE_LIMIT",
"EVENT_LOG_EVENT_SIZE_LIMIT",
] {
let mut partial = evidence.clone();
partial["completeness"] = json!("partial");
partial["truncated"] = json!(true);
partial["error_code"] = json!(code);
let partial_result = JobResult {
output_truncated: true,
..Default::default()
};
windows_event_log_success_evidence(&job, &partial_result, &partial).unwrap();
assert!(windows_event_log_success_evidence(&job, &result, &partial).is_err());
partial["error_code"] = json!("EVENT_LOG_TIMEOUT");
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
partial["quality"] = json!("permission_denied");
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
}
let mut permission_denied = evidence.clone();
permission_denied["win32_error"] = json!(5);
assert!(windows_event_log_success_evidence(&job, &result, &permission_denied).is_err());
let mut false_complete = evidence.clone();
false_complete["truncated"] = json!(true);
assert!(windows_event_log_success_evidence(&job, &result, &false_complete).is_err());
}
#[test]
fn requested_profile_success_evidence_is_exact_without_effective_policy_claim() {
let mut action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'hi'\r\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
};
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
"execution_policy_scope":"process", "script_sha256":hash(b"Write-Output 'hi'\r\n")});
script_profile_evidence(&action, &evidence).unwrap();
for field in [
"windows_execution_profile",
"execution_policy",
"execution_policy_requested",
"execution_policy_scope",
"script_sha256",
] {
let mut changed = evidence.clone();
changed.as_object_mut().unwrap().remove(field);
assert!(
script_profile_evidence(&action, &changed).is_err(),
"{field}"
);
changed[field] = json!("different");
assert!(
script_profile_evidence(&action, &changed).is_err(),
"{field}"
);
}
if let Action::RunScript {
windows_execution_profile,
..
} = &mut action
{
*windows_execution_profile = None;
}
script_profile_evidence(&action, &json!({})).unwrap();
}
}
async fn locked_job(
tx: &mut Transaction<'_, Postgres>,
agent: Uuid,
@@ -536,12 +314,6 @@ pub async fn permit(
return Ok(denied("BINDING_MISMATCH"));
}
let now = Utc::now();
if !payload
.action
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
{
return Ok(denied("INVALID_JOB_LIMITS"));
}
if !payload.action.validate() {
return Ok(denied("APT_MANIFEST_REQUIRED"));
}
@@ -739,9 +511,6 @@ pub async fn next(
if !payload
.action
.available_for(&payload.execution_identity, &caps)
|| !payload
.action
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
{
tx.commit().await?;
return Ok(None);
+1 -314
View File
@@ -151,13 +151,6 @@ pub struct Variant {
interpreter: String,
encoding: String,
script_utf8: String,
#[serde(
default,
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "WindowsExecutionProfile")]
windows_execution_profile: Option<WindowsExecutionProfile>,
}
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
@@ -220,7 +213,6 @@ impl PlanRequest {
script_utf8: v.script_utf8.clone(),
arguments: p.arguments.clone().unwrap_or_default(),
expected_stdout: p.expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
}
}
"refresh_inventory" => Action::RefreshInventory {
@@ -318,7 +310,6 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
script_utf8: v.script_utf8.clone(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: v.windows_execution_profile,
};
if v.encoding != "utf-8"
|| action.script_platform() != Some(v.os_family.as_str())
@@ -345,21 +336,12 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
script_utf8,
arguments,
expected_stdout,
windows_execution_profile,
} = &input.action
else {
return Err(fail("VALIDATION_ERROR"));
};
let first = &input.script_variants[0];
if interpreter != &first.interpreter
|| script_utf8 != &first.script_utf8
|| windows_execution_profile != &first.windows_execution_profile
|| (input.execution_identity != "agent_service"
&& input
.script_variants
.iter()
.any(|v| v.windows_execution_profile.is_some()))
{
if interpreter != &first.interpreter || script_utf8 != &first.script_utf8 {
return Err(fail("VALIDATION_ERROR"));
}
let platform = match (
@@ -380,7 +362,6 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
script_utf8: v.script_utf8.clone(),
arguments: arguments.clone(),
expected_stdout: expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
})
}
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
@@ -472,9 +453,6 @@ pub async fn plan(
let row = &rows[0];
let caps = capabilities(row.get("capabilities"))?;
let action = target_action(&input, &caps)?;
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
return Err(fail("VALIDATION_ERROR"));
}
if !action.available_for(&input.execution_identity, &caps) {
return Err(fail("UNSUPPORTED_CAPABILITY"));
}
@@ -602,12 +580,6 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
}
let mut references = Vec::new();
for job in &plan.jobs {
if !job.payload.action.valid_job_limits(
job.payload.max_runtime_seconds,
job.payload.max_output_bytes,
) {
return Err(fail("VALIDATION_ERROR"));
}
if !job.payload.action.validate() {
return Err(Error(StatusCode::CONFLICT, "APT_MANIFEST_REQUIRED"));
}
@@ -1032,7 +1004,6 @@ async fn operations_http(
#[cfg(test)]
mod windows_contract_tests {
use super::*;
use chrono::Duration;
fn input() -> PlanInput {
let tenant = Uuid::new_v4();
let now = Utc::now();
@@ -1064,111 +1035,6 @@ mod windows_contract_tests {
i.script_variants.remove(1);
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
}
#[test]
fn fixed_windows_log_web_contract_denies_extra_source_parameters() {
let tenant = Uuid::new_v4();
let now = Utc::now();
let value = json!({"tenant_id":tenant,"action":"query_logs","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":30,"max_output_bytes":4096,"unit":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"since":now-Duration::hours(1),"until":now,"max_lines":1000},"schedule":{"not_before":now,"start_before":now+Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed source"});
let input = serde_json::from_value::<PlanRequest>(value.clone())
.unwrap()
.resolve(tenant)
.unwrap();
assert!(input.action.is_windows_event_log_fixture());
assert!(input.action.validate());
assert!(
input
.action
.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes)
);
assert!(input.script_variants.is_empty());
for field in ["channel", "provider", "xpath", "bookmark"] {
let mut bad = value.clone();
bad["parameters"][field] = json!("arbitrary");
assert!(
serde_json::from_value::<PlanRequest>(bad)
.map(|request| request.resolve(tenant).is_err())
.unwrap_or(true)
);
}
}
#[test]
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
let mut i = input();
let legacy_linux = encode(&i.action).unwrap();
i.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert_eq!(
encode(&target_action(&i, &["linux.base/1".into()]).unwrap()).unwrap(),
legacy_linux
);
let windows = target_action(&i, &["windows.base/1".into()]).unwrap();
assert!(matches!(
windows,
Action::RunScript {
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
..
}
));
assert!(!windows.available_for(
"agent_service",
&[
"windows.base/1".into(),
"rmm.sync.v1".into(),
"run_script".into(),
"script.powershell/1".into()
]
));
for identity in ["root", "system"] {
i.execution_identity = identity.into();
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
}
i.execution_identity = "agent_service".into();
// Even the first Action must match the optional profile byte-for-byte.
i.script_variants.reverse();
i.action = windows;
assert!(target_action(&i, &["windows.base/1".into()]).is_ok());
if let Action::RunScript {
windows_execution_profile,
..
} = &mut i.action
{
*windows_execution_profile = None;
}
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
i.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert!(validate_variants(&i.script_variants).is_err());
let schema = schemars::schema_for!(Variant).to_value();
assert_eq!(
schema["properties"]["windows_execution_profile"],
json!({"$ref":"#/$defs/WindowsExecutionProfile"})
);
assert!(
!schema["required"]
.as_array()
.unwrap()
.contains(&json!("windows_execution_profile"))
);
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
let legacy = json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi"});
let inherited: Variant = serde_json::from_value(legacy.clone()).unwrap();
assert!(inherited.windows_execution_profile.is_none());
assert_eq!(serde_json::to_value(inherited).unwrap(), legacy);
for profile in [
Value::Null,
json!(false),
json!(1),
json!([]),
json!({}),
json!({"powershell_51_remote_signed":null}),
json!("bypass"),
json!("powershell_7_remote_signed"),
] {
assert!(serde_json::from_value::<Variant>(json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi", "windows_execution_profile":profile})).is_err());
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":profile})).is_err());
}
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":"powershell_51_remote_signed"})).is_err());
}
#[tokio::test]
#[ignore = "requires dedicated isolated PostgreSQL; tests/windows_plan_database.py"]
async fn windows_plan_caps_persisted_database() {
@@ -1309,75 +1175,6 @@ mod windows_contract_tests {
"PLAN_HASH_MISMATCH"
);
tx.rollback().await.unwrap();
// A process-profile plan needs the additional current capability. Its
// presence is rechecked at submit/approval just like interpreter support.
let mut profiled = request.clone();
profiled.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert_eq!(
plan(&state, &principal, tenant, profiled.clone())
.await
.unwrap_err()
.1,
"UNSUPPORTED_CAPABILITY"
);
let mut profile_caps = windows_caps.as_array().unwrap().clone();
profile_caps.push(json!("script.powershell.process_remote_signed/1"));
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(json!(profile_caps))
.execute(&admin)
.await
.unwrap();
let view = plan(&state, &principal, tenant, profiled).await.unwrap();
let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
let bytes: Vec<u8> =
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
.bind(profile_id)
.fetch_one(&admin)
.await
.unwrap();
let profile_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
recheck(&mut tx, &profile_bound).await.unwrap();
tx.rollback().await.unwrap();
let mut changed = profile_bound.clone();
let windows_job = changed
.jobs
.iter_mut()
.find(|j| j.payload.asset_id == assets[1])
.unwrap();
if let Action::RunScript {
windows_execution_profile,
..
} = &mut windows_job.payload.action
{
*windows_execution_profile = None;
}
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &changed).await.unwrap_err().1,
"PLAN_HASH_MISMATCH"
);
tx.rollback().await.unwrap();
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(&windows_caps)
.execute(&admin)
.await
.unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &profile_bound).await.unwrap_err().1,
"UNSUPPORTED_CAPABILITY"
);
tx.rollback().await.unwrap();
request.script_variants.clear();
assert_eq!(
plan(&state, &principal, tenant, request.clone())
@@ -1401,116 +1198,6 @@ mod windows_contract_tests {
.unwrap()
.is_none()
);
let now = Utc::now();
let mut logs = input();
logs.targets.asset_ids = vec![assets[1]];
logs.script_variants.clear();
logs.max_runtime_seconds = 30;
logs.action = Action::QueryLogs {
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
since: now - Duration::hours(1),
until: now,
max_lines: 1000,
};
assert_eq!(
plan(&state, &principal, tenant, logs.clone())
.await
.unwrap_err()
.1,
"FORBIDDEN"
);
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
assert_eq!(
plan(&state, &principal, tenant, logs.clone())
.await
.unwrap_err()
.1,
"UNSUPPORTED_CAPABILITY"
);
let mut log_caps = windows_caps.as_array().unwrap().clone();
log_caps.extend([
json!("query_logs"),
json!(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY),
]);
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(json!(log_caps))
.execute(&admin)
.await
.unwrap();
let view = plan(&state, &principal, tenant, logs).await.unwrap();
let log_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
let bytes: Vec<u8> =
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
.bind(log_id)
.fetch_one(&admin)
.await
.unwrap();
let log_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
recheck(&mut tx, &log_bound).await.unwrap();
tx.rollback().await.unwrap();
let pending = submit(
&state,
&principal,
tenant,
log_id,
Submit {
idempotency_key: "fixed-event-log".into(),
},
)
.await
.unwrap();
assert_eq!(pending["approval_state"], "pending_approval");
assert_eq!(pending["job_count"], 0);
let mut changed = log_bound.clone();
if let Action::QueryLogs { max_lines, .. } = &mut changed.jobs[0].payload.action {
*max_lines = 999;
}
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &changed).await.unwrap_err().1,
"PLAN_HASH_MISMATCH"
);
tx.rollback().await.unwrap();
let mut changed = log_bound.clone();
changed.jobs[0].payload.max_output_bytes = 65537;
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &changed).await.unwrap_err().1,
"VALIDATION_ERROR"
);
tx.rollback().await.unwrap();
log_caps.retain(|cap| cap != WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY);
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(json!(log_caps))
.execute(&admin)
.await
.unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &log_bound).await.unwrap_err().1,
"UNSUPPORTED_CAPABILITY"
);
tx.rollback().await.unwrap();
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &log_bound).await.unwrap_err().1,
"FORBIDDEN"
);
tx.rollback().await.unwrap();
let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs WHERE tenant_id=$1),(SELECT count(*) FROM outbox WHERE tenant_id=$1),(SELECT count(*) FROM execution_permits WHERE tenant_id=$1)").bind(tenant).fetch_one(&admin).await.unwrap();
assert_eq!(counts, (0, 0, 0));
let after: Vec<u8> =
-1
View File
@@ -356,7 +356,6 @@ mod tests {
script_utf8: "true\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
-1
View File
@@ -393,7 +393,6 @@ mod tests {
script_utf8: "Write-Output 'hello'".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
assert!(!policy.permits("selected", &job, &caps, now));
job.action = Action::SetServiceState {
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Local CreateNew correction of the public recovery hash function alias clash.
The User's H/Get-History error occurred in the old pre-effect case/config guard.
Keep the same console case and untouched original files. No target/server call,
alias mutation or retry of an effect; the same case-absence guard still applies.
"""
import argparse
import os
from pathlib import Path
import re
import console_access_precision as previous
require, sha, save = previous.require, previous.sha, previous.save
CASE = '5c96d3d8-1657-40c8-a6ec-c00b63a98210'
OLD_SHA = '4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69'
OLD_NAME = 'Recover-ExistingDevAccess.ps1'
NEW_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
NAME = 'Get-RmmRecoveryFileSha256'
STATE = previous.original.cb.EVIDENCE / 'dev-access-console-hash-correction'
def corrected(raw):
require(previous.original.pair.raw_sha(raw) == OLD_SHA, 'exact original reviewed 5c96 public script')
source = raw.decode('utf-8')
require(source.count('function H(') == 1 and NAME not in source, 'one original hash function and fresh unique name')
calls = re.findall(r'\(H\s', source)
require(len(calls) == source.count('(H ') and calls, 'all original H calls have the reviewed spelling')
result = source.replace('function H(', 'function ' + NAME + '(').replace('(H ', '(' + NAME + ' ')
require('function H(' not in result and not re.search(r'\(H\s', result), 'no alias-sensitive hash call remains')
require(result.replace('function ' + NAME + '(', 'function H(').replace('(' + NAME + ' ', '(H ') == source, 'only function/command spelling changed; all effects/pins/case bytes preserved')
return result.encode(), len(calls)
def build():
folder = previous.STATE / CASE
raw = (folder / OLD_NAME).read_bytes()
new, calls = corrected(raw)
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
previous.original.pair.write_bytes(STATE / NEW_NAME, new)
digest = previous.original.pair.raw_sha(new)
# Literal replacement, UTF8 without BOM, CreateNew, both independent hashes.
# No free script content, Remove-Alias, persistent policy or registry change.
patch = r'''$ErrorActionPreference='Stop'
$oldPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'
$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1'
if((Get-FileHash -LiteralPath $oldPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OLD@@'){throw 'Falsche Originaldatei; nichts ausfuehren'}
if(Test-Path -LiteralPath $newPath){throw 'Korrekturdatei existiert bereits; nur lesend pruefen'}
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($oldPath))
$text=$text.Replace('function H(','function Get-RmmRecoveryFileSha256(').Replace('(H ','(Get-RmmRecoveryFileSha256 ')
$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text)
$out=[IO.File]::Open($newPath,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
try{$out.Write($bytes,0,$bytes.Length);$out.Flush($true)}finally{$out.Dispose()}
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@NEW@@'){throw 'Korrekturhash stimmt nicht; nichts ausfuehren'}
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
'''.replace('@@OLD@@', OLD_SHA).replace('@@NEW@@', digest)
previous.original.pair.write_bytes(STATE / 'Create-VerifiedHashFix.ps1', patch.encode())
save(STATE / 'qualification.json', dict(source_sha256=sha(__file__), source_only=True, same_console_case=CASE, original_script_sha256=OLD_SHA, corrected_script_sha256=digest, renamed_call_count=calls, exact_inverse_spelling_transform=True, all_other_bytes_unchanged=True, original_script_and_zip_unchanged=True, case_absence_guard_retained=True, no_alias_mutation=True, no_server_or_vm_call=True, original_failure='Get-History/IdCannotConvert before New-Item/case or any effect'))
print('corrected_script_sha256=' + digest)
print('patch_sha256=' + sha(STATE / 'Create-VerifiedHashFix.ps1'))
print('renamed_hash_calls=' + str(calls))
print('patch=' + str((STATE / 'Create-VerifiedHashFix.ps1').resolve()))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
if __name__ == '__main__':
main()
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""One local provenance correction: pin the actually deployed original bootstrap.
Actual User readonly values identify the published original file, not an unknown
hash. Preserve the same absent console case and every other byte/guard/effect.
No Windows/server access, new expiry, alias/policy change or effect retry.
"""
import argparse
import json
import os
from pathlib import Path
import zipfile
import console_access_hash_command as previous
require, sha, save = previous.require, previous.sha, previous.save
STATE = previous.previous.original.cb.EVIDENCE / 'dev-access-console-original-bootstrap-correction'
MAIN = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
OLD_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
NEW_NAME = 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
OLD_SCRIPT_SHA = 'd366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c'
PARENT_SOURCE_SHA = 'b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad'
REPO_BOOTSTRAP_SHA = '9e992602034026efbe17f833d4d6be694da3e223ac6b4a394c502eb140ec0189'
PUBLISHED_BOOTSTRAP_SHA = '332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f'
CONFIG_SHA = '4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823'
BUNDLE_SHA = 'cba159469efad9039562633fd60213d8f6a62f169fc3d1bba915e49d22c764d2'
REPAIR_BUNDLE_SHA = '2558448b7812b95de1612fca5f11da8f4a868764fb45666b128d03eb0c423eb4'
def build(facts_path):
require(sha(previous.__file__) == PARENT_SOURCE_SHA, 'immutable reviewed parent hash fix source')
facts = previous.previous.original.cb.contract.protected_json(facts_path)
require(set(facts) == {'case_present', 'config_sha256', 'bootstrap_sha256', 'configured_expiry', 'account_expiry_filetime'} and facts['case_present'] is False and facts['config_sha256'] == CONFIG_SHA and facts['bootstrap_sha256'] == PUBLISHED_BOOTSTRAP_SHA and facts['configured_expiry'] == '2026-11-14T12:55:31.254999+00:00' and facts['account_expiry_filetime'] == '134391345312549990', 'exact actual User readonly original baseline, no unknown hash adoption')
public = MAIN / 'devstate/windows-bootstrap'
require(sha(public / 'windows-dev-access.zip') == BUNDLE_SHA and sha(public / 'windows-dev-repair.zip') == REPAIR_BUNDLE_SHA, 'immutable originally published bundles')
with zipfile.ZipFile(public / 'windows-dev-access.zip') as archive:
bootstrap = archive.read('Bootstrap-DevAccess.ps1'); config = archive.read('bootstrap-public.json')
with zipfile.ZipFile(public / 'windows-dev-repair.zip') as archive:
repair = json.loads(archive.read('repair-public.json'))
raw_sha = previous.previous.original.pair.raw_sha
require(raw_sha(bootstrap) == PUBLISHED_BOOTSTRAP_SHA == repair['previous_bootstrap_sha256'] and raw_sha(config) == CONFIG_SHA, 'actual file equals original publication and independently pinned repair prerequisite')
original_path = previous.STATE / OLD_NAME
require(sha(original_path) == OLD_SCRIPT_SHA, 'exact reviewed parent PS1')
source = original_path.read_bytes().decode('utf-8')
old = "$expectedBootstrap='" + REPO_BOOTSTRAP_SHA + "'"
new = "$expectedBootstrap='" + PUBLISHED_BOOTSTRAP_SHA + "'"
require(source.count(old) == 1 and new not in source, 'single exact original constant')
corrected = source.replace(old, new, 1)
require(corrected.replace(new, old, 1) == source, 'all other bytes including expiry/case/alias/clock/effects unchanged')
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
save(STATE / 'actual-user-readonly.json', facts)
previous.previous.original.pair.write_bytes(STATE / NEW_NAME, corrected.encode())
digest = raw_sha(corrected.encode())
patch = r'''$ErrorActionPreference='Stop'
$inputPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1';$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
if((Get-FileHash -LiteralPath $inputPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@INPUT@@'-or(Test-Path -LiteralPath $newPath)){throw 'Originalhash falsch oder neue Datei bereits vorhanden; nichts ausfuehren'}
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($inputPath));$text=$text.Replace("`$expectedBootstrap='@@OLD@@'","`$expectedBootstrap='@@PIN@@'");$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text);$file=[IO.File]::Open($newPath,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OUTPUT@@'){throw 'Neuer Hash falsch; nichts ausfuehren'}
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
'''
for token, value in {'INPUT': OLD_SCRIPT_SHA, 'OLD': REPO_BOOTSTRAP_SHA, 'PIN': PUBLISHED_BOOTSTRAP_SHA, 'OUTPUT': digest}.items():
patch = patch.replace('@@' + token + '@@', value)
previous.previous.original.pair.write_bytes(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1', patch.encode())
save(STATE / 'qualification.json', dict(source_only=True, source_sha256=sha(__file__), parent_source_sha256=PARENT_SOURCE_SHA, actual_user_readonly_sha256=sha(STATE / 'actual-user-readonly.json'), same_console_case=previous.CASE, input_script_sha256=OLD_SCRIPT_SHA, corrected_script_sha256=digest, original_bundle_sha256=BUNDLE_SHA, repair_bundle_sha256=REPAIR_BUNDLE_SHA, published_bootstrap_sha256=PUBLISHED_BOOTSTRAP_SHA, corrected_exactly_one_constant=True, all_other_bytes_unchanged=True, no_unknown_hash_adoption=True, original_scripts_and_zip_retained=True, no_windows_or_server_access=True))
print('source_sha256=' + sha(__file__))
print('corrected_script_sha256=' + digest)
print('patch_sha256=' + sha(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1'))
print('patch=' + str((STATE / 'Create-VerifiedOriginalBootstrapFix.ps1').resolve()))
def main():
os.umask(0o077)
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('build',));parser.add_argument('--actual-user-readonly',required=True,type=Path);args=parser.parse_args();build(args.actual_user_readonly)
if __name__ == '__main__':
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""New public console package correcting only the old AccountExpires guard.
Local only: reads the immutable completed server-only recovery case and its
public package, never contacts Windows/server and cannot change a server lease.
The same active server expiry/key/pins remain bound. The old package is retained.
"""
import argparse
import json
import os
from pathlib import Path
import uuid
import zipfile
import console_access_recovery as original
require, sha, save = original.require, original.sha, original.save
STATE = original.cb.EVIDENCE / 'dev-access-console-precision-correction'
PARENT_ID = '4b6506a7-6c3e-4cca-a497-618fa8666300'
PARENT_SOURCE_SHA = '703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053'
PARENT_INTENT_SHA = 'cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a'
PARENT_ENTER_SHA = '2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317'
PARENT_READBACK = 'readback-754e47df-25e0-4c0b-a411-56b3d350ace5.json'
PARENT_READBACK_SHA = 'f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787'
EXPIRY = '2026-11-15T13:05:58+00:00'
AUTHORIZED_SHA = 'fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2'
NAMES = ('Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt')
def replace_once(text, old, new):
require(text.count(old) == 1, 'one exact reviewed precision/provenance replacement')
return text.replace(old, new, 1)
def corrected_script(source, ident):
require(str(uuid.UUID(ident)) == ident, 'new canonical console UUID')
# The original cfg bytes/hash and its exact expiry string have already been
# verified before this line. Derive ONE full 64-bit FILETIME, no rounding,
# alternative value, tolerance or claim of a measured VM account value.
old = "$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}"
new = "$expectedOldAccountFiletime=[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc().ToString()\n$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$expectedOldAccountFiletime){throw 'Existing original expired account precision mismatch; stop for readonly inspection'}"
result = replace_once(source, old, new)
result = replace_once(result, "$recoveryId='" + PARENT_ID + "'", "$recoveryId='" + ident + "'")
result = replace_once(result, "@{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=", "@{id=$recoveryId;parent_server_case='" + PARENT_ID + "';parent_server_enter_sha256='" + PARENT_ENTER_SHA + "';new_expiry=$newExpiry;original_config_sha256=")
effect = '[IO.File]::Replace($candidate,$config,$nativeBackup)'
require(result.split(effect, 1)[1] == source.split(effect, 1)[1], 'all three mutation steps/start behavior unchanged')
require(result.count('Start-ScheduledTask -TaskName $taskName') == 1 and '134391345310000000' not in result, 'one original task start, no obsolete rounded guard')
return result
def parent():
require(sha(original.__file__) == PARENT_SOURCE_SHA, 'immutable historical source, no rebase')
folder = original.STATE / PARENT_ID
require(sha(folder / 'intent.json') == PARENT_INTENT_SHA and sha(folder / 'server-entered.json') == PARENT_ENTER_SHA and sha(folder / PARENT_READBACK) == PARENT_READBACK_SHA, 'exact existing server-only CAS and independent readback')
intent = original.cb.contract.protected_json(folder / 'intent.json')
entered = original.cb.contract.protected_json(folder / 'server-entered.json')
readback = original.cb.contract.protected_json(folder / PARENT_READBACK)
require(intent['id'] == PARENT_ID and intent['source_sha256'] == PARENT_SOURCE_SHA and intent['payload']['new_expiry'] == EXPIRY and entered['completed'] is True and entered['authorized_sha256'] == readback['authorized_sha256'] == AUTHORIZED_SHA and entered['expiry'] == readback['expiry'] == '20261115130558Z' and readback['read_only'] is True and readback['completed'] is True, 'same already completed server lease; never a new CAS')
before = intent['payload']['server_before']
require(all(readback[field] == before[field] for field in ('profile_sha256', 'effective_sha256', 'server_host_key_sha256', 'tunnel_public_key_sha256', 'uid', 'gid', 'home', 'shell')), 'original forwarding authority/key/profile/account unchanged')
for name, field in ((NAMES[0], 'console_sha256'), ('README.txt', 'readme_sha256'), ('public-recovery.json', 'public_json_sha256'), ('windows-dev-access-recovery.zip', 'bundle_sha256')):
require(sha(folder / name) == intent[field], 'immutable original public package files')
return folder, intent
def build():
old_folder, old_intent = parent()
require(original.cb.contract.now() < original.dt.datetime.fromisoformat(EXPIRY), 'existing server lease still in its fixed window')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
save(folder / 'prepare-intent.json', dict(id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_server_enter_sha256=PARENT_ENTER_SHA, new_server_cas=False, no_windows_or_server_access=True))
script = corrected_script((old_folder / NAMES[0]).read_text(), ident)
original.pair.write_bytes(folder / NAMES[0], script.encode())
digest = original.pair.raw_sha(script.encode())
public = dict(schema_version=1, id=ident, parent_server_case=PARENT_ID, parent_source_sha256=PARENT_SOURCE_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, new_expiry=EXPIRY, script_sha256=digest, no_private_keys=True, new_server_cas=False, old_account_guard='exact_derived_from_verified_config_utc_filetime', actual_vm_account_filetime_measured=False)
save(folder / 'public-recovery.json', public)
readme = (old_folder / 'README.txt').read_text()
require(old_intent['console_sha256'] in readme, 'original independent PS1 hash instructions')
readme = readme.replace(old_intent['console_sha256'], digest)
readme += ('\nPraezisionskorrektur: neues Konsolenpaket, neuer Fall ' + ident + '.\n'
'Verwendet ausschliesslich den bereits bestaetigten Serverfall ' + PARENT_ID + ' und dieselbe UTC-Frist ' + EXPIRY + '. Keine neue Serververlaengerung.\n'
'Der alte AccountExpires-Sollwert wird exakt aus der unveraenderten alten Config-UTC-Zeit einschliesslich Bruchteilen abgeleitet. Dies ist kein gemessener VM-Accountwert.\n'
'Keine Rundung, Toleranz oder alternativer Sollwert. Bei Abweichung abbrechen und nur lesend pruefen lassen.\n'
'Falls ein frueheres Paket bereits erfolgreich ausgefuehrt wurde: dieses Paket NICHT als Retry verwenden; der alte Config-Hashguard muss dann verweigern.\n')
original.pair.write_bytes(folder / 'README.txt', readme.encode())
bundle = folder / 'windows-dev-access-recovery.zip'
with zipfile.ZipFile(bundle, 'x', compression=zipfile.ZIP_DEFLATED) as archive:
for name in NAMES: archive.write(folder / name, name)
bundle.chmod(0o600)
intent = dict(schema_version=1, id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_intent_sha256=PARENT_INTENT_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, original_bundle_sha256=old_intent['bundle_sha256'], new_expiry=EXPIRY, console_sha256=digest, public_json_sha256=sha(folder / 'public-recovery.json'), readme_sha256=sha(folder / 'README.txt'), bundle_sha256=sha(bundle), no_windows_or_server_access=True, new_server_cas=False)
save(folder / 'intent.json', intent)
print(json.dumps(dict(id=ident, intent_sha256=sha(folder / 'intent.json'), bundle=str(bundle.resolve()), bundle_sha256=intent['bundle_sha256'], console_source=str((folder / NAMES[0]).resolve()), console_sha256=digest, new_expiry=EXPIRY, parent_server_case=PARENT_ID, new_server_cas=False, no_windows_or_server_access=True)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
if __name__ == '__main__':
try: main()
except Exception as error: print('CONSOLE_PRECISION_CORRECTION_INCOMPLETE:' + type(error).__name__); raise SystemExit(2) from None
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Expired development tunnel recovery: server-only CAS + fixed public console code.
No Windows access, key generation, SSH profile edit, port/download/RMM change.
Root renews the one expired restricted authorized key first, then hands the
reviewed public PowerShell to the User's elevated Windows console.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import subprocess
import uuid
import zipfile
import client_bootstrap as cb
import system_pipe_upgrade as pair
import dev_access_renewal as previous
require,sha,save=pair.require,pair.sha,pair.save
STATE=cb.EVIDENCE/'dev-access-console-recovery'
OLD_EXPIRY='2026-11-14T12:55:31.254999+00:00'
def recover_server(payload):
import datetime as dt
import re
import stat
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
ident=str(uuid.UUID(payload['id']));case=root/('console-recovery-'+ident)
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
def check(path,mode):
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
check(authorized,0o644);check(profile,0o644)
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
if payload['phase']=='state':return state()
if payload['phase']=='readback':
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and old<dt.datetime.now(dt.timezone.utc)<new<=dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=24) and state()==payload['server_before'],'exact EXPIRED original key/CAS and bounded fresh 24h console recovery')
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
def write(path,data,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 out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
CONSOLE = r'''
# Paste this complete reviewed block into elevated Windows PowerShell 5.1.
# Bootstrap SSH recovery only. No RMM job, policy/ACL change, installation or reboot.
$ErrorActionPreference='Stop'
if(!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){throw 'Elevated Windows console required'}
$recoveryId='@@ID@@';$newExpiry='@@EXPIRY@@';$expectedConfig='@@CONFIG@@';$expectedBootstrap='@@BOOTSTRAP@@'
$expectedTunnel='@@TUNNEL@@';$expectedWindowsHost='@@HOST@@';$root='C:\ProgramData\RmmDevAccess';$config=Join-Path $root 'bootstrap-public.json';$case=Join-Path $root ('console-recovery-'+$recoveryId);$taskName='RmmDevReverseTunnel'
function H($path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Only regular fixed public/bootstrap file'};$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No reparse ancestor'};$parent=$parent.Parent};return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function B([string]$text){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash([Text.Encoding]::UTF8.GetBytes($text)))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function NewReceipt($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()}}
$directory=Get-Item -LiteralPath $root -Force;$acl=Get-Acl -LiteralPath $root
if(!$directory.PSIsContainer-or($directory.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original protected bootstrap directory'}
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-ne'Allow'-or$rule.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original private directory ACL'}}
if((Test-Path -LiteralPath $case)-or(H $config)-cne$expectedConfig-or(H (Join-Path $root 'Bootstrap-DevAccess.ps1'))-cne$expectedBootstrap){throw 'Only untouched original expired bootstrap; existing recovery means readback only'}
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'-or$cfg.expires_at-cne'2026-11-14T12:55:31.254999+00:00'){throw 'Exact original public config and old expiry'}
$expiry=[DateTimeOffset]::Parse($newExpiry);if($expiry-le[DateTimeOffset]::UtcNow-or$expiry-gt[DateTimeOffset]::UtcNow.AddHours(24)){throw 'Bounded reviewed new UTC expiry'}
$tunnelPublic=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' '
$windowsHostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' '
if($tunnelPublic-cne$expectedTunnel-or$windowsHostPublic-cne$expectedWindowsHost-or(Get-Content -LiteralPath (Join-Path $root 'known_hosts') -Raw)-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")-or(Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original tunnel/server/Windows/notebook public pins'}
$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}
$task=Get-ScheduledTask -TaskName $taskName;$actions=@($task.Actions)
if($task.State-cne'Ready'-or$actions.Count-ne1-or$actions[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$actions[0].Arguments-cne'-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'-or$task.Principal.UserId-notin@('SYSTEM','S-1-5-18')-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'){throw 'Unchanged original SYSTEM task must be Ready'}
$active=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='ssh.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'-or$_.CommandLine-like'*C:\ProgramData\RmmDevAccess\tunnel_ed25519*'})
if($active.Count){throw 'Old maintainer/tunnel must exit naturally; no kill or duplicate start'}
$taskXml=Export-ScheduledTask -TaskName $taskName;$fixed=[ordered]@{}
foreach($path in @((Join-Path $root 'known_hosts'),(Join-Path $root 'Bootstrap-DevAccess.ps1'),(Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub','C:\ProgramData\ssh\sshd_config','C:\ProgramData\ssh\administrators_authorized_keys')){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse public/bootstrap file'};$fixed[$path]=@{sha256=(H $path);sddl=(Get-Acl -LiteralPath $path).Sddl}}
$private=[ordered]@{};foreach($path in @((Join-Path $root 'tunnel_ed25519'),'C:\ProgramData\ssh\ssh_host_ed25519_key','C:\ProgramData\ssh\ssh_host_rsa_key','C:\ProgramData\ssh\ssh_host_ecdsa_key')){if(Test-Path -LiteralPath $path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse private key'};$private[$path]=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl}}}
New-Item -ItemType Directory -Path $case|Out-Null
NewReceipt (Join-Path $case 'intent.json') @{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=$expectedConfig;account_sid=$account.SID.Value;task_xml_sha256=(B $taskXml);fixed=$fixed;private_metadata=$private;private_keys_read=$false;no_new_authority=$true}
$backup=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$backup,$false)
$cfg.expires_at=$newExpiry;$candidate=Join-Path $case 'bootstrap-public.next';NewReceipt $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
NewReceipt (Join-Path $case 'config-replace-intent.json') @{old_sha256=$expectedConfig;new_expiry=$newExpiry;native_backup=$nativeBackup}
if((H $config)-cne$expectedConfig-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$originalAcl=Get-Acl -LiteralPath $config
[IO.File]::Replace($candidate,$config,$nativeBackup);Set-Acl -LiteralPath $config -AclObject $originalAcl
NewReceipt (Join-Path $case 'account-expiry-intent.json') @{existing_sid=$account.SID.Value;new_expiry=$newExpiry}
if((Get-LocalUser -Name 'rmm-dev').SID.Value-cne$account.SID.Value){throw 'Original account changed'}
Set-LocalUser -Name 'rmm-dev' -AccountExpires $expiry.LocalDateTime
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'@@FILETIME@@'){throw 'Exact renewed account expiry'}
foreach($path in $fixed.Keys){if((H $path)-cne$fixed[$path].sha256-or(Get-Acl -LiteralPath $path).Sddl-cne$fixed[$path].sddl){throw 'Original fixed bootstrap/key bytes or ACL changed'}}
foreach($path in $private.Keys){$item=Get-Item -LiteralPath $path -Force;$meta=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl};foreach($field in @('bytes','created','written','sddl')){if($meta[$field]-cne$private[$path][$field]){throw 'Private key metadata changed'}}}
if((Export-ScheduledTask -TaskName $taskName)-cne$taskXml-or(Get-ScheduledTask -TaskName $taskName).State-cne'Ready'){throw 'Original task changed; no start'}
NewReceipt (Join-Path $case 'original-task-start-intent.json') @{start_once=$true;task_xml_sha256=(B $taskXml)}
Start-ScheduledTask -TaskName $taskName
NewReceipt (Join-Path $case 'console-completed.json') @{completed=$true;new_expiry=$newExpiry;original_task_start_requested_once=$true;private_keys_read=$false;no_keys_ports_policy_acl_install_reboot_or_rmm_change=$true}
Write-Host ('Bestehender SSH-Zugang erneuert bis '+$newExpiry+'. Originaltunnel einmal gestartet. Bitte diese Zeile zurueckmelden; keine Schluessel senden.')
'''
class ServerAccess:
def __init__(self,root):self.root=Path(root).absolute();require(self.root==self.root.resolve() and self.root!=cb.ROOT,'separate protected Main access root')
def rpc(self,payload):
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(recover_server)+'\ntry:\n print(json.dumps(recover_server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed server-only recovery RPC')
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server-only recovery incomplete; readback only');return value
def prepare(access):
require(cb.contract.now()>dt.datetime.fromisoformat(OLD_EXPIRY),'original lease actually expired')
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
expiry=(cb.contract.now()+dt.timedelta(hours=24)).replace(microsecond=0)
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
with zipfile.ZipFile(access.root/'devstate/windows-bootstrap/windows-dev-access.zip') as bundle:
original=bundle.read('bootstrap-public.json')
public=json.loads(original,object_pairs_hook=cb.contract.strict_object)
require(public['expires_at']==OLD_EXPIRY and public['server']=='discovery.ease-technologies.de','original public-only bundle')
payload=dict(id=ident,phase='state',old_expiry=OLD_EXPIRY,new_expiry=expiry.isoformat(),tunnel_public_key=console['tunnel_public_key'])
save(folder/'prepare-intent.json',dict(id=ident,source_sha256=sha(__file__),new_expiry=payload['new_expiry'],no_windows_access=True))
baseline=access.rpc(payload);require(baseline['expiry']==dt.datetime.fromisoformat(OLD_EXPIRY).strftime('%Y%m%d%H%M%SZ'),'only original expired key')
payload['server_before']=baseline
script=CONSOLE
for key,value in {'ID':ident,'EXPIRY':payload['new_expiry'],'CONFIG':hashlib.sha256(original).hexdigest(),'BOOTSTRAP':sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'TUNNEL':console['tunnel_public_key'],'HOST':console['windows_host_public_key'],'FILETIME':str((int(expiry.timestamp())+11644473600)*10000000)}.items():
token='@@'+key+'@@';require(script.count(token)==1,'exact fixed public console field');script=script.replace(token,value)
require('@@' not in script,'complete fixed public instructions')
pair.write_bytes(folder/'Recover-ExistingDevAccess.ps1',script.encode())
save(folder/'public-recovery.json',dict(id=ident,new_expiry=payload['new_expiry'],script_sha256=pair.raw_sha(script.encode()),no_private_keys=True))
readme=('Bestehenden Windows-Entwicklungszugang wiederherstellen\r\n\r\n'
'Nur in dieser Windows-Test-VM ausfuehren, in einer als Administrator gestarteten PowerShell.\r\n'
'Der Cloudserver muss zuvor durch den Entwickler fuer diese feste Frist erneuert worden sein.\r\n'
'Neue UTC-Frist: '+payload['new_expiry']+'\r\n'
'ZIP-SHA256 mit dem unabhaengig mitgeteilten Downloadhash vergleichen; dann hier entpacken.\r\n'
'Folgende Befehle im entpackten Verzeichnis ausfuehren:\r\n\r\n'
"$recoveryScript = Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'\r\n"
"if ((Get-FileHash -LiteralPath $recoveryScript -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+pair.raw_sha(script.encode())+"') { throw 'Falsche Recoverydatei' }\r\n"
'Unblock-File -LiteralPath $recoveryScript\r\n'
'powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $recoveryScript\r\n\r\n'
'Unblock-File betrifft nur diese exakt gepruefte heruntergeladene Datei; RemoteSigned nur diesen Bootstrapprozess.\r\n'
'Keine globale Policy/GPO aendern. Falls eine Richtlinie oder Pruefung verweigert: stoppen, Fehlermeldung melden, nicht erneut ausfuehren.\r\n'
'Das Skript behaelt Schluessel, Pins, SSH-Profil und Taskdefinition bei, erneuert nur die Ablaufzeit und startet den Originaltunnel einmal.\r\n'
'Keine Installation, ACL-Reparatur, RMM-Aktion, Reboot oder Update. Private Schluessel werden nicht gelesen/ausgegeben.\r\n'
'Nach Erfolg bitte nur die Abschlusszeile melden, keine Schluessel oder Zugangsdaten. Bei Fehler den Zustand fuer lesende Kontrolle behalten.\r\n')
pair.write_bytes(folder/'README.txt',readme.encode('utf-8'))
bundle=folder/'windows-dev-access-recovery.zip'
with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
for name in ('Recover-ExistingDevAccess.ps1','public-recovery.json','README.txt'):
archive.write(folder/name,name)
bundle.chmod(0o600)
intent=dict(id=ident,source_sha256=sha(__file__),access_root=str(access.root),payload=payload,console_sha256=pair.raw_sha(script.encode()),bundle_sha256=sha(bundle),readme_sha256=sha(folder/'README.txt'),public_json_sha256=sha(folder/'public-recovery.json'))
save(folder/'intent.json',intent)
print(json.dumps(dict(id=ident,review_sha256=sha(folder/'intent.json'),console_source=str((folder/'Recover-ExistingDevAccess.ps1').resolve()),console_sha256=intent['console_sha256'],bundle=str(bundle.resolve()),bundle_sha256=sha(bundle),new_expiry=payload['new_expiry'],windows_not_accessed=True)))
def run(access,ident,phase,review_sha):
require(str(uuid.UUID(ident))==ident,'canonical original recovery');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
require(intent['source_sha256']==sha(__file__) and intent['access_root']==str(access.root) and sha(folder/'Recover-ExistingDevAccess.ps1')==intent['console_sha256'] and sha(folder/'windows-dev-access-recovery.zip')==intent['bundle_sha256'] and sha(folder/'README.txt')==intent['readme_sha256'] and sha(folder/'public-recovery.json')==intent['public_json_sha256'],'same immutable console recovery source/public package')
if phase=='server-enter':
require(review_sha==sha(folder/'intent.json'),'explicit reviewed server-only CAS');save(folder/'server-enter-intent.json',dict(once=True))
payload=dict(intent['payload'],phase='enter' if phase=='server-enter' else 'readback')
result=access.rpc(payload);save(folder/('server-entered.json' if phase=='server-enter' else 'readback-'+str(uuid.uuid4())+'.json'),result)
print(json.dumps(dict(id=ident,result=result,windows_not_accessed=True,console_handoff_allowed=result.get('completed') is True)))
def main():
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','server-enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=ServerAccess(args.access_root)
if args.phase=='prepare':require(not(args.id or args.review_sha256),'fresh server-only preparation');prepare(access)
else:require(args.id and ((args.phase=='server-enter')==bool(args.review_sha256)),'same case, reviewed CAS once');run(access,args.id,args.phase,args.review_sha256)
if __name__=='__main__':
try:main()
except Exception as error:print('CONSOLE_ACCESS_RECOVERY_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""One 24h renewal of the existing restricted development SSH transport.
No new key, port, shell, RMM setting, download lease, stop/kill or reboot.
The unchanged tunnel expires naturally; one SYSTEM worker starts its original
scheduled task at original expiry+60s. This deliberately permits a short gap.
Lost mutation replies allow readback only. Main config publication is Root work.
"""
import argparse
import base64
import datetime as dt
import inspect
import json
import os
from pathlib import Path
import subprocess
import uuid
import client_bootstrap as cb
import system_pipe_upgrade as pair
require, sha, canonical, save = pair.require, pair.sha, pair.canonical, pair.save
STATE = cb.EVIDENCE / 'dev-access-renewal'
OLD_EXPIRY = '2026-11-14T12:55:31.254999+00:00'
OLD_UTC = dt.datetime.fromisoformat(OLD_EXPIRY)
NEW_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(hours=24)
START_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(seconds=60)
def server(payload):
import datetime as dt
import re
import stat
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
ident=str(uuid.UUID(payload['id']));case=root/('renew-'+ident)
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
def check(path,mode):
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
check(authorized,0o644);check(profile,0o644)
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
if payload['phase']=='state':return state()
if payload['phase']=='readback':
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and new==old.replace(microsecond=0)+dt.timedelta(hours=24) and dt.datetime.now(dt.timezone.utc)<old and state()==payload['server_before'],'exact original server expiry/CAS and single 24h extension')
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
def write(path,data,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 out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
COMMON = r'''
$ErrorActionPreference='Stop';$p=$global:RmmRenewalPayload
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.phase-notin@('state','enter','readback','worker')){throw 'Fixed access renewal'}
$root='C:\ProgramData\RmmDevAccess';$case=Join-Path $root ('renew-'+$p.id);$config=Join-Path $root 'bootstrap-public.json';$taskName='RmmDevReverseTunnel';$workerName='RmmDevAccessRenew-'+$p.id
$sys='S-1-5-18';$admin='S-1-5-32-544'
function Safe($path,$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Original regular transport path'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Transport owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty transport ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@($sys,$admin)){throw 'Private transport ACL'}}}
function SafePublic($path){
if($path-notin@((Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub')){throw 'Only two fixed public key files'}
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-gt4096){throw 'Bounded regular public key'};Safe $i.Directory.FullName $true
$ancestor=$i.Directory;while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public key reparse ancestor'};$ancestor=$ancestor.Parent}
$builtin=@(Get-LocalUser|Where-Object{$_.SID.Value-like'*-500'});if($builtin.Count-ne1){throw 'Actual builtin Administrator SID'};$builtinSid=$builtin[0].SID.Value
if(@(Get-LocalGroupMember -SID $admin|Where-Object{$_.SID.Value-ceq$builtinSid}).Count-ne1){throw 'Builtin Administrator membership'}
$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin,$builtinSid)){throw 'Public key trusted owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty public DACL'}
foreach($r in $rules){if($r.AccessControlType-ne'Allow'){throw 'Public key DACL shape'};if($r.IdentityReference.Value-notin@($sys,$admin,$builtinSid)-and([int64]$r.FileSystemRights-band(-bnot[int64]0x1200a9))-ne0){throw 'No public file writer beyond SYSTEM/Admin/builtin Administrator'}}
}
function HashPublic($path){SafePublic $path;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function HashBytes([byte[]]$b){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($b))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function Hash($path){Safe $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function Acl($path){return HashBytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))}
function WriteBytes($path,[byte[]]$b){$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress)))}
function Equal($a,$b){return(($a|ConvertTo-Json -Depth 16 -Compress)-ceq($b|ConvertTo-Json -Depth 16 -Compress))}
function ProcessRecord($process){
if(!$process){return $null};$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;if($owner-cne$sys){throw 'Actual own SYSTEM task process'};$native=[Diagnostics.Process]::GetProcessById([int]$process.ProcessId)
try{if($native.HasExited){throw 'Own process exited while pinning'};$birth=$native.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$native.Dispose()}
return @{pid=[uint32]$process.ProcessId;parent_pid=[uint32]$process.ParentProcessId;creation_filetime=$birth;owner_sid=$owner;image=$process.ExecutablePath;image_sha256=(Get-FileHash -LiteralPath $process.ExecutablePath -Algorithm SHA256).Hash.ToLowerInvariant();command_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($process.CommandLine)))}
}
function OriginalTask{
$task=Get-ScheduledTask -TaskName $taskName;$action=@($task.Actions);$expected='-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'
if($action.Count-ne1-or$action[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$action[0].Arguments-cne$expected-or$task.Principal.UserId-notin@('SYSTEM',$sys)-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'-or$task.Settings.MultipleInstances-cne'IgnoreNew'){throw 'Original task definition/authority'}
return @{xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $taskName))));action_execute=$action[0].Execute;action_arguments_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($action[0].Arguments)));principal=$task.Principal.UserId;logon_type=[string]$task.Principal.LogonType;run_level=[string]$task.Principal.RunLevel;state=[string]$task.State}
}
function State{
Safe $root $true;Safe $config $false;$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'){throw 'Original public transport schema'}
$user=Get-LocalUser -Name 'rmm-dev';if(!$user.Enabled-or!$user.AccountExpires){throw 'Original enabled temporary access account'}
$files=[ordered]@{};foreach($entry in @(@('bootstrap',(Join-Path $root 'Bootstrap-DevAccess.ps1')),@('known_hosts',(Join-Path $root 'known_hosts')),@('public_key',(Join-Path $root 'tunnel_ed25519.pub')),@('sshd_config','C:\ProgramData\ssh\sshd_config'),@('authorized','C:\ProgramData\ssh\administrators_authorized_keys'),@('host_public','C:\ProgramData\ssh\ssh_host_ed25519_key.pub'))){$digest=$null;if($entry[0]-in@('public_key','host_public')){$digest=HashPublic $entry[1]}else{$digest=Hash $entry[1]};$files[$entry[0]]=@{sha256=$digest;acl_sha256=(Acl $entry[1])}}
$key=Join-Path $root 'tunnel_ed25519';Safe $key $false;$k=Get-Item -LiteralPath $key -Force
$known=[IO.File]::ReadAllText((Join-Path $root 'known_hosts'));if($known-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")){throw 'Original strict server host pin'}
$public=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' ';if($public-cne$p.tunnel_public_key){throw 'Original VM tunnel public key'}
$hostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' ';if($hostPublic-cne$p.windows_host_public_key){throw 'Console-confirmed original VM host pin'}
if((Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original only notebook public key'}
$t=OriginalTask;$all=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'});if($all.Count-gt1){throw 'Only original maintainer instance'};$maintainer=$null;$child=$null
if($all.Count-eq1){if($all[0].ExecutablePath-ine$t.action_execute){throw 'Original maintainer image'};$maintainer=ProcessRecord $all[0];$children=@(Get-CimInstance Win32_Process -Filter ('ParentProcessId='+$maintainer.pid) -OperationTimeoutSec 10|Where-Object{$_.Name-ceq'ssh.exe'});if($children.Count-gt1){throw 'Only original SSH child'};if($children.Count-eq1){if($children[0].ExecutablePath-ine'C:\Windows\System32\OpenSSH\ssh.exe'-or$children[0].CommandLine-notlike'*-R*127.0.0.1:22240:127.0.0.1:22222*rmm-win-tunnel@discovery.ease-technologies.de*'){throw 'Original restricted SSH child'};$child=ProcessRecord $children[0]}}
$listeners=@(Get-NetTCPConnection -State Listen -LocalPort 22222 -ErrorAction SilentlyContinue);if(!$listeners.Count-or@($listeners|Where-Object{$_.LocalAddress-cne'127.0.0.1'}).Count){throw 'Existing SSH loopback-only listener'}
return @{config_sha256=(Hash $config);config_acl_sha256=(Acl $config);expires_at=$cfg.expires_at;account_sid=$user.SID.Value;account_expires_filetime=$user.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString();files=$files;private_key_metadata=@{bytes=$k.Length;created=$k.CreationTimeUtc.Ticks.ToString();written=$k.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(Acl $key);private_key_read=$false};server_host_key_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($cfg.server_host_key)));task=$t;maintainer=$maintainer;ssh_child=$child}
}
function ReadIntent{Safe $case $true;Safe (Join-Path $case 'intent.json') $false;$i=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw|ConvertFrom-Json;foreach($field in $p.PSObject.Properties.Name){if($field-cne'phase'-and!(Equal $i.$field $p.$field)){throw 'Same exact original renewal intent'}};return $i}
'''
WORKER = COMMON + r'''
$p=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$p.phase='worker';$null=ReadIntent
if((Hash $PSCommandPath)-cne$p.worker_sha256-or$PSCommandPath-cne(Join-Path $case 'Renew-Transport.ps1')){throw 'Actual fixed own worker source'}
WriteNew (Join-Path $case 'worker-started.json') @{once=$true;utc=[DateTimeOffset]::UtcNow.ToString('o')}
$registration=Get-Content -LiteralPath (Join-Path $case 'worker-registered.json') -Raw|ConvertFrom-Json;if((HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))-cne$registration.worker_xml_sha256){throw 'Exact own worker task definition'}
$now=[DateTimeOffset]::UtcNow;if($p.start_at-cne'2026-11-14T12:56:31+00:00'-or$now-lt[DateTimeOffset]::Parse($p.start_at)-or$now-gt[DateTimeOffset]::Parse($p.start_at).AddMinutes(5)){throw 'Only narrow original expiry+60s worker window'}
$state=State;if($state.expires_at-cne$p.new_expiry-or$state.account_expires_filetime-cne$p.new_account_filetime-or$state.task.state-cne'Ready'-or$null-ne$state.maintainer-or$null-ne$state.ssh_child){throw 'Old task/child must have naturally exited; never kill or repeat'}
foreach($field in @('files','private_key_metadata','account_sid','config_acl_sha256','server_host_key_sha256')){if(!(Equal $p.before.$field $state.$field)){throw 'Original transport identity/ACL changed'}}
if($state.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'Original task XML unchanged'}
foreach($record in @($p.before.maintainer,$p.before.ssh_child)){$current=Get-Process -Id $record.pid -ErrorAction SilentlyContinue;if($current){try{if($current.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-ceq$record.creation_filetime-and!$current.HasExited){throw 'Original pinned process still alive'}}finally{$current.Dispose()}}}
WriteNew (Join-Path $case 'original-task-start-attempt.json') @{once=$true;original_task=$taskName;original_xml_sha256=$state.task.xml_sha256}
Start-ScheduledTask -TaskName $taskName
$deadline=[DateTimeOffset]::UtcNow.AddSeconds(30);do{Start-Sleep -Seconds 1;$after=State;if($after.task.state-ceq'Running'-and$null-ne$after.maintainer-and$null-ne$after.ssh_child){break}}while([DateTimeOffset]::UtcNow-lt$deadline)
if($after.task.state-cne'Running'-or$null-eq$after.maintainer-or$null-eq$after.ssh_child-or$after.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'One fresh original tunnel task start not verified'}
WriteNew (Join-Path $case 'completed.json') @{completed=$true;new_expiry=$p.new_expiry;new_state=$after;no_kill=$true;no_new_authority=$true;download_lease_changed=$false}
Disable-ScheduledTask -TaskName $workerName|Out-Null
WriteNew (Join-Path $case 'worker-disabled.json') @{disabled=$true;retained=$true}
'''
SCRIPT = COMMON + r'''
if($p.phase-ceq'state'){State|ConvertTo-Json -Depth 16 -Compress;exit 0}
if($p.phase-ceq'readback'){$value=@{read_only=$true;state=(State);case_exists=(Test-Path -LiteralPath $case)};if($value.case_exists){$null=ReadIntent;$value['phases']=@{};foreach($name in @('config-replace-attempt','config-replaced','account-expiry-attempt','account-expiry-set','worker-register-attempt','worker-registered','worker-started','original-task-start-attempt','completed','worker-disabled')){$value.phases[$name]=Test-Path -LiteralPath (Join-Path $case ($name+'.json'))}};$value|ConvertTo-Json -Depth 16 -Compress;exit 0}
if($p.phase-cne'enter'-or(Test-Path -LiteralPath $case)-or(Get-ScheduledTask -TaskName $workerName -ErrorAction SilentlyContinue)){throw 'Single new renewal admission; readback only'}
if($p.old_expiry-cne'2026-11-14T12:55:31.254999+00:00'-or[DateTimeOffset]::Parse($p.new_expiry)-ne[DateTimeOffset]::Parse($p.old_expiry).AddHours(24).AddTicks(-2549990)-or[DateTimeOffset]::UtcNow-ge[DateTimeOffset]::Parse($p.old_expiry)){throw 'Exact original window and 24h renewal'}
$before=State;if(!(Equal $before $p.before)-or$before.task.state-cne'Running'-or$null-eq$before.maintainer-or$null-eq$before.ssh_child){throw 'Concrete original live transport CAS'}
New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
$original=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$original,$false);Safe $original $false
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json;$cfg.expires_at=$p.new_expiry;$candidate=Join-Path $case 'bootstrap-public.next';WriteNew $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
WriteNew (Join-Path $case 'config-replace-attempt.json') @{original_sha256=$before.config_sha256;native_backup=$nativeBackup}
if((Hash $config)-cne$before.config_sha256-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$sddl=(Get-Acl -LiteralPath $config).Sddl;[IO.File]::Replace($candidate,$config,$nativeBackup);$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $config -AclObject $acl
WriteNew (Join-Path $case 'config-replaced.json') @{sha256=(Hash $config);native_backup_sha256=(Hash $nativeBackup)}
WriteNew (Join-Path $case 'account-expiry-attempt.json') @{account='rmm-dev';old_filetime=$before.account_expires_filetime;new_filetime=$p.new_account_filetime}
$currentUser=Get-LocalUser -Name 'rmm-dev';if($currentUser.SID.Value-cne$before.account_sid-or$currentUser.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$before.account_expires_filetime){throw 'Immediate original account SID/expiry CAS'}
Set-LocalUser -Name 'rmm-dev' -AccountExpires ([DateTimeOffset]::Parse($p.new_expiry).LocalDateTime)
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$p.new_account_filetime){throw 'Actual exact account expiry'};WriteNew (Join-Path $case 'account-expiry-set.json') @{new_filetime=$p.new_account_filetime}
$worker=Join-Path $case 'Renew-Transport.ps1';$bytes=[Convert]::FromBase64String($p.worker_base64);if((HashBytes $bytes)-cne$p.worker_sha256){throw 'Exact reviewed renewal worker'};WriteBytes $worker $bytes;Safe $worker $false
$action=New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+$worker+'"')
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::FromMinutes(2)) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$trigger=New-ScheduledTaskTrigger -Once -At ([DateTimeOffset]::Parse($p.start_at).LocalDateTime)
WriteNew (Join-Path $case 'worker-register-attempt.json') @{name=$workerName;source_sha256=$p.worker_sha256;once=$true;start_at=$p.start_at}
Register-ScheduledTask -TaskName $workerName -Action $action -Trigger $trigger -Settings $settings -Principal $principal|Out-Null
WriteNew (Join-Path $case 'worker-registered.json') @{registered=$true;original_task_unmodified=$true;worker_xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))}
@{entered=$true;planned_gap=$true;start_at=$p.start_at;new_expiry=$p.new_expiry;original_task_restarted_now=$false;download_lease_changed=$false}|ConvertTo-Json -Compress
'''
# Worker sets its own fixed payload before COMMON examines it.
WORKER = "$global:RmmRenewalPayload=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$global:RmmRenewalPayload.phase='worker'\n" + WORKER
class Access(pair.Access):
def stage_controller(self,path):
name='DevAccessRenewal.ps1';digest=sha(path)
prepare=pair.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name)
observed=self.powershell(prepare,dict(sha256=digest))
if not observed['already_uploaded']:
access=cb.contract.protected_json(self.root/'credentials/windows-dev-access.json');prefix=access['ssh_prefix']
args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]]
target='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+name
result=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
require(result.returncode==0,'single exact renewal source transfer; no retry')
require(self.powershell(prepare,dict(sha256=digest))['already_uploaded'] is True,'exact staged controller')
def rpc(self, payload):
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(server)+'\ntry:\n print(json.dumps(server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed renewal server RPC')
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server renewal incomplete; readback only');return value
def windows(self,payload):
# Existing fixed access bridge; no credentials copy or Main writes.
launch=pair.LAUNCH.replace('SystemPipeUpgrade.ps1','DevAccessRenewal.ps1').replace('RmmPipeUpgradePayload','RmmRenewalPayload')
return self.powershell(launch,dict(sha256=pair.raw_sha(SCRIPT.encode()),payload=payload),timeout=150)
def load(access,ident):
require(str(uuid.UUID(ident))==ident,'canonical case');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
require(intent['runner_sha256']==sha(__file__) and intent['worker_sha256']==pair.raw_sha(WORKER.encode()) and intent['access_root']==str(access.root),'original immutable renewal source/accessroot')
return folder,intent
def prepare(access):
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
payload=dict(id=ident,phase='state',tunnel_public_key=console['tunnel_public_key'],windows_host_public_key=console['windows_host_public_key'],old_expiry=OLD_EXPIRY,new_expiry=NEW_UTC.isoformat(),start_at=START_UTC.isoformat(),new_account_filetime=str((int(NEW_UTC.timestamp())+11644473600)*10000000),worker_sha256=pair.raw_sha(WORKER.encode()),worker_base64=base64.b64encode(WORKER.encode()).decode())
require(cb.contract.now()<OLD_UTC,'original lease still active')
save(folder/'prepare-intent.json',dict(id=ident,runner_sha256=sha(__file__),no_new_authority=True))
source=folder/'DevAccessRenewal.ps1';pair.write_bytes(source,SCRIPT.encode());access.stage_controller(source)
before=access.windows(payload);server_before=access.rpc(payload)
require(before['files']['bootstrap']['sha256']==sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'original fixed maintainer source')
require(before['expires_at']==OLD_EXPIRY and before['server_host_key_sha256']==server_before['server_host_key_sha256'] and server_before['expiry']==OLD_UTC.strftime('%Y%m%d%H%M%SZ'),'same original windows/server expiry/host pin')
payload.update(before=before,server_before=server_before)
intent=dict(id=ident,runner_sha256=sha(__file__),worker_sha256=payload['worker_sha256'],access_root=str(access.root),payload=payload)
save(folder/'intent.json',intent)
print(json.dumps(dict(id=ident,prepared=True,review_sha256=sha(folder/'intent.json'),new_expiry=payload['new_expiry'],start_at=payload['start_at'],planned_short_gap=True)))
def run(access,ident,phase,review_sha=None):
folder,intent=load(access,ident);payload=dict(intent['payload'],phase='readback' if phase=='readback' else 'enter')
if phase=='enter':
require(review_sha==sha(folder/'intent.json'),'explicit reviewed renewal intent SHA')
save(folder/'server-enter-attempt.json',dict(once=True))
server_result=access.rpc(payload);require(server_result.get('completed') is True,'server expiry CAS first');save(folder/'server-entered.json',server_result)
save(folder/'windows-enter-attempt.json',dict(once=True))
observed=access.windows(payload);save(folder/'windows-entered.json',observed)
else:
server_result=access.rpc(payload);observed=access.windows(payload);save(folder/('readback-'+str(uuid.uuid4())+'.json'),dict(server=server_result,windows=observed))
print(json.dumps(dict(id=ident,phase=phase,server_expiry=server_result.get('expiry'),windows=observed,main_config_updated=False)))
def main():
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=Access(args.access_root)
if args.phase=='prepare':require(not(args.id or args.review_sha256),'new readonly renewal baseline');prepare(access)
else:require(args.id and ((args.phase=='enter')==bool(args.review_sha256)),'same case and reviewed intent for enter');run(access,args.id,args.phase,args.review_sha256)
if __name__=='__main__':
try:main()
except Exception as error:print('DEV_ACCESS_RENEWAL_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
@@ -0,0 +1,193 @@
#!/usr/bin/env python3
"""One reviewed recovery of the unchanged failed6d2 joint upgrade; no retries.
Uses explicit File.Replace backup paths, preserving the original failed source,
attempt, four backups, journals and intent. Readback never swaps or starts.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import uuid
import client_bootstrap as cb
import system_delegation_upgrade as u
CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
ORIGINAL_SOURCE = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
STATE = cb.EVIDENCE / 'system-delegation-recovery'
require = cb.contract.require
PREFIX = u.SCRIPT.split('\nCheckControl $boot $true\n', 1)[0]
SCRIPT = PREFIX + r'''
$r=$global:RmmDelegationRecoveryPayload
if(!$r-or[guid]::ParseExact($r.recovery_id,'D').ToString()-cne$r.recovery_id-or$r.phase-notin@('prepare','enter','readback')-or$p.id-cne'6d2df065-0877-41c4-983c-2c9fdb6e5437'-or$r.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Only the original failed6d recovery'}
CheckControl $boot $true
$ownScript=Join-Path (Join-Path $boot $r.script_sha256) 'SystemDelegationRecovery.ps1'
if($PSCommandPath-cne$ownScript-or(Hash $PSCommandPath)-cne$r.script_sha256){throw 'Exact actually executing recovery source'}
CheckControl $ownScript $false
$intent=ReadIntent
$recovery=Join-Path $boot ('system-delegation-recovery-'+$r.recovery_id)
$recoveryActive=Join-Path $boot 'system-delegation-6d2-recovery-once.json'
function ReadService($role){$name=$agentName;if($role-ceq'helper'){$name=$helperName};$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10;if(!$s){throw 'Fixed existing service'};return @{state=$s.State;pid=$s.ProcessId;account=$s.StartName;mode=$s.StartMode;path=$s.PathName;exit_code=$s.ExitCode}}
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
function RecoveryReadback{
$original=[ordered]@{};foreach($name in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$original[$name]=Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))}
$own=[ordered]@{};foreach($name in @('intent','prepared','enter-attempt','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-intent','agent-start-intent','entered')){$own[$name]=Test-Path -LiteralPath (Join-Path $recovery ($name+'.json'))}
return @{read_only=$true;original_id=$p.id;recovery_id=$r.recovery_id;hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)};service=(ReadService 'agent');helper_service=(ReadService 'helper');original_phases=$original;recovery_phases=$own;recovery_active_exists=(Test-Path -LiteralPath $recoveryActive);no_repeated_start=$true}
}
if($r.phase-ceq'readback'){RecoveryReadback|ConvertTo-Json -Depth 20 -Compress;exit 0}
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class RmmDelegationRecoveryFileId {
[StructLayout(LayoutKind.Sequential)] public struct Id {
public ulong VolumeSerialNumber;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)] public byte[] FileId;
}
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, out Id info, uint length);
}
'@
function FileIdentity($path){
Check $path $false;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{$id=New-Object RmmDelegationRecoveryFileId+Id;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmDelegationRecoveryFileId+Id]);if($size-ne24-or![RmmDelegationRecoveryFileId]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Exact native file identity'}
return [ordered]@{volume_serial=$id.VolumeSerialNumber.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.FileId)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path)}
}finally{$file.Dispose()}
}
function CheckOriginalStopped{
foreach($name in @('intent','agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt')){CheckControl (Join-Path $folder ($name+'.json')) $false}
foreach($name in @('helper-replace-attempt','settings-replace-attempt','pin-replace-attempt','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){if(Test-Path -LiteralPath (Join-Path $folder ($name+'.json'))){throw 'Original case progressed; no recovery replay'}}
$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json
$current=State $false
if($current.service.state-cne'Stopped'-or$current.helper_service.state-cne'Stopped'){throw 'Both own original services must remain stopped'}
Preserved $frozen $current $true
$checks=@(@('agent',$p.old_agent,$p.new_agent),@('helper',$p.old_helper,$p.new_helper),@('settings',$p.old_policy,$p.new_policy),@('pin',$p.old_pin,$p.new_pin))
foreach($item in $checks){$backup=Join-Path $folder ($item[0]+'-original');CheckControl $backup $false;if((Hash $backup)-cne$item[1]){throw 'Original exact backup'};$receipt=Get-Content -LiteralPath (Join-Path $folder ($item[0]+'-backup.json')) -Raw|ConvertFrom-Json;if($receipt.sha256-cne$item[1]){throw 'Original backup receipt'}}
$attempt=Get-Content -LiteralPath (Join-Path $folder 'agent-replace-attempt.json') -Raw|ConvertFrom-Json
if($attempt.old_sha256-cne$p.old_agent-or$attempt.new_sha256-cne$p.new_agent){throw 'Original unchanged failed agent attempt'}
if((Hash (Join-Path $folder 'agent-candidate'))-cne$p.new_agent){throw 'Retain exact original agent candidate'}
foreach($label in @('helper','settings','pin')){if(Test-Path -LiteralPath (Join-Path $folder ($label+'-candidate'))){throw 'No other old candidate expected'}}
if((Hash (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe'))-cne$p.new_agent-or(Hash (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe'))-cne$p.new_helper-or(Hash (Join-Path $folder 'new-helper.json'))-cne$p.new_policy-or(Hash (Join-Path $folder 'new-agent-pin.json'))-cne$p.new_pin){throw 'All four complete new sources'}
$current['recovery_file_identities']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);agent_candidate=(FileIdentity (Join-Path $folder 'agent-candidate'))}
return $current
}
if($r.phase-ceq'prepare'){
if((Test-Path -LiteralPath $recovery)-or(Test-Path -LiteralPath $recoveryActive)){throw 'Existing recovery: readback only'}
$before=CheckOriginalStopped
New-Item -ItemType Directory -Path $recovery|Out-Null;CheckControl $recovery $true
WriteNew $recoveryActive @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;create_only=$true}
WriteNew (Join-Path $recovery 'intent.json') @{original_id=$p.id;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256;original_payload=$p;before=$before}
WriteNew (Join-Path $recovery 'prepared.json') @{prepared=$true;no_service_changes=$true;original_failed_attempt_retained=$true}
@{prepared=$true;original_id=$p.id;recovery_id=$r.recovery_id;both_stopped=$true;preserved=$true}|ConvertTo-Json -Compress;exit 0
}
CheckControl $recovery $true;foreach($name in @('intent.json','prepared.json')){CheckControl (Join-Path $recovery $name) $false};CheckControl $recoveryActive $false
$saved=Get-Content -LiteralPath (Join-Path $recovery 'intent.json') -Raw|ConvertFrom-Json;$currentActive=Get-Content -LiteralPath $recoveryActive -Raw|ConvertFrom-Json
if($saved.original_id-cne$p.id-or$saved.recovery_id-cne$r.recovery_id-or$saved.script_sha256-cne$r.script_sha256-or!(JsonEqual $saved.original_payload $p)-or$currentActive.original_id-cne$p.id-or$currentActive.recovery_id-cne$r.recovery_id-or$currentActive.script_sha256-cne$r.script_sha256){throw 'Exact original recovery admission'}
if(Test-Path -LiteralPath (Join-Path $recovery 'enter-attempt.json')){throw 'Recovery already attempted: readback only'}
$before=CheckOriginalStopped;Preserved $saved.before $before $true
if(!(JsonEqual $saved.before.recovery_file_identities $before.recovery_file_identities)){throw 'Original destination/candidate file IDs or ACL/bytes changed'}
WriteNew (Join-Path $recovery 'enter-attempt.json') @{enter_once=$true;recovery_id=$r.recovery_id;script_sha256=$r.script_sha256}
function RecoverSwap($label,$destination,$source,$oldHash,$newHash,[bool]$reuse){
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'No component start during four-file recovery'}
$candidate=Join-Path $folder ($label+'-candidate');$nativeBackup=Join-Path $recovery ($label+'-native-original')
$oldReceipt=Get-Content -LiteralPath (Join-Path $folder ($label+'-backup.json')) -Raw|ConvertFrom-Json;$sddl=$oldReceipt.original_sddl
if((Hash $destination)-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))-or(Test-Path -LiteralPath $nativeBackup)){throw 'Exact old destination/backup/ACL and new source CAS'}
if($reuse){if((Hash $candidate)-cne$newHash){throw 'Retain original exact candidate'}}else{if(Test-Path -LiteralPath $candidate){throw 'Candidate exists; no overwrite'};[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate}
if((Hash $candidate)-cne$newHash){throw 'Complete candidate'}
$destinationIdentity=FileIdentity $destination;$candidateIdentity=FileIdentity $candidate
if(!(JsonEqual $destinationIdentity $before.recovery_file_identities.$label)-or($reuse-and!(JsonEqual $candidateIdentity $before.recovery_file_identities.agent_candidate))){throw 'Fresh native CAS identities/ACL/bytes'}
WriteNew (Join-Path $recovery ($label+'-replace-attempt.json')) @{old_sha256=$oldHash;new_sha256=$newHash;native_backup=$nativeBackup;recovery_id=$r.recovery_id;source_sha256=$r.script_sha256;destination_identity=$destinationIdentity;candidate_identity=$candidateIdentity}
[IO.File]::Replace($candidate,$destination,$nativeBackup)
PrivateBackupAcl $nativeBackup
$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne(BytesHash ([Text.Encoding]::UTF8.GetBytes($sddl)))){throw 'Actual exact replacement and explicit original backup'}
$receipt=@{old_sha256=$oldHash;new_sha256=$newHash;backup_sha256=(Hash (Join-Path $folder ($label+'-original')));acl_sha256=(AclHash $destination);native_backup_sha256=(Hash $nativeBackup);recovery_id=$r.recovery_id;source_sha256=$r.script_sha256}
WriteNew (Join-Path $recovery ($label+'-replaced.json')) $receipt
WriteNew (Join-Path $folder ($label+'-replaced.json')) $receipt
}
try{
RecoverSwap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent $true
RecoverSwap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper $false
RecoverSwap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy $false
RecoverSwap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin $false
$swapped=State $true;Preserved $before $swapped $true
if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files checked before first start'}
$swapped['recovery_id']=$r.recovery_id;$swapped['recovery_source_sha256']=$r.script_sha256
WriteNew (Join-Path $recovery 'swapped.json') $swapped;WriteNew (Join-Path $folder 'swapped.json') $swapped
WriteNew (Join-Path $recovery 'helper-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'helper'
WriteNew (Join-Path $recovery 'agent-start-intent.json') @{recovery_id=$r.recovery_id;source_sha256=$r.script_sha256};StartOnce 'agent'
$after=State $true;Preserved $intent.before $after $false;Preserved $before $after $false
$after['recovery_id']=$r.recovery_id;$after['recovery_source_sha256']=$r.script_sha256
WriteNew (Join-Path $recovery 'entered.json') $after;WriteNew (Join-Path $folder 'entered.json') $after
@{entered=$true;original_id=$p.id;recovery_id=$r.recovery_id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
}catch{WriteNew (Join-Path $recovery ('incomplete-'+[guid]::NewGuid().ToString()+'.json')) @{error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;readback_only=$true;no_retry=$true};throw}
'''
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1')
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationRecovery.ps1').replace('RmmTransportPayload', 'RmmDelegationRecoveryPayload')
# Prefix reads the immutable original payload; the recovery data is separate.
LAUNCH = LAUNCH.replace('& $script', '$global:RmmDelegationUpgradePayload=$p.payload.original_payload\n& $script')
def load(recovery_id):
require(str(uuid.UUID(recovery_id)) == recovery_id, 'canonical recovery UUID')
folder = STATE / recovery_id; intent = cb.contract.protected_json(folder / 'intent.json')
require(u.sha(u.__file__) == ORIGINAL_SOURCE and intent['runner_sha256'] == u.sha(__file__) and intent['script_sha256'] == u.raw_sha(SCRIPT.encode()), 'original and new source remain immutable')
_, original = u.load_case(CASE)
require(intent['original_intent_sha256'] == u.sha(u.STATE / CASE / 'intent.json') and intent['original_payload'] == original['payload'], 'unchanged original case')
return folder, intent
def remote(intent, phase):
original_action = 'readback' if phase == 'readback' else 'enter'
payload = dict(recovery_id=intent['recovery_id'], phase=phase, script_sha256=intent['script_sha256'], original_payload=dict(intent['original_payload'], action=original_action))
return cb.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=payload), timeout=180, remote_signed=True)
def prepare():
require(u.sha(u.__file__) == ORIGINAL_SOURCE, 'original failed runner must not change')
_, original = u.load_case(CASE)
original_folder = u.STATE / CASE
require((original_folder / 'enter-attempt.json').is_file() and (original_folder / 'reply-incomplete.json').is_file(), 'actual original failed entry retained')
u.original_helper.private_dir(STATE)
recovery_id = str(uuid.uuid4()); folder = STATE / recovery_id; folder.mkdir(mode=0o700)
intent = dict(schema_version=1, type='rmm.windows.passive-joint-recovery', recovery_id=recovery_id, original_id=CASE, original_payload=original['payload'], original_intent_sha256=u.sha(original_folder / 'intent.json'), runner_sha256=u.sha(__file__), script_sha256=u.raw_sha(SCRIPT.encode()))
u.save(folder / 'intent.json', intent)
source = folder / 'SystemDelegationRecovery.ps1'
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno())
u.original_helper.transfer(source, 'SystemDelegationRecovery.ps1', intent['script_sha256'], PREPARE)
result = remote(intent, 'prepare'); u.save(folder / 'prepared.json', result)
require(result.get('prepared') is True and result.get('both_stopped') is True and result.get('preserved') is True, 'actual preserved recovery admission')
print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'prepared': True, 'no_start': True}))
def run(recovery_id, phase):
folder, intent = load(recovery_id)
if phase == 'enter':
require(cb.contract.protected_json(folder / 'prepared.json')['prepared'] is True, 'actual prepared admission')
u.save(folder / 'enter-attempt.json', {'once': True, 'lost_reply_readback_only': True})
try:
result = remote(intent, phase)
except Exception as error:
u.save(folder / ('reply-incomplete-' + str(uuid.uuid4()) + '.json'), {'error_type': type(error).__name__, 'readback_only': True})
raise
u.save(folder / ('entered.json' if phase == 'enter' else 'readback-' + str(uuid.uuid4()) + '.json'), result)
print(json.dumps({'original_id': CASE, 'recovery_id': recovery_id, 'entered': result.get('entered', False), 'read_only': result.get('read_only', False), 'original_phases': result.get('original_phases'), 'recovery_phases': result.get('recovery_phases')}))
def main():
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=['prepare', 'enter', 'readback']); parser.add_argument('--id'); args = parser.parse_args()
os.umask(0o077)
if args.phase == 'prepare':
require(args.id is None, 'create a new recovery admission'); prepare()
else:
require(args.id is not None, 'exact existing recovery UUID required'); run(args.id, args.phase)
if __name__ == '__main__':
main()
+368
View File
@@ -0,0 +1,368 @@
#!/usr/bin/env python3
"""Source-bound Pipe-v2 pack and create-once native units, never deployment.
The access root only supplies the existing pinned SSH transport and immutable
native Core proofs. No credentials/devstate symlinks, copies, services or jobs.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import uuid
CODE = Path(__file__).resolve().parents[2]
ACCESS = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
sys.path.insert(0, str(ACCESS / 'deploy/windows'))
sys.path.insert(0, str(ACCESS / 'deploy'))
import client_bootstrap as cb
import auto_transport_acceptance as auto
import runtime_upgrade as previous
require = cb.contract.require
BUILD = CODE / 'devstate/windows-pipe-drain-build'
NATIVE = CODE / 'devstate/windows-client/native-pipe-v2'
# These imported transports read their original protected access configuration.
# Their new local upload/error receipts belong to this isolated checkout.
cb.EVIDENCE = CODE / 'devstate/windows-client'
CORE = ACCESS / 'devstate/core-no-start/build-de37ee99-11bf-465b-9519-45ad8f6e5b87/manifest.json'
CORE_SHA = '1bc082031fcad20d5a519b0004f63d499dbba2ea9ce25d56230d48d2556d474b'
LOCAL = CODE / 'devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json'
LOCAL_SHA = 'a7e3c604d4ad19feed0323ac23aa7a0290b6fb93bc57649cafbadbe5f293b1d4'
TARGET = 'x86_64-pc-windows-gnu'
NAMES = {'agent': 'rmm-agent-windows.exe', 'helper': 'rmm-helper-windows.exe',
'probe': 'RuntimeStateProbe.exe', 'system_probe': 'SystemStateProbe.exe',
'lib': 'windows-tests-lib.exe', 'bin': 'windows-tests-bin.exe'}
# Expected V2 native lists: unchanged names, two existing codec cases extended.
TESTS = {
'lib': sorted([
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
'clock::tests::suspend_closes_until_actual_post_resume_sync',
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
'clock::tests::wall_step_and_overflow_fail_closed',
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
'helper_ipc::tests::serialization_refuses_oversized_frame',
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
'helper_system::tests::service_adapter_exposes_only_implemented_states',
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
'journal::tests::durable_reopen_ack_identity_and_single_process',
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
'native::tests::boot_identity_survives_independent_native_queries',
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted']),
'bin': sorted([
'https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses'])}
COUNTS = {'lib': 23, 'bin': 7}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(path, value):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
cb.contract.write_private(path, value)
def private_file(path):
path = Path(path)
require(not path.is_symlink() and not path.parent.is_symlink(), 'private regular path')
info = path.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid()
and stat.S_IMODE(info.st_mode) == 0o600, 'private regular owner/mode')
return path
def sources():
require(ACCESS.is_dir() and not ACCESS.is_symlink() and cb.ROOT == ACCESS,
'original access checkout only; no copied configuration')
names = {'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'proto/agent.proto',
'deploy/windows/system_pipe_acceptance.py', 'docs/windows-helper-pipe-drain.md'}
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates').glob('*/Cargo.toml'))
for crate in ('agent-windows', 'agent-core', 'domain', 'protocol'):
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates' / crate).rglob('*')
if p.is_file() and p.suffix in ('.rs', '.c', '.h', '.idl', '.toml'))
names.update('crates/agent/src/' + n + '.rs' for n in ('https_channel', 'transport', 'wire_channel'))
require(all((CODE / n).is_file() and not (CODE / n).is_symlink() for n in names), 'complete fixed build sources')
transport = {}
for module in tuple(sys.modules.values()):
raw = getattr(module, '__file__', None)
if raw:
path = Path(raw).resolve()
if path.is_relative_to(ACCESS / 'deploy') and path.suffix == '.py':
transport[str(path.relative_to(ACCESS))] = sha(path)
require('deploy/windows/client_bootstrap.py' in transport, 'actual transport source binding')
return {'code': {n: sha(CODE / n) for n in sorted(names)}, 'access_transport': dict(sorted(transport.items()))}
def core_proof():
require(sha(CORE) == CORE_SHA, 'exact original Linux-first Core manifest')
manifest = cb.contract.protected_json(CORE)
result = {'manifest_sha256': CORE_SHA}
for platform, count in (('linux', 80), ('windows', 58)):
path = CORE.parent / (platform + '-passed.json')
proof = cb.contract.protected_json(path)
require(proof['verified'] is True and proof['platform'] == platform
and proof['manifest_sha256'] == CORE_SHA, 'actual same-manifest native Core proof')
actual = proof['native']['reports']
require(set(actual) == set(manifest['test_counts'][platform])
and sum(len(v['names']) for v in actual.values()) == count, 'all native Core reports')
for kind, item in actual.items():
n = manifest['test_counts'][platform][kind]
output = base64.b64decode(item['stdout_b64'], validate=True)
require(item['exit_code'] == 0 and item['timed_out'] is False
and item['names'] == manifest['test_names'][platform][kind]
and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
and re.search(rb'test result: ok\. ' + str(n).encode()
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', output),
'complete actual native Core result')
result[platform] = {'proof_sha256': sha(path), 'case_id': proof['case_id']}
for name, digest in manifest['source_files'].items():
if name.startswith(('crates/agent-core/', 'crates/domain/', 'crates/protocol/', 'proto/')):
require(sha(CODE / name) == digest, 'isolated common source equals actual native Core proof')
return result
def reused_qualification():
require(sha(LOCAL) == LOCAL_SHA, 'exact retained local qualification')
value = cb.contract.protected_json(LOCAL)
require(value['type'] == 'rmm.windows.pipe-drain-local-qualification'
and value['source_before_after_equal'] is True and value['native_executed'] is False
and value['clock_qualified'] is False and value['native_counts_expected'] == COUNTS
and len(value['commands']) == 4 and all(c['exit_code'] == 0 for c in value['commands']),
'actual previous cross-Clippy/release/unit-link qualification')
for name, digest in value['source_files'].items():
require(sha(CODE / name) == digest, 'all original qualified inputs remain unchanged')
for item in list(value['artifacts'].values()) + list(value['unit_links'].values()):
path = Path(item['path'])
target = LOCAL.parent / 'target'
require(path.is_relative_to(target), 'qualified link under private target')
current = target
for part in ('',) + path.relative_to(target).parts:
if part:
current = current / part
info = current.lstat()
require(not stat.S_ISLNK(info.st_mode) and info.st_uid in (0, os.getuid())
and info.st_mode & 0o022 == 0, 'protected original compiler output')
require(stat.S_ISREG(path.lstat().st_mode) and sha(path) == item['sha256']
and path.stat().st_size == item['bytes'], 'retained exact qualified links')
require(re.search(r'^pub const ADAPTER_QUALIFIED: bool = false;$',
(CODE / 'crates/agent-windows/src/clock.rs').read_text(), re.M), 'production clock remains closed')
return value
def command(args, folder, name):
with (folder / (name + '.stdout')).open('xb') as out, (folder / (name + '.stderr')).open('xb') as err:
result = subprocess.run(args, stdout=out, stderr=err)
save(folder / (name + '.json'), {'exit_code': result.returncode, 'local_only': True, 'arguments': args})
require(result.returncode == 0, 'local build failed; original stdout/stderr retained')
def build():
before, common, prior = sources(), core_proof(), reused_qualification()
folder = BUILD / ('build-' + str(uuid.uuid4()))
folder.mkdir(mode=0o700, parents=True)
save(folder / 'source-before.json', before)
save(folder / 'reused-qualification.json', {'path': str(LOCAL), 'sha256': LOCAL_SHA, 'value': prior})
image = prior['build_image']
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable compiler image')
target = LOCAL.parent / 'target'
# Only these two RELEASE examples were missing. Original Clippy, EXEs and
# unit links are hash-bound above and are deliberately not rerun/rebuilt.
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
'-v', str(CODE) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target',
'--entrypoint', 'cargo', image, 'build', '--manifest-path', '/src/Cargo.toml', '--locked', '--offline',
'--target', TARGET, '-p', 'rmm-agent-windows', '--features', 'system-helper', '--release',
'--example', 'runtime_state', '--example', 'system_state'], folder, 'release-examples')
selected = {'agent': Path(prior['artifacts']['agent']['path']), 'helper': Path(prior['artifacts']['helper']['path']),
'lib': Path(prior['unit_links']['lib']['path']), 'bin': Path(prior['unit_links']['bin']['path']),
'probe': target / TARGET / 'release/examples/runtime_state.exe',
'system_probe': target / TARGET / 'release/examples/system_state.exe'}
artifacts = {}
for kind, original in selected.items():
output, retained = folder / NAMES[kind], folder / (NAMES[kind] + '.linked')
original_sha = sha(original)
for destination in (retained, output):
shutil.copyfile(original, destination)
destination.chmod(0o600)
if kind in COUNTS:
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(folder) + ':/artifacts',
'--entrypoint', 'x86_64-w64-mingw32-strip', image, '--strip-debug', '/artifacts/' + NAMES[kind]],
folder, 'strip-' + kind)
require(sha(original) == sha(retained) == original_sha, 'original links retained unchanged')
data = output.read_bytes()
offset = int.from_bytes(data[60:64], 'little')
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows AMD64 PE')
artifacts[kind] = {'path': str(output), 'name': NAMES[kind], 'sha256': sha(output), 'bytes': len(data),
'original_link_path': str(retained), 'original_link_sha256': original_sha,
'release_build': kind not in COUNTS, 'debug_stripped': kind in COUNTS}
require(sources() == before and core_proof() == common and reused_qualification() == prior,
'compiler inputs, original links and native Core proof unchanged before/after')
manifest = {'schema_version': 1, 'type': 'rmm.windows.pipe-v2-build', 'source_files': before,
'source_before_after_equal': True, 'code_root': str(CODE), 'access_root': str(ACCESS),
'artifacts': artifacts, 'test_names_expected': TESTS, 'native_counts_expected': COUNTS,
'core_native_proofs': common, 'reused_local_qualification': {'path': str(LOCAL), 'sha256': LOCAL_SHA},
'build_image_id': image, 'transport_version': 2, 'raw_v1_controls_qualified': False,
'production_clock_qualified': False, 'native_executed': False}
save(folder / 'manifest.json', manifest)
print(json.dumps({'manifest': str(folder / 'manifest.json'), 'native_executed': False}))
SCRIPT = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('run','read')-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Pipe V2 unit case'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('native-pipe-v2-'+$p.id)
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private unit type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty unit ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit ACL'}}}
function WriteNew($path,$value){$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function ReadPrivate($path){Safe $path $false;if((Get-Item -LiteralPath $path).Length-gt196608){throw 'Unit report bound'};return (Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
Safe $root $true
if($p.action-eq'read'){
if(!(Test-Path -LiteralPath $case)){@{case_exists=$false;completed=$false;readback_only=$true}|ConvertTo-Json -Compress;exit 0}
Safe $case $true;$i=ReadPrivate (Join-Path $case 'intent.json');if($i.manifest_sha256-cne$p.manifest_sha256){throw 'Original unit intent'}
$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){ReadPrivate $result|ConvertTo-Json -Depth 16 -Compress;exit 0}
$lists=@{};$reports=@{};foreach($kind in @('lib','bin')){$file=Join-Path $case ('list-'+$kind+'.json');if(Test-Path -LiteralPath $file){$lists[$kind]=ReadPrivate $file};$file=Join-Path $case ('report-'+$kind+'.json');if(Test-Path -LiteralPath $file){$reports[$kind]=ReadPrivate $file}}
@{case_exists=$true;completed=$false;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $case 'started.json'));lists=$lists;reports=$reports}|ConvertTo-Json -Depth 16 -Compress;exit 0
}
if(Test-Path -LiteralPath $case){throw 'Existing unit case: readback only'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
function Run($exe,$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit process start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(30000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt65536-or$e.Result.Length-gt65536){throw 'Bounded unit output collection'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout=$o.Result;stderr=$e.Result}}finally{$c.Dispose()}}
$lists=@{};$paths=@{}
foreach($kind in @('lib','bin')){
$a=$p.artifacts.$kind;if($a.sha256-notmatch'^[a-f0-9]{64}$'-or$a.name-cne('windows-tests-'+$kind+'.exe')){throw 'Fixed test artifact'};$folder=Join-Path $root $a.sha256;Safe $folder $true;$exe=Join-Path $folder $a.name;Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$a.sha256-or(Get-Item -LiteralPath $exe).Length-ne$a.bytes){throw 'Exact unit artifact'}
$listed=Run $exe '--list --format terse';[string[]]$names=@($listed.stdout-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($names,[StringComparer]::Ordinal)
$value=@{sha256=$a.sha256;names=$names;listed=$listed};WriteNew (Join-Path $case ('list-'+$kind+'.json')) $value
if($listed.exit_code-ne0-or$listed.timed_out-or$names.Count-ne$p.counts.$kind-or(($names-join"`n")-cne(@($p.test_names.$kind)-join"`n"))){throw 'Exact complete native list before ANY tests'};$lists[$kind]=$value;$paths[$kind]=$exe
}
WriteNew (Join-Path $case 'both-lists-verified.json') @{manifest_sha256=$p.manifest_sha256;both_lists_verified_before_any_test=$true}
WriteNew (Join-Path $case 'started.json') @{start_once=$true};$reports=@{}
foreach($kind in @('lib','bin')){$run=Run $paths[$kind] '--test-threads=1';$value=@{sha256=$lists[$kind].sha256;names=$lists[$kind].names;listed=$lists[$kind].listed;result=$run};WriteNew (Join-Path $case ('report-'+$kind+'.json')) $value;$reports[$kind]=$value;if($run.exit_code-ne0-or$run.timed_out){throw 'Native unit execution failed; readback only'}}
$value=@{completed=$true;manifest_sha256=$p.manifest_sha256;reports=$reports;both_lists_verified_before_any_test=$true;bootstrap_administrator_units=$true;local_service_proof=$false;native_pipe_proof=$false;rmm_jobs=$false;product_state_writes=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
'''
def verified(path, current=True):
path = private_file(path)
require(path.parent.parent == BUILD and path.parent.name.startswith('build-')
and str(uuid.UUID(path.parent.name[6:])) == path.parent.name[6:], 'fixed private build namespace')
value = cb.contract.protected_json(path)
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['schema_version'] == 1
and value['source_before_after_equal'] is True and value['production_clock_qualified'] is False
and value['transport_version'] == 2 and value['raw_v1_controls_qualified'] is False
and value['native_executed'] is False
and value['reused_local_qualification'] == {'path': str(LOCAL), 'sha256': LOCAL_SHA}
and value['native_counts_expected'] == COUNTS and value['test_names_expected'] == TESTS
and value['code_root'] == str(CODE) and value['access_root'] == str(ACCESS), 'exact V2 build profile')
if current:
require(value['source_files'] == sources() and value['core_native_proofs'] == core_proof(), 'current source/Core proof binding')
require(set(value['artifacts']) == set(NAMES), 'six exact artifacts')
for kind, item in value['artifacts'].items():
output, original = private_file(item['path']), private_file(item['original_link_path'])
require(output == path.parent / NAMES[kind] and original == path.parent / (NAMES[kind] + '.linked')
and sha(output) == item['sha256'] and output.stat().st_size == item['bytes']
and sha(original) == item['original_link_sha256']
and item['release_build'] is (kind not in COUNTS)
and item['debug_stripped'] is (kind in COUNTS), 'exact retained delivery and original link')
return value
def native(path, ident=None):
path = path.resolve()
manifest = verified(path, current=ident is None)
if ident is None:
ident = str(uuid.uuid4());folder = NATIVE / ident;folder.mkdir(mode=0o700, parents=True)
save(folder / 'intent.json', {'id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
'runner_sha256': sha(__file__), 'script_sha256': hashlib.sha256(SCRIPT.encode()).hexdigest()})
before = {'counts': auto.scopes(), 'flags': auto.status()}
require(auto.flags_disabled(before['flags']), 'closed fault flags before native units')
save(folder / 'server-before.json', before)
for kind in COUNTS:
previous.upload(manifest['artifacts'][kind])
save(folder / 'started-local.json', {'start_once': True})
action = 'run'
else:
require(str(uuid.UUID(ident)) == ident, 'canonical original native case')
folder = NATIVE / ident;intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['manifest_sha256'] == sha(path) and intent['manifest_path'] == str(path)
and intent['runner_sha256'] == sha(__file__)
and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same original case; readback only')
action = 'read'
result = cb.powershell(SCRIPT, {'id': ident, 'action': action, 'manifest_sha256': sha(path),
'artifacts': {k: manifest['artifacts'][k] for k in COUNTS},
'counts': COUNTS, 'test_names': TESTS}, timeout=150)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
if result.get('completed') is not True:
print(json.dumps({'verified': False, 'case_id': ident, 'readback_only': True, 'completed': False,
'case_exists': result.get('case_exists'), 'tests_repeated': False}))
return
require(result['manifest_sha256'] == sha(path) and set(result['reports']) == set(COUNTS)
and result['both_lists_verified_before_any_test'] is True
and result['rmm_jobs'] is False and result['product_state_writes'] is False
and result['local_service_proof'] is False and result['native_pipe_proof'] is False,
'actual narrow unit result, no runtime proof')
for kind, actual in result['reports'].items():
run, listed = actual['result'], actual['listed']
names = re.findall(r'^(.+): test\r?$', listed['stdout'], re.M)
require(actual['sha256'] == manifest['artifacts'][kind]['sha256']
and names == actual['names'] == TESTS[kind] and len(set(names)) == COUNTS[kind]
and listed['exit_code'] == run['exit_code'] == 0 and not listed['timed_out'] and not run['timed_out']
and re.search(r'test result: ok\. ' + str(COUNTS[kind])
+ r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', run['stdout']),
'every exact named native unit passed, none skipped/filtered')
before = cb.contract.protected_json(folder / 'server-before.json')
require(auto.scopes() == before['counts'] and auto.status() == before['flags'], 'both central counts and closed flags unchanged')
if action == 'run':
verified(path) # Full before/after source and retained-artifact check.
proof = {'verified': True, 'case_id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
'native': result, 'no_jobs': True, 'clock_adapter_qualified': False,
'local_service_proof': False, 'native_pipe_proof': False}
destination = folder / 'passed.json'
if destination.exists():
require(cb.contract.protected_json(destination) == proof, 'retain exact original proof')
else:
save(destination, proof)
print(json.dumps({'verified': True, 'case_id': ident, 'tests': COUNTS, 'proof': str(destination)}))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('build-local', 'native-units', 'readback'))
parser.add_argument('--access-root', required=True, type=Path)
parser.add_argument('--manifest', type=Path)
parser.add_argument('--case')
args = parser.parse_args()
require(args.access_root == ACCESS and not args.access_root.is_symlink(), 'exact existing access root')
if args.phase == 'build-local':
require(args.manifest is None and args.case is None, 'build only')
build()
else:
require(args.manifest is not None and ((args.phase == 'readback') == bool(args.case)), 'explicit manifest and original readback case')
native(args.manifest, args.case)
if __name__ == '__main__':
try:
main()
except Exception as error:
print('WINDOWS_PIPE_V2_QUALIFICATION_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None
+564
View File
@@ -0,0 +1,564 @@
#!/usr/bin/env python3
"""One preserving passive pipe-v2 pair upgrade; no target actions by default.
prepare stages immutable bootstrap artifacts and captures a read-only baseline.
enter needs that exact separately reviewed baseline hash and runs once. A lost
reply permits readback/finish only. Main access-root is read-only, including the
current indices: Root publishes those separately after reviewing this result.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid
import client_bootstrap as cb
import system_delegation_upgrade as u
require = cb.contract.require
ROOT = cb.ROOT
STATE = cb.EVIDENCE / 'system-pipe-upgrade'
ORIGINAL_RUNNER = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
OLD_AGENT = '89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676'
OLD_HELPER = 'e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662'
OLD_POLICY = '007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703'
OLD_PIN = '126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15'
OLD_CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
OLD_RESULT_SHA = 'ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460'
PIPE_VERIFIER_SHA = '2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf'
sha, raw_sha, canonical, save = u.sha, u.raw_sha, u.canonical, u.save
def replace_once(text, old, new):
require(text.count(old) == 1, 'exact reviewed bootstrap splice')
return text.replace(old, new, 1)
def write_bytes(path, data):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(data); output.flush(); os.fsync(output.fileno())
# Reuse read-only witnesses only, bound to the historical runner hash below.
# None of its original hard-PID stop, File.Replace(NULL), start, or case logic
# is included. Every new mutation is visible in this file.
PREFIX = u.SCRIPT.split('\nfunction ReadIntent', 1)[0]
PREFIX = replace_once(PREFIX, 'RmmDelegationUpgradePayload', 'RmmPipeUpgradePayload')
PREFIX = replace_once(PREFIX, "@('state','enter','finish','readback')", "@('baseline','enter','finish','readback')")
PREFIX = replace_once(PREFIX, "('system-delegation-'+$p.id)", "('system-pipe-'+$p.id)")
PREFIX = replace_once(PREFIX, "'system-delegation-active-intent.json'", "'system-pipe-active-intent.json'")
for old, new in ((u.OLD_AGENT, OLD_AGENT), (u.OLD_HELPER, OLD_HELPER), (u.OLD_POLICY, OLD_POLICY), (u.OLD_PIN, OLD_PIN)):
PREFIX = replace_once(PREFIX, old, new)
NATIVE = r'''
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32.SafeHandles;
public static class RmmPipeNative {
public sealed class Held : SafeHandleZeroOrMinusOneIsInvalid {
public Held(IntPtr h):base(true){SetHandle(h);}
protected override bool ReleaseHandle(){return CloseHandle(handle);}
}
[StructLayout(LayoutKind.Sequential)] public struct FileId {
public ulong Volume;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=16)] public byte[] Id;
}
[StructLayout(LayoutKind.Sequential)] struct SidAndAttributes {public IntPtr Sid;public uint Attributes;}
[StructLayout(LayoutKind.Sequential)] struct Groups {public uint Count;public SidAndAttributes First;}
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool CloseHandle(IntPtr h);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(Held h,out long creation,out long exit,out long kernel,out long user);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(Held h,uint flags,StringBuilder image,ref uint size);
[DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(Held h,uint millis);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(Held process,uint access,out IntPtr token);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,int bytes,out int needed);
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int kind,out FileId id,uint size);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] public static extern SafeFileHandle CreateFile(string path,uint access,uint share,IntPtr security,uint creation,uint flags,IntPtr template);
public static Held Open(int pid){IntPtr h=OpenProcess(0x101000,false,pid);if(h==IntPtr.Zero)throw new Win32Exception();return new Held(h);}
public static bool Alive(Held h){return WaitForSingleObject(h,0)==258;}
public static bool Exited(Held h,uint timeout){return WaitForSingleObject(h,timeout)==0;}
static IntPtr Info(IntPtr token,int kind,out int bytes){
int needed;GetTokenInformation(token,kind,IntPtr.Zero,0,out needed);
if(needed<=0||needed>65536)throw new InvalidOperationException("Token size");
IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p;
}
public static Dictionary<string,object> Proof(Held h,int pid,string owner,string serviceSid,string image){
if(!Alive(h))throw new InvalidOperationException("Process not alive");
long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception();
StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image");
IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception();
try {
int bytes;IntPtr info=Info(token,1,out bytes);string actual;
try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);}
if(actual!=owner)throw new InvalidOperationException("Process owner");
info=Info(token,2,out bytes);bool found=false;
try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes));
if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size");
for(int n=0;n<count;n++){SidAndAttributes g=(SidAndAttributes)Marshal.PtrToStructure(IntPtr.Add(info,offset+n*stride),typeof(SidAndAttributes));if(new SecurityIdentifier(g.Sid).Value==serviceSid&&(g.Attributes&4)!=0&&(g.Attributes&16)==0)found=true;}
}finally{Marshal.FreeHGlobal(info);}
if(!found||!Alive(h))throw new InvalidOperationException("Enabled service SID/process liveness");
return new Dictionary<string,object>{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}};
}finally{CloseHandle(token);}
}
}
'@
function FileIdentity($path,[bool]$actor=$false){
Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'}
return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)}
}finally{$file.Dispose()}
}
function Kernel($role,$record,$held){
$owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary}
$proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image)
if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof
}
function ActualState([bool]$new){
$value=State $new
$value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))}
foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service}
$proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}}
$value[$role+'_kernel']=$proof
};return $value
}
# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds
# the private key's actual native FileID, not merely a timestamp/name.
function FileIdentityMetadata($path){
Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()}
}
function SameOriginal($before,$after){
Preserved $before $after $false
if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'}
foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}}
}
function PreserveImmutableFiles($before,$after,[bool]$frozen){
Preserved $before $after $frozen
foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}}
}
'''
# The original fixed-role SCM configuration checks are reused exactly. Unlike
# Service(), this readback projection makes no running-process proof claim and
# honestly exposes pending/raw State/PID without changing a service.
READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r'''
$state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'}
return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true}
}
'''
PHASES = r'''
CheckControl $boot $true
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'}
if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0}
function ReadCase{
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false
$i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json
if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'}
foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}}
if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i
}
if($p.action-ceq'readback'){
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
$i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))}
@{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if($p.action-ceq'finish'){
$i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false
CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false
foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}}
@{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}
$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json
$before=ActualState $false;SameOriginal $baseline $before
if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'}
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null
try{
$null=Kernel 'agent' $before.service $heldAgent
if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper}
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true}
function StopHeld($role,$record,$held){
$live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held
$name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record}
Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'}
WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true}
}
StopHeld 'agent' $before.service $heldAgent
if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}}
$frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen
function Backup($label,$path,$expected){
$identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'}
$backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup
if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl}
}
Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
$settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'}
WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
function Swap($label,$destination,$source,$oldHash,$newHash){
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'}
foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}}
$old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate')
if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'}
[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'}
WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256}
if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'}
[IO.File]::Replace($candidate,$destination,$nativeBackup)
PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'}
WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))}
}
Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
$swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped
function StartOnce($role){
$checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName}
WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true}
Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
$s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()}
}
StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
@{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}}
'''
SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1')
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload')
class Access:
"""Explicit read-only access roots; never redirects source/manifest globals."""
def __init__(self, root):
self.root = Path(root).absolute()
require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy')
self.evidence = self.root / 'devstate/windows-client'
def powershell(self, source, payload, timeout=180):
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
wrapped = "try {\n" + source + "\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 -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode()
result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout)
if result.returncode:
# Fixed error identifiers/line only; never raw stderr/payload/commands.
safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr))
try:
error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
if error.get('bootstrap_error') is True:
safe.update(error_id=error.get('error_id'), line=error.get('line'))
except (ValueError, AttributeError):
pass
save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe)
raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only')
return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
def stage(self, path, name):
require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names')
path = Path(path)
digest = sha(path)
prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
observed = self.powershell(prepare, dict(sha256=digest))
if not observed['already_uploaded']:
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
prefix = access['ssh_prefix']
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry')
observed = self.powershell(prepare, dict(sha256=digest))
require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage')
def server(self, function, payload):
cloud = u.transport.cloud
require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses')
# The inherited parser is strict data parsing, not source/eval. Its ROOT
# only checks the source .gitignore; its supplied path remains Main.
cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf')
ssh = ['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 = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n')
result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require('error' not in value, 'readonly server witness incomplete')
return value
def server_state(self):
cloud = u.transport.cloud
linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json')
require(linux['verified'] is True, 'accepted Linux target only')
counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in (
('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))}
flags = self.server(u.auto.server_state, {})
require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate')
return dict(counts=counts, flags=flags)
def observe(self, ident):
return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident))
def device_and_denials(self):
bridge = self
class ReadBackend(u.transport.cloud.Backend):
def request(self, body):
if body['method'] == 'tools/call':
require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads')
else:
require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session')
return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal))
device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET))
require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory')
denied = []
backend = ReadBackend('b')
for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'):
backend.sequence += 1
response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET))))
data = response.get('data', {})
require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied')
denied.append(dict(tenant_id=tenant, denied=True))
return device, denied
def dependencies():
modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper]
return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules}
def guards():
require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source')
require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded')
require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup')
ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts')
require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives')
require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback')
# Fresh isolated interpreter: the Pipe pack deliberately imports its transport
# modules from Main. Reusing its module in this interpreter would accidentally
# reuse our cached worktree client_bootstrap and corrupt the source/access split.
# This code calls verification/read-only proof parsing ONLY, never native().
VERIFY_PACK = r'''
import hashlib,importlib.util,json,re,sys,uuid
from pathlib import Path
path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path)
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve()
manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs
proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require
case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace')
require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability')
intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json')
require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest')
require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent')
before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json')
require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope')
actual=proof['native']
require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only')
for kind,count in pack.COUNTS.items():
report=actual['reports'][kind];listed=report['listed'];run=report['result']
names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M)
require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout')
print(json.dumps(manifest))
'''
def qualified(manifest_path, proof_path):
verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py'
require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier')
result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling')
return value
def prior(access):
runtime_path = access.evidence / 'current-runtime.json'
components_path = access.evidence / 'current-components.json'
runtime = cb.contract.protected_json(runtime_path)
components = cb.contract.protected_json(components_path)
result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json')
require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result')
result = cb.contract.protected_json(result_path)
require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation')
evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA)
require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback')
recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json'
require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved')
original = cb.contract.protected_json(result_path.parent / 'intent.json')
settings = base64.b64decode(original['payload']['settings_base64'], validate=True)
require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings')
return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
def passive_settings(old, agent, helper):
require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings')
require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes')
new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper
settings = canonical(new); policy = raw_sha(settings)
pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper']))
return settings, pin, policy
def leaves(access):
path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation')
proof = cb.contract.protected_json(path)
require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification')
created_path = path.parent / 'created.json'
require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt')
created = cb.contract.protected_json(created_path)
items = {v['name']: v for v in created['leaves']}
require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves')
return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
def remote(access, intent, action):
require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source')
return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)))
def load(ident, access):
require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID')
folder = STATE / ident
intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case')
manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair')
return folder, intent
def prepare(access, manifest_path, proof_path):
guards()
manifest = qualified(manifest_path, proof_path)
indices, accepted, old = prior(access)
settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
script_sha = raw_sha(SCRIPT.encode())
payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access))
draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True)
save(folder / 'prepare-intent.json', draft)
for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]:
write_bytes(folder / name, data)
for kind in ('agent', 'helper', 'probe', 'system_probe'):
item = manifest['artifacts'][kind]
require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes')
access.stage(item['path'], item['name'])
access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1')
before = remote(access, draft, 'baseline')
expected = accepted['native']
for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'):
require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read')
for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'):
require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity')
for field in ('helper_ledger', 'executor_lock', 'intent_store'):
require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves')
for role in ('service', 'helper_service'):
for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'):
require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL')
baseline = canonical(before)
write_bytes(folder / 'baseline.json', baseline)
payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline))
draft['payload'] = payload
save(folder / 'intent.json', draft)
save(folder / 'server-before.json', access.server_state())
central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device')
save(folder / 'central-before.json', central)
print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True)))
def enter(access, ident, baseline_sha):
folder, intent = load(ident, access)
require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required')
indices, _, _ = prior(access)
require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged')
save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True))
result = remote(access, intent, 'enter')
require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply')
save(folder / 'entered.json', result)
print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter')))
def finish(access, ident, read_only=False):
folder, intent = load(ident, access)
action = 'readback' if read_only else 'finish'
observed = remote(access, intent, action)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback')
if read_only:
print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
require(observed['completed'] is True, 'actual complete pair preservation')
result_path = folder / 'result.json'
if result_path.exists():
previous = cb.contract.protected_json(result_path)
require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation')
print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return
# Two genuinely new server heartbeats after both single starts, not cached
# contacts from baseline, and no new network-agent jobs/capabilities.
after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json')
watermark = access.observe(ident)['device']
require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark')
deadline = time.monotonic() + 150; first = None
while True:
evidence = access.observe(ident); device = evidence['device']
if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']):
require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity')
if first is None: first = evidence
elif device['last_contact_at'] != first['device']['last_contact_at']: break
require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing')
time.sleep(2)
final = remote(access, intent, 'finish'); native = final['native']
original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object)
require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK')
device, denied = access.device_and_denials()
require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory')
require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged')
indices, _, _ = prior(access)
require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication')
pipe = u.actual_pipe_proof(native, intent)
result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256'])
save(result_path, result)
print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards'))
parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256')
args = parser.parse_args(); guards()
if args.phase == 'guards':
require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return
require(args.access_root, 'explicit separate read-only Main access root')
access = Access(args.access_root)
if args.phase == 'prepare':
require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation')
prepare(access, args.manifest, args.qualification)
elif args.phase == 'enter':
require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash')
enter(access, args.id, args.baseline_sha256)
else:
require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish')
finish(access, args.id, args.phase == 'readback')
if __name__ == '__main__':
try: main()
except Exception as error:
print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None
@@ -0,0 +1,70 @@
"""Four local orchestration guards; no credentials/VM/Windows API calls."""
import contextlib
import copy
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
import system_pipe_upgrade as p
def settings():
return dict(schema_version=1, binding={'public_fixture': True}, agent=dict(binary_sha256=p.OLD_AGENT), helper=dict(binary_sha256=p.OLD_HELPER), allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False)
class PipeUpgradeGuards(unittest.TestCase):
def test_closed_reciprocal_settings_only_change_two_image_pins(self):
original = settings(); preserved = copy.deepcopy(original)
raw, pin, policy = p.passive_settings(original, 'a' * 64, 'b' * 64)
changed = json.loads(raw); changed['agent']['binary_sha256'] = p.OLD_AGENT; changed['helper']['binary_sha256'] = p.OLD_HELPER
self.assertEqual(changed, preserved); self.assertEqual(original, preserved)
self.assertEqual(p.raw_sha(raw), policy); self.assertEqual(json.loads(pin)['policy_sha256'], policy)
for field, value in [('enable_effects', True), ('allow_reboot', True), ('allowed_services', ['foreign']), ('max_runtime_seconds', 120), ('schema_version', True)]:
bad = settings(); bad[field] = value
with self.subTest(field=field), self.assertRaises(RuntimeError): p.passive_settings(bad, 'a' * 64, 'b' * 64)
def test_historical_mutation_helpers_excluded_and_explicit_backups_ordered(self):
p.guards()
self.assertNotIn('function PinProcess', p.PREFIX)
self.assertNotIn('[IO.File]::Replace($candidate,$destination,$null)', p.SCRIPT)
self.assertIn('[RmmPipeNative]::Open([int]$before.service.pid)', p.SCRIPT)
self.assertNotIn('$expected=5140', p.SCRIPT)
self.assertIn("'helper-already-stopped.json'", p.SCRIPT)
self.assertIn('stop_called=$false;start_called=$false', p.SCRIPT)
self.assertIn("@('config','ca','identity','certificate','private_key')", p.SCRIPT)
self.assertEqual(p.SCRIPT.count('PreserveImmutableFiles '), 5)
readback = p.PHASES.split("if($p.action-ceq'readback'){", 1)[1].split("if($p.action-ceq'finish'){", 1)[0]
self.assertIn("(ReadbackService 'agent')", readback)
self.assertNotIn('(Service ', readback)
self.assertIn('process_identity_verified=$false', p.READBACK_SERVICE)
self.assertIn('pack.verified(manifest_path)', p.VERIFY_PACK)
self.assertIn("names==report['names']==pack.TESTS[kind]", p.VERIFY_PACK)
with patch.object(p.subprocess, 'run', return_value=Mock(returncode=0, stdout=b'{"type":"rmm.windows.system-delegation-build"}')):
with self.assertRaises(RuntimeError): p.qualified(Path('unused-fixture'), Path('unused-proof'))
def test_lost_enter_reply_cannot_repeat_target_mutation(self):
with tempfile.TemporaryDirectory() as temporary:
folder = Path(temporary); p.write_bytes(folder / 'baseline.json', b'{}')
digest = p.sha(folder / 'baseline.json'); indices = {'unit_fixture': True}
intent = dict(payload=dict(baseline_sha256=digest), original_indices=indices)
p.save(folder / 'server-before.json', {'unit_counts': 0})
access = Mock(); access.server_state.return_value = {'unit_counts': 0}
with patch.object(p, 'load', return_value=(folder, intent)), patch.object(p, 'prior', return_value=(indices, {}, {})), patch.object(p, 'remote', side_effect=TimeoutError('unit fixture lost reply')) as remote:
with self.assertRaises(TimeoutError): p.enter(access, 'fixture', digest)
self.assertTrue((folder / 'enter-attempt.json').exists())
with self.assertRaises(FileExistsError): p.enter(access, 'fixture', digest)
self.assertEqual(remote.call_count, 1)
def test_readback_never_queries_server_starts_or_publishes_main_indices(self):
with tempfile.TemporaryDirectory() as temporary:
access = Mock(); access.server_state.side_effect = AssertionError('server unavailable in readback')
with patch.object(p, 'load', return_value=(Path(temporary), {})), patch.object(p, 'remote', return_value=dict(read_only=True, id='fixture', phase_receipts={})) as remote, contextlib.redirect_stdout(io.StringIO()):
p.finish(access, 'fixture', read_only=True)
remote.assert_called_once_with(access, {}, 'readback')
self.assertFalse(access.server_state.called)
if __name__ == '__main__': unittest.main()
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Start the existing W32Time once after review; lost replies use readback only.
This bootstrap never changes service configuration, NTP, policy, ACLs or RMM
components. A running W32Time is not evidence of a qualified/trusted clock.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import uuid
import client_bootstrap as cb
import system_helper_bootstrap as helper
import transport_acceptance as source_stage
STATE = cb.EVIDENCE / 'time-service-start'
CONTEXT = cb.EVIDENCE / 'time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973/before.json'
require = cb.contract.require
SCRIPT = r'''$ErrorActionPreference='Stop'
$p=$global:RmmTimeServiceStartPayload
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','start','readback')){throw 'Fixed time-service case'}
foreach($name in @('agent_sha256','helper_sha256','config_sha256','policy_sha256','pin_sha256')){if($p.$name-notmatch'^[a-f0-9]{64}$'){throw 'Exact retained component pins'}}
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-service-'+$p.id);$active=Join-Path $boot 'w32time-start-once.json'
function HashBytes([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function JsonHash($value){return HashBytes ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress)))}
function CheckControl($path,[bool]$directory){
$item=Get-Item -LiteralPath $path -Force
if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed private bootstrap path'}
$acl=Get-Acl -LiteralPath $path
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$acl.Access.Count){throw 'Bootstrap owner/DACL'}
foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Bootstrap controller only'}}
}
function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));$file=[IO.File]::Open($path,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()};CheckControl $path $false}
function FileMeta($path,[bool]$hash){
$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original component'}
$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original ancestor reparse'};$parent=$parent.Parent}
$acl=Get-Acl -LiteralPath $path
return [ordered]@{length=$item.Length;created_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();written_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();owner_sid=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;acl_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($acl.Sddl)));sha256=if($hash){(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}else{$null}}
}
function ServiceState($name){
$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10
if(!$service){throw 'Existing fixed service required'}
$security=& "$env:WINDIR\System32\sc.exe" sdshow $name;if($LASTEXITCODE-ne0){throw 'Read service security'}
$sidtype=& "$env:WINDIR\System32\sc.exe" qsidtype $name;if($LASTEXITCODE-ne0){throw 'Read service SID type'}
$definition=[ordered]@{account=$service.StartName;start_mode=$service.StartMode;image_path=$service.PathName;service_type=$service.ServiceType;security_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($security-join "`n").Trim())));sid_type_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($sidtype-join "`n").Trim())))}
return [ordered]@{name=$name;state=$service.State;pid=$service.ProcessId;definition=$definition}
}
function TimeConfigHash{
# Selected stable configuration only. Normal synchronization may update other
# runtime registry state; neither values nor NTP hostnames leave this function.
$specs=@(
@('SYSTEM\CurrentControlSet\Services\W32Time',@('Start','DelayedAutoStart','ImagePath','ObjectName','Type')),
@('SYSTEM\CurrentControlSet\Services\W32Time\Parameters',@('Type','NtpServer','ServiceDll','ServiceMain')),
@('SYSTEM\CurrentControlSet\Services\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval','FrequencyCorrectRate','PhaseCorrectRate','LocalClockDispersion')),
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
@('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')),
@('SOFTWARE\Policies\Microsoft\W32Time\Parameters',@('Type','NtpServer')),
@('SOFTWARE\Policies\Microsoft\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval')),
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')),
@('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')))
$entries=@();foreach($spec in $specs){$path='Registry::HKEY_LOCAL_MACHINE\'+$spec[0];$exists=Test-Path -LiteralPath $path;$values=@()
if($exists){$key=Get-Item -LiteralPath $path;try{foreach($name in $spec[1]){if($key.GetValueNames()-ccontains$name){$values+=,[ordered]@{name=$name;kind=$key.GetValueKind($name).ToString();value=$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}}}}finally{$key.Close()}}
$entries+=,[ordered]@{path=$spec[0];exists=$exists;values=$values}
};return JsonHash $entries
}
function Snapshot{
$rmm=@();foreach($pair in @(@('RmmDiscoveryWindows','C:\Program Files\RustDiscovery\rmm-agent-windows.exe',$p.agent_sha256),@('RmmDiscoverySystemHelper','C:\Program Files\RustDiscovery\rmm-helper-windows.exe',$p.helper_sha256))){
$service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'}
$proc=[Diagnostics.Process]::GetProcessById([int]$service.pid);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();$image=$proc.MainModule.FileName}finally{$proc.Dispose()}
if(![string]::Equals($image,$pair[1],[StringComparison]::OrdinalIgnoreCase)){throw 'Actual retained RMM image'}
$binary=FileMeta $pair[1] $true;if($binary.sha256-cne$pair[2]){throw 'Independently pinned RMM binary'}
$rmm+=,[ordered]@{service=$service;process_birth_filetime=$birth;binary=$binary}
}
$files=[ordered]@{};foreach($pair in @(@('config','C:\ProgramData\RustDiscovery\config.json',$p.config_sha256),@('helper_settings','C:\ProgramData\RustDiscoverySystem\helper.json',$p.policy_sha256),@('agent_pin','C:\ProgramData\RustDiscoverySystem\agent-pin.json',$p.pin_sha256))){$value=FileMeta $pair[1] $true;if($value.sha256-cne$pair[2]){throw 'Retained original config/pins'};$files[$pair[0]]=$value}
foreach($pair in @(@('ca','C:\ProgramData\RustDiscovery\server-ca.pem'),@('identity','C:\ProgramData\RustDiscovery\state\identity.json'),@('certificate','C:\ProgramData\RustDiscovery\state\device.pem'))){$files[$pair[0]]=FileMeta $pair[1] $true}
$files['private_key_metadata_only']=FileMeta 'C:\ProgramData\RustDiscovery\state\device.key' $false
$cfg=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\config.json' -Raw|ConvertFrom-Json
if(($cfg.PSObject.Properties.Name-ccontains'enable_jobs')-and$cfg.enable_jobs-ne$false){throw 'No RMM jobs enabled'}
if(($cfg.PSObject.Properties.Name-ccontains'job_binding_file')-and$null-ne$cfg.job_binding_file){throw 'No new job binding'}
$policy=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\helper.json' -Raw|ConvertFrom-Json
if($policy.enable_effects-ne$false-or$policy.allow_reboot-ne$false-or@($policy.allowed_services).Count-ne0){throw 'Closed original helper policy'}
return [ordered]@{rmm=$rmm;original_files=$files;time_service=(ServiceState 'W32Time');selected_time_config_sha256=(TimeConfigHash);time_config_coverage='fixed_service_NTP_and_policy_configuration_values_only'}
}
function BaselineHash($snapshot){return JsonHash ([ordered]@{rmm=$snapshot.rmm;original_files=$snapshot.original_files;time_definition=$snapshot.time_service.definition;selected_time_config_sha256=$snapshot.selected_time_config_sha256})}
function Preserved($before,$after){
if((JsonHash $before.rmm)-cne(JsonHash $after.rmm)-or(JsonHash $before.original_files)-cne(JsonHash $after.original_files)){throw 'RMM components or original config/PKI metadata changed'}
if((JsonHash $before.time_service.definition)-cne(JsonHash $after.time_service.definition)-or$before.selected_time_config_sha256-cne$after.selected_time_config_sha256){throw 'Service configuration/security or selected NTP/policy values changed'}
}
CheckControl $boot $true
if($p.action-ceq'state'){$snapshot=Snapshot;@{id=$p.id;snapshot=$snapshot;baseline_sha256=(BaselineHash $snapshot);read_only=$true;no_jobs=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
if($p.expected_sha256-notmatch'^[a-f0-9]{64}$'-or$p.baseline_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Retained reviewed case hashes'}
if($p.action-ceq'readback'){
if(!(Test-Path -LiteralPath $folder)){@{id=$p.id;entered=$false;readback_only=$true;start_repeated=$false;current=(Snapshot);clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return}
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false
$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json
if($intent.id-cne$p.id-or$intent.expected_sha256-cne$p.expected_sha256){throw 'Exact retained time-service intent'}
$after=Snapshot;Preserved $intent.before $after
$receipt=Join-Path $folder 'result.json';$result=$null;if(Test-Path -LiteralPath $receipt){CheckControl $receipt $false;$result=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json}
@{id=$p.id;entered=$true;readback_only=$true;start_repeated=$false;original_result=$result;start_intent_exists=(Test-Path -LiteralPath (Join-Path $folder 'start-intent.json'));current=$after;preserved=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return
}
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing start case: readback only, never repeat start'}
$before=Snapshot
if((BaselineHash $before)-cne$p.baseline_sha256){throw 'Exact reviewed baseline changed; do not rebase'}
if($before.time_service.state-notin@('Stopped','Running')){throw 'Pending or unknown time-service state: no start'}
if($before.time_service.state-ceq'Stopped'){$controller=Get-Service -Name W32Time;try{if(@($controller.ServicesDependedOn).Count-ne0-or$controller.Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'No implicit dependency starts or changed service state'}}finally{$controller.Dispose()}}
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
WriteNew (Join-Path $folder 'intent.json') @{id=$p.id;expected_sha256=$p.expected_sha256;before=$before;create_only=$true;clock_trust_assessed=$false}
if($before.time_service.state-ceq'Running'){
$after=Snapshot;Preserved $before $after
$result=@{id=$p.id;status='already_running';start_called=$false;already_running_read_only=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true}
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Compress;return
}
# Durable local and global admission precede the one exact SCM start. Nothing
# catches/retries the start; an incomplete receipt can only be read back.
WriteNew $active @{id=$p.id;expected_sha256=$p.expected_sha256;service='W32Time';create_only=$true}
WriteNew (Join-Path $folder 'start-intent.json') @{id=$p.id;service='W32Time';start_reserved=$true;observed_at=[DateTime]::UtcNow.ToString('o')}
Start-Service -Name W32Time
$service=Get-Service -Name W32Time
$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
$after=Snapshot;Preserved $before $after
if($after.time_service.state-cne'Running'){throw 'No running-state confirmation'}
$result=@{id=$p.id;status='started';start_called=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true;after=$after}
WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 24 -Compress
'''
PREPARE = source_stage.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1')
LAUNCH = source_stage.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1').replace('RmmTransportPayload', 'RmmTimeServiceStartPayload')
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(folder, name, value):
return helper.store(folder, name, value)
def preserve_failure(folder):
path = cb.EVIDENCE / 'bootstrap-private-last-error.json'
if not path.exists():
return
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as source:
info = os.fstat(source.fileno())
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 4 * 1024 * 1024, 'private original bootstrap failure')
raw = source.read()
target = folder / ('retained-bootstrap-error-' + hashlib.sha256(raw).hexdigest() + '.json')
if not target.exists():
fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(raw); output.flush(); os.fsync(output.fileno())
def remote(folder, payload):
preserve_failure(folder)
try:
return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), 'payload': payload}, timeout=100, remote_signed=True)
finally:
preserve_failure(folder)
def prepare(pins):
require(all(re.fullmatch('[0-9a-f]{64}', value) for value in pins.values()), 'independently known retained hashes')
helper.private_dir(STATE); ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest()
payload = dict(id=ident, **pins)
save(folder, 'intent.json', {'schema_version': 1, 'type': 'rmm.windows.time-service-start', 'payload': payload, 'source_file_sha256': digest(__file__), 'script_sha256': source_sha, 'closed_central_before': {'path': str(CONTEXT), 'sha256': digest(CONTEXT)}})
source = folder / 'TimeServiceStart.ps1'
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno())
preserve_failure(folder)
try:
helper.transfer(source, 'TimeServiceStart.ps1', source_sha, PREPARE)
before = remote(folder, dict(payload, action='state'))
finally:
preserve_failure(folder)
require(before.get('read_only') is True and before.get('clock_trust_assessed') is False, 'actual readonly baseline')
save(folder, 'before.json', before)
print(json.dumps({'case_id': ident, 'prepared': True, 'time_state': before['snapshot']['time_service']['state'], 'clock_trust_assessed': False, 'start_executed': False}))
def run(ident, action):
require(str(uuid.UUID(ident)) == ident, 'exact existing case UUID')
folder = STATE / ident; intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['source_file_sha256'] == digest(__file__) and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same reviewed source; no case rebase')
baseline = cb.contract.protected_json(folder / 'before.json')['snapshot']
# Powershell creates its canonical baseline hash during state. It is sent
# back verbatim rather than approximating ConvertTo-Json in Python.
payload = dict(intent['payload'], action=action, baseline_sha256=cb.contract.protected_json(folder / 'before.json')['baseline_sha256'], expected_sha256=hashlib.sha256(json.dumps(intent['payload'], sort_keys=True, separators=(',', ':')).encode()).hexdigest())
require(baseline is not None and digest(CONTEXT) == intent['closed_central_before']['sha256'], 'retained actual baseline and closed central context')
if action == 'start':
save(folder, 'start-attempt.json', {'case_id': ident, 'once': True, 'lost_reply_readback_only': True})
result = remote(folder, payload)
save(folder, ('result.json' if action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json'), result)
original = result.get('original_result') or result
current = result.get('current') or result.get('after')
print(json.dumps({'case_id': ident, 'status': original.get('status', 'unconfirmed'), 'running': current['time_service']['state'] == 'Running' if current else original.get('status') == 'already_running', 'preserved': result.get('preserved', False), 'readback_only': result.get('readback_only', False), 'clock_trust_assessed': False}))
def main():
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('action', choices=['prepare', 'start', 'readback']); parser.add_argument('--id')
for name in ['agent', 'helper', 'config', 'policy', 'pin']:
parser.add_argument('--' + name + '-sha256')
args = parser.parse_args()
if args.action == 'prepare':
pins = {name + '_sha256': getattr(args, name + '_sha256') for name in ['agent', 'helper', 'config', 'policy', 'pin']}
require(all(isinstance(value, str) for value in pins.values()), 'all five independent hashes required'); prepare(pins)
else:
require(args.id is not None, 'explicit retained case required'); run(args.id, args.action)
if __name__ == '__main__':
main()
-503
View File
@@ -1,503 +0,0 @@
#!/usr/bin/env python3
"""M3 Event Log pure contracts: Linux VM FIRST, then Windows VM.
Only two fixed test executables run in separate bootstrap scratch directories.
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
Native execution is explicit; any lost reply permits same-case readback only.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import stat
import subprocess
import uuid
import vm_access_check as access
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/windows-eventlog-contracts'
IMAGE = 'rust-discovery-durable-final-build:local'
PROFILE = 'windows-eventlog-contracts-v1'
LINUX_REMOTE = '/var/lib/rmm-windows-eventlog-contracts'
KINDS = ('domain', 'contracts')
REVIEWED_M3 = {'crates/agent-core/src/auth.rs': '360e6af153d7d5b31717e0f8fbc0e988850c7fa032eaa3a657962187f5a657e4',
'crates/agent-core/tests/contracts.rs': '2482928f45e3236ae079329668849f5ccd2e01503e56cd3b8e37579af3f21e9c',
'crates/agent-windows/Cargo.toml': '886f0ee1bc8b02133325bc1f1c4db76db3f0194435fba151eb1f3ca42e0660dc',
'crates/agent-windows/src/actions.rs': 'a13e3746ee05619b993b6828e9c7b103fa5d3f9d47f1b52de595da3c57910180',
'crates/agent-windows/src/event_log.rs': '00756bc178c5e67eca0de64fe55f6a1b3865e27d33f3e1c87fa575b5be81706d',
'crates/agent-windows/src/event_log_job.rs': '08798cf194c405e93cd5874517857a06649aa47a0cc8c933fbd924018670113e',
'crates/agent-windows/src/job_binding.rs': '488bab9f74b84023cf5b8f35f6f624903d98a82e886ef78d7ab93c8d99281e26',
'crates/agent-windows/src/lib.rs': '391764708bfd6a8ab5546ef299d40f54dc4eefa02d4334dead7a16e46a22cd66',
'crates/agent-windows/src/runtime.rs': '21c09cbc2a0b4caf5a4e273a20eac63dc870bb942a3683fb5b7ba6f7b36b4674',
'crates/domain/src/jobs.rs': 'b9950270fc77086d06b3f7aa177aba2ad13155c10653b3ee73a2be436365cf1f',
'crates/server/src/job_gateway.rs': '234542f4783c95cfcfd567495bfb7233f2c05a1b88dd87fb85a916d32eae5fc5',
'crates/server/src/jobs.rs': '5bff6fe61fce601cd03721cebd82bca05b5af83d3640bf862ba6d603ceb7e3e9'}
COUNTS = {'linux': {'domain': 17, 'contracts': 7}, 'windows': {'domain': 17, 'contracts': 6}}
DOMAIN_NAMES = sorted(('apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
'inventory_document::tests::additive_metadata_and_bounds',
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes', 'jobs::tests::codec_golden_and_exact_script_bytes',
'jobs::tests::no_terminal_replay_or_unknown_restart', 'jobs::tests::permit_codec_golden_all_bindings',
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
'jobs::tests::windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes',
'jobs::tests::windows_interpreter_and_capability_contract',
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
'tests::production_never_accepts_development_auth'))
CONTRACT_NAMES = sorted(('atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
'portable_acceptance_requires_platform_capability_and_exact_redelivery'))
UNIX_ONLY = 'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering'
EXPECTED = {'linux': {'domain': DOMAIN_NAMES, 'contracts': CONTRACT_NAMES},
'windows': {'domain': DOMAIN_NAMES, 'contracts': [x for x in CONTRACT_NAMES if x != UNIX_ONLY]}}
def require(value, code):
if not value:
raise RuntimeError(code)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def object_pairs(items):
value = {}
for key, item in items:
require(key not in value, 'duplicate JSON field')
value[key] = item
return value
def private(path, directory=False):
item = Path(path).lstat()
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
'private owned regular path')
def load(path):
private(path)
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
def save(path, value):
private(Path(path).parent, True)
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
def setup_state():
os.umask(0o077)
STATE.parent.mkdir(mode=0o700, exist_ok=True)
metadata = STATE.parent.lstat()
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
'owned non-world-writable devstate parent')
STATE.mkdir(mode=0o700, exist_ok=True)
private(STATE, True)
def source_files():
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
'deploy/windows_eventlog_acceptance.py', 'deploy/remote_client_bootstrap.py',
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/windows/client_bootstrap.py')]
paths += list((ROOT / 'crates').rglob('Cargo.toml'))
for name in ('domain', 'agent-core', 'protocol', 'server', 'agent-windows'):
paths += [p for p in (ROOT / 'crates' / name).rglob('*') if p.is_file()]
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
for path in paths:
require(not path.is_symlink() and path.is_file(), 'regular source inputs only')
value = {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
require(all(value[name] == digest for name, digest in REVIEWED_M3.items()), 'exact frozen reviewed M3 sources')
return value
def names(raw):
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
def check_list(raw, expected):
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
'terse list contains only exact tests, no benchmarks or extra entries')
def check_output(raw, count):
require(re.search(rb'^test result: ok\. ' + str(count).encode()
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
'all tests passed without skipped or filtered tests')
def command(args, folder, timeout=300):
index = len(list(folder.glob('command-*.json')))
try:
done = subprocess.run(args, capture_output=True, timeout=timeout)
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
require(done.returncode == 0, 'local qualification command failed; private output retained')
return done.stdout
except subprocess.TimeoutExpired as error:
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('local qualification timed out; no automatic retry') from None
def scripts():
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
def build():
setup_state()
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
before = source_files(); save(folder / 'source-before.json', before)
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable local build image')
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
common = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
'-v', str(ROOT) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target', '--entrypoint', 'cargo', image]
artifacts = {'linux': {}, 'windows': {}}
for platform, triple in [('linux', 'x86_64-unknown-linux-gnu'), ('windows', 'x86_64-pc-windows-gnu')]:
for kind in KINDS:
package, selection = ('rmm-domain', ['--lib']) if kind == 'domain' else ('rmm-agent-core', ['--test', 'contracts'])
options = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline', '--target', triple, '-p', package]
command(common + ['clippy'] + options + selection + ['--', '-D', 'warnings'], folder)
raw = command(common + ['test'] + options + selection + ['--release', '--no-run', '--message-format=json'], folder)
linked = []
for line in raw.splitlines():
try: item = json.loads(line)
except ValueError: continue
expected_name = 'rmm_domain' if kind == 'domain' else 'contracts'
if item.get('reason') == 'compiler-artifact' and item.get('executable') and item.get('profile', {}).get('test') and item['target']['name'] == expected_name:
linked.append(target / Path(item['executable']).relative_to('/target'))
require(len(linked) == 1, 'exact selected unit executable')
destination = folder / platform; destination.mkdir(mode=0o700, exist_ok=True)
original = destination / (kind + '.linked')
delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
for path in (original, delivery): shutil.copyfile(linked[0], path); path.chmod(0o600)
linked_sha = sha(original)
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(destination) + ':/artifacts',
'--entrypoint', tool, image, '--strip-debug', '/artifacts/' + delivery.name], folder)
require(sha(linked[0]) == sha(original) == linked_sha, 'unstripped original link preserved')
data = delivery.read_bytes()
if platform == 'linux':
require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
else:
offset = int.from_bytes(data[60:64], 'little')
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
artifacts[platform][kind] = dict(path=str(delivery.resolve()), sha256=sha(delivery), bytes=len(data),
original_link_path=str(original.resolve()), original_link_sha256=linked_sha, debug_stripped_delivery=True)
# Run exactly the deliverable Linux bytes in an offline disposable container.
for kind, item in artifacts['linux'].items():
invoke = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=128m',
'-v', item['path'] + ':/unit:ro', '--entrypoint', 'python3', image, '-c']
for mode in ('list', 'run'):
args = ['--list', '--format', 'terse'] if mode == 'list' else ['--test-threads=1']
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
raw = command(invoke + [script], folder)
save(folder / ('local-linux-' + kind + '-' + mode + '.json'), dict(stdout_b64=base64.b64encode(raw).decode()))
if mode == 'list': check_list(raw.decode(), EXPECTED['linux'][kind])
else: check_output(raw, COUNTS['linux'][kind])
dynamic = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
'--entrypoint', 'readelf', image, '-d', '/unit'], folder).decode()
versions = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
'--entrypoint', 'readelf', image, '--version-info', '/unit'], folder).decode()
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda x: tuple(map(int, x.split('.'))))
require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 39), 'VM-compatible glibc requirement')
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))
require(source_files() == before, 'source and runner unchanged through qualification')
manifest = dict(schema_version=1, profile=PROFILE, source_files=before, source_before_after_equal=True,
reviewed_m3_source_pins=REVIEWED_M3, m3_adapter_sources_hash_bound_only=True, live_eventlog_query=False,
runner_sha256=sha(__file__), scripts=scripts(), test_names=EXPECTED, test_counts=COUNTS, artifacts=artifacts,
build_image_id=image, both_targets_clippy_D_warnings=True, linux_lists_actual=True,
windows_lists_expected_until_native=True, local_linux_tests_passed=24, native_linux_executed=False,
native_windows_executed=False, product_state_writes=False, rmm_jobs=False)
save(folder / 'manifest.json', manifest)
print(json.dumps(dict(manifest=str((folder / 'manifest.json').resolve()), manifest_sha256=sha(folder / 'manifest.json'),
linux_tests=24, windows_tests_expected=23, native_executed=False)))
def verified(path, new_run):
path = path.absolute(); private(path.parent, True)
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
value = load(path)
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
and value['reviewed_m3_source_pins'] == REVIEWED_M3 and value['m3_adapter_sources_hash_bound_only'] is True
and value['live_eventlog_query'] is False,
'original manifest/runner/remote scripts/profile binding')
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
for platform in COUNTS:
require(set(value['artifacts'][platform]) == set(KINDS), 'exact two artifacts')
for kind, item in value['artifacts'][platform].items():
suffix = '.exe' if platform == 'windows' else ''
require(Path(item['path']) == path.parent / platform / (kind + suffix)
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
return value
def access_settings(root, platform):
"""Read strictly parsed existing access only when the parent executes native."""
require(root is not None and not root.is_symlink(), 'explicit real access-root required')
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
if platform == 'linux':
cfg = access.load_config(root / 'credentials/linux-vm.conf')
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
else:
cfg = access.load_config(root / 'credentials/server.conf')
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
credentials = root / 'credentials'; private(credentials, True)
record = load(credentials / 'windows-dev-access.json')
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
expires = dt.datetime.fromisoformat(record['expires_at'])
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
key = str(Path(cfg['ssh_key_path']).expanduser())
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
private(credentials / 'windows-dev.known_hosts')
return prefix
def transport(prefix, command_text, data, folder, timeout=60):
"""No stdout/stderr escapes the private case directory on transport failure."""
try:
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
save(folder / ('transport-' + 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, 'native transport incomplete; same-case readback only')
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
return value
except subprocess.TimeoutExpired as error:
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('native reply lost; read original case only') from None
def linux_rpc(prefix, payload, folder):
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
return transport(prefix, 'python3 -', code.encode(), folder)
def windows_rpc(prefix, payload, folder):
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
def upload(prefix, item, destination, folder, kind):
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
if '-p' in args: args[args.index('-p')] = '-P'
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
try:
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
except subprocess.TimeoutExpired as error:
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('artifact transfer incomplete; no retry') from None
def linux_case(p):
import resource
import stat
ident = str(uuid.UUID(p['id']))
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-eventlog-contracts-v1', 'fixed unit case')
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain', 'contracts'}, 'fixed Linux root qualification')
root = Path('/var/lib/rmm-windows-eventlog-contracts')
def safe(path, directory):
s = path.lstat()
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
def write(path, value):
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
os.umask(0o077)
case = root / ident
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
if p['action'] == 'prepare':
if not root.exists(): root.mkdir(mode=0o700)
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
return dict(id=ident, prepared=True)
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
original = json.loads((case / 'intent.json').read_bytes())
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
if p['action'] == 'read':
if not (case / 'result.json').exists(): return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start')
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
temp = case / 'tmp'; temp.mkdir(mode=0o700)
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
def limits():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
listings = {}
for kind in ('domain', 'contracts'):
binary = case / kind; safe(binary, False)
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
binary.chmod(0o500)
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
and actual == p['names'][kind] and len(actual) == {'domain': 17, 'contracts': 7}[kind], 'exact native test names before ANY test execution')
listings[kind] = actual
reports = {}
for kind in ('domain', 'contracts'):
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
timed = False
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
except subprocess.TimeoutExpired: timed = True; code = None
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
write(case / (kind + '-result.json'), reports[kind])
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
scripts=p['scripts'], reports=reports, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
write(case / 'result.json', value); return value
WINDOWS = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-eventlog-contracts-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-eventlog-contracts-'+$p.id)
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
Safe $root $true
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
$lists=@{};$executables=@{}
foreach($kind in @('domain','contracts')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''}|Sort-Object);$count=if($kind-eq'domain'){17}else{6};if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};$lists[$kind]=$actual;$executables[$kind]=$exe}
$reports=@{};foreach($kind in @('domain','contracts')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
'''
def check_result(manifest, platform, value, payload):
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
and value.get('environment_cleared') is True and set(value['reports']) == set(KINDS), 'complete native original binding')
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
for kind, item in value['reports'].items():
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
check_output(raw, COUNTS[platform][kind])
def execute(path, platform, access_root, case_id=None):
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
prefix = access_settings(access_root, platform)
if case_id is None:
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED[platform])
if platform == 'windows':
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED['linux'])
check_result(manifest, 'linux', proof['native'], linux_payload)
payload['linux_proof_sha256'] = sha(proof_path)
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
save(folder / 'intent.json', intent)
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
run_read = False
else:
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
payload = intent['payload']; run_read = True
rpc = linux_rpc if platform == 'linux' else windows_rpc
if not run_read:
result = rpc(prefix, dict(payload, action='prepare'), folder)
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
for kind in KINDS:
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-eventlog-contracts-' + case_id + '/' + kind + '.exe'
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
if result.get('status'):
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
check_result(manifest, platform, result, payload)
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
destination = path.parent / (platform + '-passed.json')
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
else: save(destination, proof)
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
manifest_sha256=sha(path), proof_sha256=sha(destination))))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
if args.action == 'build-local':
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
elif args.action.startswith('readback-'):
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
else:
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
execute(args.manifest, args.action, args.access_root)
if __name__ == '__main__':
try: main()
except Exception as error:
print(json.dumps(dict(error='WINDOWS_EVENTLOG_CONTRACT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
raise SystemExit(2) from None
-485
View File
@@ -1,485 +0,0 @@
#!/usr/bin/env python3
"""Package24 pure profile contracts: Linux VM FIRST, then Windows VM.
Only two fixed test executables run in separate bootstrap scratch directories.
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
Native execution is explicit; any lost reply permits same-case readback only.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import stat
import subprocess
import uuid
import vm_access_check as access
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/windows-profile'
IMAGE = 'rust-discovery-durable-final-build:local'
PROFILE = 'windows-process-profile-v1'
LINUX_REMOTE = '/var/lib/rmm-windows-profile-units'
KINDS = ('domain', 'contracts')
COUNTS = {'linux': {'domain': 16, 'contracts': 7}, 'windows': {'domain': 16, 'contracts': 6}}
DOMAIN_NAMES = sorted(('apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
'inventory_document::tests::additive_metadata_and_bounds',
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes', 'jobs::tests::codec_golden_and_exact_script_bytes',
'jobs::tests::no_terminal_replay_or_unknown_restart', 'jobs::tests::permit_codec_golden_all_bindings',
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
'jobs::tests::windows_interpreter_and_capability_contract',
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
'tests::production_never_accepts_development_auth'))
CONTRACT_NAMES = sorted(('atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
'portable_acceptance_requires_platform_capability_and_exact_redelivery'))
UNIX_ONLY = 'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering'
EXPECTED = {'linux': {'domain': DOMAIN_NAMES, 'contracts': CONTRACT_NAMES},
'windows': {'domain': DOMAIN_NAMES, 'contracts': [x for x in CONTRACT_NAMES if x != UNIX_ONLY]}}
def require(value, code):
if not value:
raise RuntimeError(code)
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def object_pairs(items):
value = {}
for key, item in items:
require(key not in value, 'duplicate JSON field')
value[key] = item
return value
def private(path, directory=False):
item = Path(path).lstat()
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
'private owned regular path')
def load(path):
private(path)
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
def save(path, value):
private(Path(path).parent, True)
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
def setup_state():
os.umask(0o077)
STATE.parent.mkdir(mode=0o700, exist_ok=True)
metadata = STATE.parent.lstat()
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
'owned non-world-writable devstate parent')
STATE.mkdir(mode=0o700, exist_ok=True)
private(STATE, True)
def source_files():
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
'deploy/windows_profile_acceptance.py', 'deploy/remote_client_bootstrap.py',
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/windows/client_bootstrap.py')]
paths += list((ROOT / 'crates').rglob('Cargo.toml'))
for name in ('domain', 'agent-core', 'protocol'):
paths += [p for p in (ROOT / 'crates' / name).rglob('*') if p.is_file()]
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
for path in paths:
require(not path.is_symlink() and path.is_file(), 'regular source inputs only')
return {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
def names(raw):
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
def check_list(raw, expected):
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
'terse list contains only exact tests, no benchmarks or extra entries')
def check_output(raw, count):
require(re.search(rb'^test result: ok\. ' + str(count).encode()
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
'all tests passed without skipped or filtered tests')
def command(args, folder, timeout=300):
index = len(list(folder.glob('command-*.json')))
try:
done = subprocess.run(args, capture_output=True, timeout=timeout)
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
require(done.returncode == 0, 'local qualification command failed; private output retained')
return done.stdout
except subprocess.TimeoutExpired as error:
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('local qualification timed out; no automatic retry') from None
def scripts():
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
def build():
setup_state()
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
before = source_files(); save(folder / 'source-before.json', before)
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable local build image')
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
common = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
'-v', str(ROOT) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target', '--entrypoint', 'cargo', image]
artifacts = {'linux': {}, 'windows': {}}
for platform, triple in [('linux', 'x86_64-unknown-linux-gnu'), ('windows', 'x86_64-pc-windows-gnu')]:
for kind in KINDS:
package, selection = ('rmm-domain', ['--lib']) if kind == 'domain' else ('rmm-agent-core', ['--test', 'contracts'])
options = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline', '--target', triple, '-p', package]
command(common + ['clippy'] + options + selection + ['--', '-D', 'warnings'], folder)
raw = command(common + ['test'] + options + selection + ['--release', '--no-run', '--message-format=json'], folder)
linked = []
for line in raw.splitlines():
try: item = json.loads(line)
except ValueError: continue
expected_name = 'rmm_domain' if kind == 'domain' else 'contracts'
if item.get('reason') == 'compiler-artifact' and item.get('executable') and item.get('profile', {}).get('test') and item['target']['name'] == expected_name:
linked.append(target / Path(item['executable']).relative_to('/target'))
require(len(linked) == 1, 'exact selected unit executable')
destination = folder / platform; destination.mkdir(mode=0o700, exist_ok=True)
original = destination / (kind + '.linked')
delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
for path in (original, delivery): shutil.copyfile(linked[0], path); path.chmod(0o600)
linked_sha = sha(original)
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(destination) + ':/artifacts',
'--entrypoint', tool, image, '--strip-debug', '/artifacts/' + delivery.name], folder)
require(sha(linked[0]) == sha(original) == linked_sha, 'unstripped original link preserved')
data = delivery.read_bytes()
if platform == 'linux':
require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
else:
offset = int.from_bytes(data[60:64], 'little')
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
artifacts[platform][kind] = dict(path=str(delivery.resolve()), sha256=sha(delivery), bytes=len(data),
original_link_path=str(original.resolve()), original_link_sha256=linked_sha, debug_stripped_delivery=True)
# Run exactly the deliverable Linux bytes in an offline disposable container.
for kind, item in artifacts['linux'].items():
invoke = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=128m',
'-v', item['path'] + ':/unit:ro', '--entrypoint', 'python3', image, '-c']
for mode in ('list', 'run'):
args = ['--list', '--format', 'terse'] if mode == 'list' else ['--test-threads=1']
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
raw = command(invoke + [script], folder)
save(folder / ('local-linux-' + kind + '-' + mode + '.json'), dict(stdout_b64=base64.b64encode(raw).decode()))
if mode == 'list': check_list(raw.decode(), EXPECTED['linux'][kind])
else: check_output(raw, COUNTS['linux'][kind])
dynamic = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
'--entrypoint', 'readelf', image, '-d', '/unit'], folder).decode()
versions = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
'--entrypoint', 'readelf', image, '--version-info', '/unit'], folder).decode()
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda x: tuple(map(int, x.split('.'))))
require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 39), 'VM-compatible glibc requirement')
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))
require(source_files() == before, 'source and runner unchanged through qualification')
manifest = dict(schema_version=1, profile=PROFILE, source_files=before, source_before_after_equal=True,
runner_sha256=sha(__file__), scripts=scripts(), test_names=EXPECTED, test_counts=COUNTS, artifacts=artifacts,
build_image_id=image, both_targets_clippy_D_warnings=True, linux_lists_actual=True,
windows_lists_expected_until_native=True, local_linux_tests_passed=23, native_linux_executed=False,
native_windows_executed=False, product_state_writes=False, rmm_jobs=False)
save(folder / 'manifest.json', manifest)
print(json.dumps(dict(manifest=str((folder / 'manifest.json').resolve()), manifest_sha256=sha(folder / 'manifest.json'),
linux_tests=23, windows_tests_expected=22, native_executed=False)))
def verified(path, new_run):
path = path.absolute(); private(path.parent, True)
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
value = load(path)
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True,
'original manifest/runner/remote scripts/profile binding')
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
for platform in COUNTS:
require(set(value['artifacts'][platform]) == set(KINDS), 'exact two artifacts')
for kind, item in value['artifacts'][platform].items():
suffix = '.exe' if platform == 'windows' else ''
require(Path(item['path']) == path.parent / platform / (kind + suffix)
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
return value
def access_settings(root, platform):
"""Read strictly parsed existing access only when the parent executes native."""
require(root is not None and not root.is_symlink(), 'explicit real access-root required')
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
if platform == 'linux':
cfg = access.load_config(root / 'credentials/linux-vm.conf')
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
else:
cfg = access.load_config(root / 'credentials/server.conf')
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
credentials = root / 'credentials'; private(credentials, True)
record = load(credentials / 'windows-dev-access.json')
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
expires = dt.datetime.fromisoformat(record['expires_at'])
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
key = str(Path(cfg['ssh_key_path']).expanduser())
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
private(credentials / 'windows-dev.known_hosts')
return prefix
def transport(prefix, command_text, data, folder, timeout=60):
"""No stdout/stderr escapes the private case directory on transport failure."""
try:
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
save(folder / ('transport-' + 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, 'native transport incomplete; same-case readback only')
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
return value
except subprocess.TimeoutExpired as error:
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('native reply lost; read original case only') from None
def linux_rpc(prefix, payload, folder):
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
return transport(prefix, 'python3 -', code.encode(), folder)
def windows_rpc(prefix, payload, folder):
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
def upload(prefix, item, destination, folder, kind):
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
if '-p' in args: args[args.index('-p')] = '-P'
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
try:
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
except subprocess.TimeoutExpired as error:
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
raise RuntimeError('artifact transfer incomplete; no retry') from None
def linux_case(p):
import resource
import stat
ident = str(uuid.UUID(p['id']))
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-process-profile-v1', 'fixed unit case')
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain', 'contracts'}, 'fixed Linux root qualification')
root = Path('/var/lib/rmm-windows-profile-units')
def safe(path, directory):
s = path.lstat()
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
def write(path, value):
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
os.umask(0o077)
case = root / ident
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
if p['action'] == 'prepare':
if not root.exists(): root.mkdir(mode=0o700)
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
return dict(id=ident, prepared=True)
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
original = json.loads((case / 'intent.json').read_bytes())
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
if p['action'] == 'read':
if not (case / 'result.json').exists(): return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start')
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
temp = case / 'tmp'; temp.mkdir(mode=0o700)
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
def limits():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
listings = {}
for kind in ('domain', 'contracts'):
binary = case / kind; safe(binary, False)
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
binary.chmod(0o500)
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
and actual == p['names'][kind] and len(actual) == {'domain': 16, 'contracts': 7}[kind], 'exact native test names before ANY test execution')
listings[kind] = actual
reports = {}
for kind in ('domain', 'contracts'):
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
timed = False
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
except subprocess.TimeoutExpired: timed = True; code = None
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
write(case / (kind + '-result.json'), reports[kind])
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
scripts=p['scripts'], reports=reports, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
write(case / 'result.json', value); return value
WINDOWS = r'''
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-process-profile-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-profile-'+$p.id)
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
Safe $root $true
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
$lists=@{};$executables=@{}
foreach($kind in @('domain','contracts')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''}|Sort-Object);$count=if($kind-eq'domain'){16}else{6};if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};$lists[$kind]=$actual;$executables[$kind]=$exe}
$reports=@{};foreach($kind in @('domain','contracts')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
'''
def check_result(manifest, platform, value, payload):
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
and value.get('environment_cleared') is True and set(value['reports']) == set(KINDS), 'complete native original binding')
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
for kind, item in value['reports'].items():
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
check_output(raw, COUNTS[platform][kind])
def execute(path, platform, access_root, case_id=None):
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
prefix = access_settings(access_root, platform)
if case_id is None:
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED[platform])
if platform == 'windows':
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED['linux'])
check_result(manifest, 'linux', proof['native'], linux_payload)
payload['linux_proof_sha256'] = sha(proof_path)
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
save(folder / 'intent.json', intent)
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
run_read = False
else:
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
payload = intent['payload']; run_read = True
rpc = linux_rpc if platform == 'linux' else windows_rpc
if not run_read:
result = rpc(prefix, dict(payload, action='prepare'), folder)
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
for kind in KINDS:
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-profile-' + case_id + '/' + kind + '.exe'
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
if result.get('status'):
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
check_result(manifest, platform, result, payload)
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
destination = path.parent / (platform + '-passed.json')
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
else: save(destination, proof)
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
manifest_sha256=sha(path), proof_sha256=sha(destination))))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
if args.action == 'build-local':
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
elif args.action.startswith('readback-'):
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
else:
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
execute(args.manifest, args.action, args.access_root)
if __name__ == '__main__':
try: main()
except Exception as error:
print(json.dumps(dict(error='WINDOWS_PROFILE_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
raise SystemExit(2) from None
+63 -2
View File
@@ -53,17 +53,78 @@ Zugänge und private Rohbelege bleiben gitignoriert.
## Aktuelle Windowsfortsetzung
Gemeinsame passive Komponentenwartung nach dokumentiertem ersten APIfehler
abgeschlossen, Originalfall `6d2df065…` und separate Recovery `595dd1da…`.
ActualAgent `89004ad3…` LocalService/Auto PID8108; Helper `e6aacbdd…`
SYSTEM/Manual PID2620; Policy `007adf5f…`, Pin `126670bc…`. Alle vier Dateien
mit expliziten Nativebackups und Datei-ID-/ACL-/Frozenprüfungen ersetzt,
danach beide eigenen Dienste jeweils einmal gestartet. Zwei frische WSS-
Heartbeats, konkretes Inventar-ACK, Tenantverweigerung und Erhaltung bestanden.
Runtime-/Komponentenindex per CAS veröffentlicht; Ursprung/Fehler/Backups erhalten.
Abschluss `ac00411f…`, Recoveryacceptance `5ad5925c…`. Keine Jobs/Bindings,
Clockfalse, Wirkungen/Rebootfalse, Intentablage weiter0B. Die ursprünglichen
Stoppedabschnitte unten sind jetzt historische Zwischenstände.
Positive Pipeabnahme weiterhin **fehlgeschlagen**: tatsächlicher neuer Agent
8108 meldet `client_read_reply`/`HELPER_PIPE_IO`/Win32233; privater Helper-
Diagnosebeleg fehlt. Das grenzt den Clientpfad ein, beweist aber keine konkrete
Serverursache. [Wartung/Recovery](windows-system-delegation-upgrade.md).
Clockkandidat nach W32Time-Start tatsächlich nativ ausgeführt, Fall `e1f3edbb…`:
LocalService bestätigt, beide ALPC-Proben1753, kein Endpunkteintrag; beide
Negativkontrollen ebenfalls1753, kein Identitätsnachweis. Named-Pipe-Diagnose1783
ohne Status, Ursache noch unbewiesen. Originalbericht separat identisch gelesen,
eigener temporärer Dienst entfernt, Zentralstände/Flags erhalten. Clockabnahme
**nicht bestanden**, Gatefalse und keine Jobs. Microsoft spezifiziert für
MS-W32T Named Pipes, keinen zugesicherten ALPC-Endpunkt. [Native Details](windows-clock-readiness.md).
Vorhandenes W32Time ausdrücklich autorisiert einmal gestartet, nativer Fall
`c3552c3f…`: Running und unveränderte RMM-PIDs5140/6240, Konfiguration,
PKI-Metadaten und Dienstdefinition bestätigt. Getrennter Readback identisch,
Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene Flags erhalten. Kein
Uhrqualifikations- oder Rebootbeleg; `ADAPTER_QUALIFIED=false`. [Startnachweis](windows-time-service-start.md).
Separater M3-Branch `codex/windows-eventlog`, Commit `eb38b4b`: fester
Application-/Fixtureprovider, begrenzter authentisierter Worker und sichtbarer
hashgebundener Plan implementiert und unabhängig geprüft. Lokal238Rust,
isolierterPG-Fall und38Webtests/Build/Clippy bestanden; anschließend nativ
Cloud-Linux24→Windows23 ohne Skips, Manifest `ed1371e9…`, Fälle `6f9bdfb7…`
und `ccb258a7…`. Quellen und beide Abnahmeschritte jeweils gepusht. Dies sind
Vertragsunits, keine tatsächliche LocalService-Eventlog-Abfrage oder Jobwirkung.
Keine Capability aktiviert, keine Runtime ersetzt. [Quellen und genaue Grenzen](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-eventlog/docs/windows-eventlog-source.md).
Separater Profilbranch `codex/windows-powershell-profile`, Commit `207b91f`:
RemoteSigned als optionales festes Aktions-/Variantenfeld implementiert, alte
Bytes erhalten, UI-Planansichten streng gebunden. Lokal Rust-/Server-/35Web-
Prüfungen bestanden; danach nativ Cloud-Linux23 ohne Skips, Fall `f463acc9…`,
Manifest `26247a3a…`. Anschließend nativ Windows22 ohne Skips bestanden,
Fall `9abd3e0d…`, Proof `47cee8c9…`, an denselben Linuxbeleg gebunden. Keine
Profilcapability veröffentlicht und kein PowerShelljob gestartet. Der
Hauptcheckout bleibt für die Komponentenwartung unverändert. Quellen/Nachweise:
[Profilbranch](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-powershell-profile).
Ein separat tatsächlich bestätigter Schemars-Nullable-Metadatenunterschied
betrifft keine Berechtigung; sein enger Attributfix wird im isolierten folgenden
M3-Schnitt mitgeführt. Der ursprüngliche Nativebeleg wird nicht umgeschrieben.
Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der
WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest
gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung;
manueller VM-Konsolenneustart erst nach konkreter Zeitabstimmung. Keine Remote-
oder RMM-Rebootfreigabe. Umsetzung des optionalen Skriptprofils noch offen.
oder RMM-Rebootfreigabe. Profilquelle und Vertragsunits im oben genannten
isolierten Branch vorhanden; tatsächlicher genehmigter Job weiterhin offen.
[Begrenzter Vertrag](windows-powershell-policy.md).
Gemeinsamer Upgradefall `6d2df065…` bisher vor dem Server-Beforecheckpoint
abgebrochen, kein Enter-/Stop-/Swap-/Startintent. Bestehender RMM-Agent meldet
weiter Heartbeats; Reverse-Tunnellistener vorhanden, aber TCP-Weiterleitung
liefert derzeit kein SSH-Banner. Kein Upgradefortschritt daraus ableiten.
lieferte zunächst kein SSH-Banner. Ein eng begrenzter Devtransport-Reset im
Fall `eed7dad0…` beendete genau den separat identifizierten Tunnel-Sessionchild
über sein gepinntes Prozesshandle; kein SSH-Master-/UID-Reset. Der bestehende
Windowsloop stellte den Listener neu her; Anmeldung mit unverändert gepinntem
Windows-Hostschlüssel und lesender Nachbeleg bestanden. Agent5140 und Helper6240
laufen unverändert, W32Time weiterhin gestoppt. Ursache der ursprünglichen
Bannerblockade unbewiesen; keine neue Schlüssel-/Port-/Expiryfreigabe und kein
VM-Neustart. Kein Upgradefortschritt daraus ableiten.
Konkrete Zeitabstimmung für den bereits zugesagten manuellen Konsolenneustart
wurde angefragt; bis zur Antwort keine Ziel-Neustartaktion und keine Annahme
eines erfolgten Neustarts. Aktuelle Artefakte weiterhin2bee/921c.
+2 -1
View File
@@ -1,6 +1,6 @@
# Entdeckungen und Aufgaben nach dem Linux-MVP
Stand 2026-11-13. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
Stand 2026-11-14. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen
Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und
[Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht.
@@ -10,6 +10,7 @@ Pfad bleiben dort sofort relevant.
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
| --- | --- | --- |
| 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. |
| Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. |
| Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. |
+44
View File
@@ -262,3 +262,47 @@ SDK-Struktur bleibt aufx64 begrenzt und wird beim MSVC-Build zusätzlich direkt
gegen die native SDK-Deklaration geprüft. Dies ersetzt weder einen nativen
MSVC- noch einen tatsächlichen W32Time-Nachweis. W32Time ist weiterhin gestoppt;
Produktgate unverändert `ADAPTER_QUALIFIED=false`.
## Autorisierter Dienststart — noch keine Clockabnahme
Nach ausdrücklicher Userentscheidung1.18 wurde das vorhandene W32Time im Fall
`c3552c3f…` genau einmal gestartet und separat lesend als Running bestätigt.
RMM-Agent/Helper samt ursprünglichen PIDs, Definitionen und PKI-Metadaten,
ausgewählte NTP-/Policywerte und zentrale Jobzählungen/Flags sind erhalten.
Keine Startart-/NTP-/ACLänderung oder Resynchronisierung angefordert; normale
Synchronisierung durch den Dienst ist erlaubt. [Genauer Beleg](windows-time-service-start.md).
Ein neuer GNU-Diagnosebuild `a817cf61…`, EXE `f5003f96…`, wurde lokal mit
identischen Quellbindungen vor/nach gebaut. Sein tatsächlicher ALPC-/Status-/
Identitätskontrolllauf ist inzwischen ausgeführt; Ergebnis folgt unten. Der
Dienststart allein öffnet weder Clock- noch Jobgate.
## Tatsächlicher Kandidatenlauf nach Dienststart: nicht qualifiziert
Fall `e1f3edbb-5a2f-4d82-a449-0432913c6bd7`, EXE `f5003f96…`, nativ als
separater LocalService-Dienst: TokenSID19, kein Administratormitglied/SYSTEM,
zwei Statusproben und beide Identitätskontrollen ausgeführt. ALPC meldet jeweils
`1753`/`CLOCK_UNSUPPORTED`; die Endpunktenumeration meldet Erfolg mit0Einträgen.
Beide Negativkontrollen ebenfalls1753, **kein Ablehnungs-/Identitätsbeweis**.
Die zusätzliche Named-Pipe-Diagnose meldet1783 ohne Status. Noch unbewiesen,
ob dessen Quelle RPC/NDR oder der eigene strikte Strukturguard ist. Keine
stillschweigende Status-/Authentisierungs-/Transportlockerung.
Der eigene temporäre Dienst wurde nach Stopped entfernt; der normale Agent und
SYSTEM-Helper wurden nicht gestoppt oder verändert. Separater Readback bestätigt
identischen Originalbericht. Zentralstände0/0/0/0 und30/30/26/0 sowie geschlossene
Flags/Rootpolicyhash vor/nach unverändert. Privater Fallabschluss
`assessment.json`, SHA256
`d80e5f39cbd6d332deb12bf4f21e1372c88025b551db4ef33a190e3f82b3300a`.
Native Ausführung belegt, **Clockabnahme fehlgeschlagen**; Produktionsgatefalse,
keine Windowsjobs oder Capabilities aktiviert.
Nach dem Lauf erneut gegen Microsoft geprüft: MS-W32T2.1 verlangt Named-Pipe-
Transport und nennt den authentisierten Endpunkt `W32TIME_ALT`; ein ALPC-
Endpunkt ist damit kein zugesicherter Plattformvertrag. Der bisherige ALPC-
Kandidat war ein zu qualifizierender Zusatz, keine native Windowsgarantie.
[Transportvertrag](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655),
[vollständiges IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
Die konkrete1783-Ursache wird separat rein diagnostisch eingegrenzt; eine
erfolgreiche unqualifizierte Pipeabfrage würde die Clockgrenze weiterhin nicht
öffnen. Bereits vorhandene Originalfehler bleiben unverändert erhalten.
+262
View File
@@ -0,0 +1,262 @@
# Windows-Entwicklungszugang: Ablauf und vorbereitete Konsolenwiederherstellung
Stand: 2026-11-14. Der bisherige SSH-Entwicklungszugang lief am
**2026-11-14T12:55:31.254999+00:00** ab. Die vorher vorbereitete automatische
Verlängerung wurde **nicht betreten**: kein Server- oder Windows-Enter, keine
Ablaufzeitänderung und kein angelegter Renewalworker. Die drei fehlgeschlagenen
Vorbereitungen und ihre Quellen bleiben historische Belege.
**Aktueller Stand:** Die spätere User-Konsolenwiederherstellung wurde
erfolgreich ausgeführt; Root bestätigte anschließend die tatsächliche Rückkehr
des gepinnten SSH-Zugangs. Auch der getrennte vollständige Key-/Task-
Erhaltungsabgleich und der lokale Accessmetadaten-CAS sind inzwischen bestanden.
Einzelheiten stehen im neuen Abschlussabschnitt dieser Verlaufserfassung.
Diese Entwicklungshilfe ist SSH-Bootstrap, keine RMM-Aktion und kein Ersatz für
Geräte-mTLS, Tenantgrenzen, TrustedClock, signierte Grants oder die
WebUI-Genehmigung. Das Notebook bleibt ausschließlich Entwicklungsrechner.
## Tatsächliche abgebrochene Vorbereitungen
| Fall unter `devstate/windows-client/dev-access-renewal/` | Tatsächliches Ergebnis |
| --- | --- |
| `45626a0c-edc4-4f35-9f36-921692bccbc1` | Rein lesende Windows-Vorbereitung verweigerte `Transport owner` vor dem Serveraufruf. Die zwei öffentlichen `.pub`-Dateien gehörten dem tatsächlichen lokalen Builtin-Administrator mit SID-Endung `-500`; deren bestehende öffentlichen Leserechte waren für die ursprüngliche private Dateiprüfung zu weit. Nur die separate öffentliche Metadatenprüfung wurde später präzisiert; keine ACL-Reparatur. |
| `d40c06a4-d6d3-4dc0-9ef6-b1ef1197bcc9` | Rein lesende Windows-Vorbereitung verweigerte `VariableNotWritable`: die Hilfsvariable `$host` kollidierte mit PowerShells schreibgeschütztem `$Host`. Die Quelle wurde anschließend auf `$hostPublic` korrigiert. Keine Server- oder Windowsmutation. |
| `6988fd11-0e0a-4fd7-878d-96b130d83aee` | Der lokale Datums-/Fristguard verweigerte nach Ablauf der alten Frist, noch vor `prepare-intent.json`. Dies war kein weiterer ausgeführter Windows-Readonly-Test. Der leere lokale Fall bleibt erhalten. |
Die ersten beiden Fälle enthalten nur Vorbereitungsintent und Controllerkopie;
keiner enthält einen Server-/Windows-Enterintent. Root bestätigte zusätzlich,
dass kein Renewal-Enter und kein Worker ausgeführt wurden. Ablauf und Fehler
werden nicht nachträglich als erfolgreiche Verlängerung ausgegeben.
## Getrennte Wiederherstellung des bereits abgelaufenen Zugangs
Die neue Quelle
[`console_access_recovery.py`](../deploy/windows/console_access_recovery.py)
hat SHA-256
`703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053`.
Sie trennt den Server-CAS von der erst anschließend durch den User in der
Windows-Administratorkonsole auszuführenden Phase. Die frühere
[`dev_access_renewal.py`](../deploy/windows/dev_access_renewal.py) wird für den
abgelaufenen Lease nicht umgedeutet oder erneut gestartet.
Root führte ausschließlich den Serverteil im neuen Fall
`4b6506a7-6c3e-4cca-a497-618fa8666300` aus. Dessen `server-entered.json`
meldet `completed=true`; ein getrennt gespeicherter lesender Readback bestätigt
dieselbe neue Autorisierungsdatei und Frist:
| Bindung | Tatsächlicher Beleg |
| --- | --- |
| Neue feste UTC-Frist | `2026-11-15T13:05:58+00:00` |
| `authorized_keys` nach CAS | `fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2` |
| Unverändertes SSH-Profil | `932adc2ad3e88c3a47054c3d09e44024f21918cf144f0bb349bd8763e844e482` |
| Unveränderte effektive SSH-Konfiguration | `3a345912fdd4bb9bb29628d670a8bdbdfbbc22b3e308ab56fb3bafb7bc15533a` |
| Server-Enterbeleg | SHA `2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317` |
| Getrennter Readback | SHA `f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787` |
Der Serverteil ersetzte ausschließlich den Ablaufwert des gleichen bestehenden
restriktiven Tunnelkeys. Keybytes und Optionen, Loopbacklistener
`127.0.0.1:22240`, SSH-Profil, Serverhostpin und der Account
`rmm-win-tunnel` mit Shell `/usr/sbin/nologin` blieben gebunden. Historische
`prepared.json`/`registered.json` wurden nicht überschrieben. Dieser CAS
veränderte weder einen Downloadlease noch die RMM-Konfiguration.
## Öffentliches Paket und noch offene Userphase
Unter dem privaten Consolefall liegt das **inzwischen zurückgezogene,
historisch erhaltene** öffentliche Paket mit genau
`Recover-ExistingDevAccess.ps1`, `public-recovery.json` und `README.txt`.
Es enthält öffentliche Pins und feste Parameter, keine privaten Schlüssel oder
Tokens. Die Paketdateien sind zusätzlich im unveränderlichen Intent gebunden.
| Datei | SHA-256 |
| --- | --- |
| `windows-dev-access-recovery.zip` | `7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7` |
| `Recover-ExistingDevAccess.ps1` | `564da57d70ef06df7bd9adc37565b7e28ef446a6c69b984711c5b77b28441e8a` |
| Consoleintent | `cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a` |
Vor der Userausführung fand Root im Konsolenguard eine unbelegte
Ganzsekundenannahme für den alten `AccountExpires`-Wert. Der feste Wert
`134391345310000000` ließ den Bruchteil `.254999` der ursprünglichen
Konfigurationszeit weg. Ein lokaler .NET-Roundtrip derselben vollständigen
UTC-Zeit ergibt `134391345312549990`. Dieser lokale Roundtrip allein war ein
**abgeleiteter Sollwert**, noch kein gemessener Windows-VM-Accountwert. Der
spätere tatsächliche Userreadback ist unten getrennt dokumentiert. Das alte Paket wird deshalb nicht zur
Ausführung weitergegeben; sein gültiger getrennter Server-CAS bleibt erhalten.
Die kleine neue Quelle
[`console_access_precision.py`](../deploy/windows/console_access_precision.py)
mit SHA
`8b4d14edf0794c4ef662d7587b4538f8e7aebc06c11db76c3cafc2c24c11a37b`
erzeugte den neuen lokalen Consolefall
`5c96d3d8-1657-40c8-a6ec-c00b63a98210`. Sie bindet den ursprünglichen
Serverintent, Enterbeleg und getrennten Readback des Falls `4b6506…` sowie
sämtliche alten Paketdateihashes. Es gibt weder einen Serveraufruf noch eine
erneute Fristverlängerung: `2026-11-15T13:05:58+00:00` bleibt unverändert.
Der neue Guard berechnet genau einen erwarteten 64-Bit-Wert über
`[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc()` aus der
zuvor anhand der Originalbytes und der exakten alten Zeit geprüften Config.
Keine Rundung, Toleranz oder alternative Zeit wird akzeptiert. UUID und
Provenienzbeleg sind neu; die drei Mutationsschritte ab `File.Replace` bis
zum Ende sind gegenüber dem alten Paket bytegleich. Falls ein früheres Paket
entgegen dem bisherigen Kontrollstand bereits erfolgreich ausgeführt wurde,
muss der alte Config-Hashguard verweigern. Dann nur lesen und durch Root
abgleichen, kein neuer Versuch.
| Neues Korrekturartefakt | SHA-256 |
| --- | --- |
| ZIP im Fall `5c96d3d8…` | `dbcd5ca863c0b09f89b67eb10eeaeaf89b941bbc5840079f1bb0c36dc6ff3b3e` |
| Neues `Recover-ExistingDevAccess.ps1` | `4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69` |
| Neuer unveränderlicher Intent | `eae7995b5735bf1e8f0fafc0ae6ccf6bdd4576566663c1256a511f6c3408e32e` |
Die Userphase mit dem Konsolenskript des Falls `5c96…` wurde inzwischen begonnen,
scheiterte aber vor jeder Wirkung an `Get-History / IdCannotConvert`: PowerShells
standardmäßiger Alias `h` wird auch unter `-NoProfile` vor der Funktion `H`
aufgelöst. Der Fehler trat im ersten Case-/Configguard vor `New-Item` auf.
Es wurde damit keine Konfigurations-/Accountablaufzeit geändert und kein
Tunneltask gestartet. Die unveränderte Case-Abwesenheitsprüfung bleibt für die
erste tatsächlich noch unerreichte Wirkung verbindlich.
Die separate lokale Quelle
[`console_access_hash_command.py`](../deploy/windows/console_access_hash_command.py)
hat SHA `b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad`.
Sie erzeugt `Recover-ExistingDevAccess-HashFix.ps1` mit SHA
`d366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c`.
Ausschließlich die eine Funktionsdefinition und alle fünf Aufrufe heißen nun
`Get-RmmRecoveryFileSha256`; eine inverse Ersetzung ergibt exakt die alten
PS1-Bytes. Alle übrigen Guards, Pins, Fristen, die gleiche Console-UUID und
Mutationsschritte bleiben erhalten. Kein Alias wird entfernt oder geändert.
Der kleine Userpatch `Create-VerifiedHashFix.ps1` mit SHA
`385a388476cef0c85f02bca236ade48f28a041476330d3e309ab1ca2f22bb9f5`
prüft zuerst den ursprünglichen PS1-Hash `4977665f…`, erzeugt ausschließlich
eine zuvor fehlende neue Datei mit UTF-8 ohne BOM, verlangt deren vollständigen
Hash `d366ae17…` und startet erst dann den separaten Bootstrapprozess mit
`-NoProfile -ExecutionPolicy RemoteSigned`. Kein neuer Download ist für diese
lokale Korrektur erforderlich. Bereits vorhandene Korrekturdateien werden
nicht überschrieben und eine unklare frühere Wirkung wird nicht wiederholt.
ASTs, vollständige Command-AST-Ersetzung sowie ein tatsächlicher lokaler
Hashfunktionsaufruf bei unverändert vorhandenem Alias `h=Get-History` bestanden;
der unabhängige Review bestätigte die reine Namensänderung. Das sind lokale
PowerShellprüfungen, kein weiterer Windows-VM-Erfolgsnachweis. Alte Quellen,
ZIPs und Fehlerbelege bleiben unverändert.
Die anschließende tatsächliche Userausführung des HashFix-Skripts `d366ae17…`
verweigerte im kombinierten anfänglichen Case-/Config-/Bootstrapguard weiterhin
vor Wirkung. Root ließ zunächst ausschließlich fünf Werte lesend ausgeben.
Der Userreadback ergab:
| Tatsächlicher Konsolenwert | Ergebnis |
| --- | --- |
| Recoverycase vorhanden | `false` |
| Config-SHA | `4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823` |
| Bootstrap-SHA | `332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f` |
| Configablaufzeit | `2026-11-14T12:55:31.254999+00:00` |
| Tatsächliches Account-FILETIME | `134391345312549990` |
Damit ist dieser Guardfehler konkret erklärt: die Recoveryquelle erwartete
den späteren Repositoryhash `9e992602…`, obwohl die VM exakt das ursprünglich
veröffentlichte Bootstrap mit Hash `332ceeed…` behielt. Das erhaltene Original-ZIP
`cba15946…` enthält genau diese Datei und die Config `4ad28ec5…`; das ebenfalls
veröffentlichte Reparaturpaket `2558448b…` bindet denselben Bootstraphash als
Voraussetzung und ersetzt Bootstrap/Config nicht. Der Maintainerteil beider
Bootstrapquellen ist bytegleich. Es wird somit keine unbekannte Datei anhand
eines beliebigen neuen Readbacks übernommen.
Die getrennte lokale Quelle
[`console_access_original_bootstrap.py`](../deploy/windows/console_access_original_bootstrap.py)
mit SHA `c0816055407c17af4c0bf4b5bd5ce3055e5a9d44fe7f2334f5aa7913520478c6`
bindet den tatsächlichen Userreadback und beide publizierten Originalpakete.
Sie erzeugt `Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit SHA
`aba0a5a4152347e639266e95a05eae4343a99be9070a94fa4fc6501bfc3283d2`.
Ausschließlich die eine Bootstrap-Sollhashkonstante wird von `9e992602…` auf
das bestätigte Original `332ceeed…` berichtigt. Alle anderen Bytes des
`d366ae17…`-Skripts, einschließlich gleicher Case-Abwesenheit, voller UTC-
Präzision, Aliasfix, Fristen und Wirkungsschritte, bleiben identisch.
Der Userpatch `Create-VerifiedOriginalBootstrapFix.ps1` hat SHA
`64f1d62ea3a87d4db7103ca01f7d735689caf54a7cc4b2458908956624062549`.
Er verlangt den vollständigen Eingabehash `d366ae17…`, schreibt nur eine
zuvor fehlende neue Datei, prüft deren vollständigen Hash `aba0a5a4…` und
startet erst danach den separaten Bootstrapprozess. Lokaler Python-/AST-Test,
ein tatsächlicher lokaler PowerShelllauf des Patchpräfixes ohne Kindstart und
der unabhängige byteweise Review bestanden. Dadurch wird die Userausführung
der korrigierten Wirkung noch nicht vorweggenommen. Kein Serveraufruf und keine
weitere Serverfriständerung wurden durch diese lokale Korrektur ausgeführt.
Eine erfolgreiche Windows-Konsolenphase und Tunnelwiederkehr sind **noch nicht
nachgewiesen**. Die korrigierte Strecke prüft die alten
Config-/Bootstrapbytes und öffentlichen Pins, den bestehenden Account sowie den
unveränderten SYSTEM-Tunneltask. Erst bei `Ready` und ohne verbliebenen
Maintainer/SSH-Kindprozess darf sie die vorhandene Konfigurations- und
Accountablaufzeit erneuern und den Originaltask mit dauerhaftem Startintent
**einmal** starten. Private Keydateien werden nur über Metadaten beobachtet,
nicht inhaltlich gelesen. Keine Installation, ACL-Reparatur, neue Schlüssel,
zusätzlichen SSH-Rechte, Prozesskills, Reboots oder RMM-Wirkungen.
Die README verlangt den unabhängig mitgeteilten Downloadhash und den festen
PS1-Hash. Ein etwaiges `Unblock-File` betrifft nur diese exakt geprüfte
Download-Datei; `RemoteSigned` nur den separaten Bootstrapprozess. Eine
verweigernde GPO oder ein fehlgeschlagener Guard wird nicht umgangen. Ein
bereits vorhandener Recoveryfall bleibt zur lesenden Inspektion erhalten.
Eine gesonderte, auf 45 Minuten begrenzte Veröffentlichung über den vorhandenen
öffentlichen TLS-Bootstrapdienst wird durch Root separat behandelt. Dieser
Server-CAS und diese Dokumentation belegen noch keine Downloadveröffentlichung.
Nach der Userausführung bleiben tatsächliche Tunnelwiederkehr, ursprüngliche
SSH-Hostidentität, erhaltene Schlüssel/Taskdefinition und die lokale
Accessmetadatenfortschreibung durch Root zu prüfen. **Neuer Windowszugriff ist
bis dahin nicht nachgewiesen.**
Lokale Python-/AST- und Paketprüfungen sowie unabhängige Source-Reviews bestanden.
Der lokale Paketfixture verwendete einen gemockten Serveraufruf und ist kein
zusätzlicher nativer Recoverybeleg. Kein RMM-Job, keine Capability oder
Clockbereitschaft folgt aus der Zugangswiederherstellung.
## Update: User-Konsolenerfolg und tatsächlicher gepinnter SSH-Kontakt
Der User meldete die erfolgreiche Ausführung der korrigierten Konsolenstrecke
`Recover-ExistingDevAccess-OriginalBootstrap.ps1` mit Hash `aba0a5a4…`.
Root erhielt danach über den bereits gepinnten SSH-Zugang tatsächlich eine
getrennte rein lesende Antwort. Der lokale Verifikationsfall ist
`fc7a6ad5-5ec5-4280-b629-851aad2529b2`; sein `readback.json` hat SHA
`bb0e2b4747068433bcb7c950743ef56007f22206ca5d4b458f6b8221a4a031e2`.
Der Beleg nennt weiterhin den ursprünglichen Consolefall
`5c96d3d8-1657-40c8-a6ec-c00b63a98210`, `read_only=true`,
`completed=true` und `no_jobs=true`.
| Tatsächlich beobachteter Wert | Ergebnis |
| --- | --- |
| Configablaufzeit | `2026-11-15T13:05:58+00:00` |
| Accountablaufzeit als FILETIME | `134392215580000000` |
| Originaler Reverse-Tunneltask | `Running` |
| `RmmDiscoveryWindows` | `Running`, PID `3172`, `NT AUTHORITY\LocalService`, Startart `Auto` |
| `RmmDiscoverySystemHelper` | `Stopped`, PID `0`, `LocalSystem`, Startart `Manual` |
| `W32Time` | `Running`, PID `3488`, `NT AUTHORITY\LocalService`, Startart `Manual` |
Damit ist die Rückkehr des Entwicklungszugangs belegt. Die früheren Aussagen
zur noch offenen Userphase bleiben historische Zwischenstände. Der zusätzliche
rein lesende Erhaltungsbeleg desselben Falls (`preservation.json`, SHA256
`490e01809ca1e4225f1dbb6a0a4414cf77f7822be31233366480b3a0d4810592`)
bestätigt alle sechs festen öffentlichen Dateien samt SHA/SDDL, Metadaten und
SDDL der vier privaten SSH-Schlüssel ohne Lesen ihrer Inhalte, den exakten
Originaltask-XML-Hash und Runningzustand, Account-SID sowie alle öffentlichen
Pins. Danach wurde lokal ausschließlich die Frist im Accessmetadaten-JSON per
CAS auf `2026-11-15T13:05:58+00:00` fortgeschrieben. Der SSH-Präfix blieb exakt
erhalten; Original und neuer Metadatenbeleg sind privat archiviert. Die alten
Fehlerfälle, Pakete und Korrekturquellen bleiben erhalten.
Der Readback ist kein Paarupgrade-, TrustedClock-, Boot- oder RMM-Jobnachweis.
Insbesondere eröffnet `W32Time=Running` keine Clockbereitschaft. Der Helper
war tatsächlich noch gestoppt; daraus wird kein authentisierter neuer
Agent-/Helper-Pipeaustausch abgeleitet. Root führt die getrennten Pipe-/MIDL-
Prüfungen erst anschließend fort.
Der User hat den nächsten Arbeitsfokus ausdrücklich auf die Skriptkonsole mit
vollständigem Shell-/PowerShellinhalt, tatsächlicher WebUI-Plangenehmigung,
Ausgabe und expliziten Root-/SYSTEM-Ausführungsrechten gelegt. Paketabnahmen
sind nachgeordnet. Der erneuerte SSH-Bootstrapzugang verleiht selbst keine
RMM-Ausführungsrechte und ersetzt keine dieser noch separat nachzuweisenden
Genehmigungs- und Ausführungsgrenzen.
@@ -1,65 +0,0 @@
# Native M3-Eventlog-Vertragsprüfung
`deploy/windows_eventlog_acceptance.py` ist ein neuer, separater Bootstraprunner.
Der unveränderte Profilrunner und dessen16/7- beziehungsweise16/6-Belege bleiben
readbackfähig. Neuer Namespace: `windows-eventlog-contracts`.
Der neue Pack enthält ausschließlich Domain-Lib17 und Core-Contracts7 auf Linux,
danach Domain-Lib17 und Core-Contracts6 auf Windows. Der Unix-OpenSSL-Paritätstest
entfällt unter Windows. Server-/Windows-M3-Quellen werden zusätzlich exakt an den
geprüften Stand gebunden, einschließlich Schemars-Metadatenfix und Gateway-
Ergebnisprüfung. Diese Adapterquellen werden durch die beiden Vertrags-EXEs
**nicht** als native Eventlogprovider qualifiziert. Es gibt weder Liveabfrage
noch RMM-Job, Capabilityaktivierung, Dienst-/Produktdatenbank-/PKIänderung.
Tatsächlich auf Cloud-Linux bestanden:24Prüfungen ohne Skips, Fall
`6f9bdfb7-3902-462e-a08f-ec612e36c635`. Gemeinsamer Build
`afb44f9b-8040-4efa-ac2c-fd6c3a43f8a6`, Manifest-SHA256
`ed1371e9b058f8e7f874b071fcfce1bc409769546d5e63235295adadb5ec1de7`,
Linuxproof-SHA256
`d37ce1644dd169c932176e3e9bd33cee22b9fa4698e9faa0f5aea0f2de09f7d4`.
Anschließend bestanden auf der Windows-VM alle23Prüfungen ohne Skips, Fall
`ccb258a7-5930-4e02-b955-d522f98f0c36`, Windowsproof-SHA256
`ee1ba206637f2465e7a066b6e23ca2f8bf9b57c0ae08ddc80fe23e0199b027e1`.
Dieser Beleg bindet denselben Build und den ursprünglichen Linuxproof.
Der lokale Build mit
98identischen Vorher-/Nachher-Inputs, vier erhaltenen Original-Linkdateien,
beiden Ziel-Clippyprüfungen und24lokalen Linux-Vertragstests ist bestanden.
Der lokale Offlinebuild erhält Original-Linkdateien neben gestrippten
Lieferkopien, prüft Clippy für beide Vertragsziele und führt die tatsächlichen
Linux-Lieferbytes mit exakter Liste und ungefiltert aus. Windowslisten bleiben
bis zur tatsächlichen Windowsausgabe erwartet. Vor/nach müssen sämtliche
gebundenen Cargo-/Toolchain-/Domain-/Core-/Protocol-/Proto-/Server-/Windows- und
Runner-/Bootstrapquellen gleich sein. Ein weiterer Backend-/PG-Testlauf ist
nicht Bestandteil dieses Runners.
**Aufrufschema; beide obigen nativen Fälle tatsächlich ausgeführt:**
```sh
python3 deploy/windows_eventlog_acceptance.py build-local
python3 deploy/windows_eventlog_acceptance.py linux --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
python3 deploy/windows_eventlog_acceptance.py windows --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
```
Artefakte und lokale Belege bleiben im isolierten Eventlogworktree. Ausschließlich
`--access-root` liest bei ausdrücklicher nativer Ausführung streng geparste
bestehende SSH-Konfigurationen für Cloud-Linux116.203.20.85 beziehungsweise den
bekannten gepinnten Windows-Reversezugang. Keine Credentialkopie oder neue
Hostkeyannahme. Windows bindet den SHA256 des zuvor tatsächlich verifizierten
Linuxbelegs desselben Manifests.
Jeder native Fall hat eigene Create-once-Intents und Startbelege. Linux nutzt
privaten Rootscratch, geleerte Umgebung und eigene Netzwerknamespace. Beide
Plattformen prüfen vor dem ersten Teststart die vollständigen Testnamen beider
Programme. Windows läuft als Bootstrapadministrator, kein LocalService-Nachweis.
Ausgaben und Transportfehler bleiben privat; stdout enthält nur Status und
Nachweishashes.
Nach Antwortverlust ausschließlich `readback-linux` beziehungsweise
`readback-windows` mit ursprünglichem Manifest, `--case UUID` und `--access-root`.
Readback lädt nichts hoch und startet nichts neu. Er bindet unveränderliche
Originalintents, Manifest sowie Runner-/Remotescripthashes; spätere
Produktquellenänderungen erzwingen keinen neuen Lauf. Nur neue Starts benötigen
den aktuellen exakt qualifizierten Quellstand. Unvollständige Fälle bleiben
unvollständig; kein automatischer zweiter Versuch.
-55
View File
@@ -1,55 +0,0 @@
# Windows-M3: begrenztes Ereignisprotokoll
Stand2026-11-14: Quelle implementiert und unabhängig gegenseitig geprüft,
noch nicht auf dem Windowsgast installiert oder als RMM-Aktion ausgeführt.
Der isolierte Branch enthält auch das bereits separat nativ qualifizierte
optionale PowerShell-Prozessprofil. Keine Capability wurde veröffentlicht.
`query_logs` bindet ausschließlich Quelle
`windows.eventlog.application.rustdiscovery-mvp-test`, Kanal `Application`
und Provider `RustDiscovery-MVP-Test`. Erforderlich sind Windows-/Sync- und
eigene Fixturecapability, `logs:read` und `agent_service`. Kein SYSTEM-Logpfad,
kein freies XPath, kein angeforderter Liveabruf als passives Inventar.
UTC-Zeitfenster höchstens24Stunden, höchstens65536Ausgabebytes und feste
innere5Sekunden-Grenze; äußerer Jobrahmen10–120Sekunden. Alle Werte stehen
aus hashgeprüften gespeicherten Planbytes vor der WebUI-Genehmigung fest.
Die synchrone native Eventlog-API läuft im begrenzten eigenen Prozess innerhalb
des vorhandenen atomaren JobObjects. Der Child prüft tatsächlichen LocalService-
Token samt Agent-Service-SID, echten SCM-/Kernel-Elternprozess, geschützte
Konfiguration, signierten Originalrequest, aktuelle qualifizierte Uhr und Boot,
den bereits dauerhaft gebuchten Verbrauch/Start samt tatsächlichem SQLite-
Dateihandle sowie einen einmaligen Startmarker. Der Aufruf über den festen
CLI-Modus allein verleiht keine Berechtigung. Keine Schlüssel-/Requestbytes
auf der Kommandozeile. Uhr-/Jobgates bleiben geschlossen.
Worker und Server prüfen konkrete Herkunft, Zeitfenster, Budget, Vollständigkeit
und Fehler. Bekannte Ereignis-/Byte-/Einzelereignisgrenzen bleiben ausdrücklich
partiell; Zeitüberschreitung oder Berechtigungsfehler werden kein vollständiger
Erfolg. Eine im Review gefundene Lücke im serverseitigen Successguard wurde
geschlossen: `win32_error` ausdrücklichnull, kein Neustartbedarf und generisches
Kürzungsflag identisch zur konkreten Evidenz.
Lokal tatsächlich bestanden:238Rusttests, ein isolierter PostgreSQL-Fall und
38Webtests samt Typecheck/Build/Clippy. Der PG-Fall prüfte unter anderem fehlendes
`logs:read`, verlorene Capability und `pending_approval` mit0Jobs/Outbox/Grants.
Nach dem Successguard-Fix wurden dessen bestehende Mutationsmatrix und
Server-Clippy gezielt erneut ausgeführt. Drei portable Provider-/Ergebnistests
liefen tatsächlich im Linux-Buildcontainer; zwei Windows-Workerprüfungen sind
bisher nur crosskompiliert. Keine dieser Ebenen ersetzt den Nativepfad.
Private Quellenbelege: `devstate/windows-eventlog-backend/qualification.json`
(`facab5cc…`), `qualification-success-flags.json` (`f5972644…`) und
`devstate/windows-eventlog/windows-source-qualification.json` (`feb16e79…`).
Die gesonderte Vertragsabnahme ist zuerst auf Cloud-Linux24, danach Windows23
ohne Skips bestanden. Manifest `ed1371e9…`; Linuxfall `6f9bdfb7…`, Windowsfall
`ccb258a7…`. [Native Runnerdokumentation](windows-eventlog-contract-acceptance.md)
hält genaue Bindungen und Grenzen fest. Kein Live-Eventlog-/Workerrollenbeweis.
Weiter offen: reale LocalService-Eventlog-API, eigene Fixtureereignisse,
Filter-/Zeit-/Ausgabe-/Fehlergrenzen und vollständiger WebUI-genehmigter Job.
Keine Registrierung oder Erhebung auf dem Ziel wurde durch diese Quellarbeiten
ausgeführt. Der Schemars-Attributfix entfernt lediglich die irreführende
Nullable-Angabe des optionalen Prozessprofils; strikte Deserialisierung und
fehlendes Feld bleiben unverändert. Die vorherigen Nativebelege bleiben an
ihre ursprünglichen Quellen gebunden.
+3 -2
View File
@@ -1,6 +1,6 @@
# Windows-Client: Abnahmegates
Stand 2026-11-14, Spezifikation 1.17. Der Windows-11-x64-Gast ist ein eigenes
Stand 2026-11-14, Spezifikation 1.18. Der Windows-11-x64-Gast ist ein eigenes
Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner;
Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP
bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht.
@@ -12,9 +12,10 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
| Signierter Jobkern | Gemeinsamer Kern zuletzt nativ Linux80→Windows58 qualifiziert. Neuer enger SYSTEM-Delegationsadapter mit dauerhaftem Intent, deny-only Abandon und unabhängigem RawMirror implementiert; native23+7Units bestanden. Bestehender laufender passiver Client bleibt unverändert; neue Artefakte noch nicht installiert. Jobs bleiben deaktiviert. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Units ersetzen keinen LocalService-/SYSTEM- oder Jobnachweis; [Quellenstand](windows-system-delegation-source.md). |
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. |
| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Separates optionales festes RemoteSigned-Prozessprofil ausdrücklich erlaubt, sichtbar an Plan/Grant gebunden; native Vertragsunits zuerst Linux23, danach Windows22 bestanden, Quellenbranch gepusht. Keine tatsächliche Jobausführung oder Profilcapability. | Profilquelle in die laufende Strecke übernehmen, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. Maschinen-/Gruppenrichtlinien unverändert. |
| Privilegierte Aktionen | Eigener SYSTEM-Helper nativ installiert und einmal gestartet, Manual/LocalSystem, leere Aktionsliste und Wirkungen/Reboot gesperrt. Die echte LocalService-Agentprobe scheitert derzeit; kein positiver Peer-/Sync-/Wirkungsnachweis. | Fehler ohne Erweiterung der Sicherheitsgrenze diagnostizieren; gegenseitige SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen. |
| Pakete/Dienste/Logs | Kleines MSI1.0.0 auf der VM erstellt, nur lesend geprüft und nach Download gehasht; keine Installation. Dienst-/Eventlog-/Paketquellen teilweise vorbereitet, keine native Aktionsabnahme. | Unveränderliche Tenantrezepte integrieren; UI-genehmigte MSI-/EXE-Installation/Upgrade/Noop, Dienste und Logs mit unabhängigen Nachbedingungen prüfen. |
| Eventlog-Vertrag | Im separaten Branch `codex/windows-eventlog` fester Application-/Fixtureprovider, authentisierter begrenzter Worker und hashgebundene UI implementiert/geprüft. Lokal238Rust/PG1/Web38 bestanden; nativ Linux24→Windows23 Vertragsunits ohne Skips. Keine Live-API-Abfrage, Runtimeinstallation oder Capabilityaktivierung. | Tatsächlichen LocalService-Provider und ausschließlich WebUI-genehmigten Job samt Grenzen/Fehlern auf dem Windowsgast qualifizieren. |
| Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. |
| Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. |
| Reboot/Installer | Entwicklungsbuild unsigniert, GNU-Crossbuild; kein MSVC-/signierter Installer-/Windows-Rebootnachweis. | Eigene Abnahmen; kein Windows-Reboot ist durch den bereits ausgeführten Linux-Testreboot autorisiert. |
+112
View File
@@ -0,0 +1,112 @@
# Windows Helper: begrenzte Transportbestätigung
Dieser Schnitt ist im isolierten Zweig `codex/windows-pipe-drain` implementiert.
Eine native Ausführung des neuen Framings und ein Komponentenupgrade sind noch
nicht nachgewiesen. Die bestehenden Nachweise des Agenten `89004ad3…` und Helpers
`e6aacbdd…` bleiben historische Belege ihres ursprünglichen Framings.
## Anlass und Beleggrenze
Beim tatsächlichen Agenten wurde `client_read_reply / HELPER_PIPE_IO / 233`
beobachtet; die Helperdiagnose war nicht vorhanden. Der bisherige Dienst rief
auch nach erfolgreichem Schreiben der Antwort sofort `DisconnectNamedPipe` auf.
Microsoft dokumentiert, dass dabei ungelesene Pipebytes verworfen werden. Das
ist ein konkreter möglicher Fehlerpfad, aber kein Nachweis, dass genau dieser
Pfad die beobachtete Störung verursacht hat.
[DisconnectNamedPipe](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)
Eine fehlende Diagnose beweist weder einen erfolgreichen Peercheck noch eine
bestimmte Ablehnung: strukturierte `Denied`-Antworten erzeugen keinen privaten
Pipefehlerbeleg, Connect-Leerlauf kann ohne Beleg enden, und das begrenzte
Diagnoseschreiben selbst kann fehlschlagen. Diese Pfade werden hier nicht
umgedeutet oder gelockert.
## Framing v2 und Reihenfolge
Agent und Helper verwenden ausschließlich `\\.\pipe\RustDiscovery-System-v2`.
Jeder JSON-Frame beginnt mit acht ASCIIbytes `RDPIPC02`, gefolgt von vier Bytes
Länge in Big Endian und den bisherigen, maximal 1 MiB großen JSONbytes.
V1 und V2 haben unterschiedliche Endpunkte; zusätzlich verweigert der V2-Parser
alte oder fremde Framingtags. Es gibt keinen stillen Fallback. Beide EXEs müssen
als gemeinsam qualifiziertes, gegenseitig gepinntes Paar bereitgestellt werden.
Die JSONschemas von Call/Reply, `helper.system.v1`, Systempolicy-Schema 1 und
RMM-Jobbytes ändern sich nicht.
Nach dem vollständigen Lesen der Antwort prüft der Agent weiterhin den tatsächlichen
Helperprozess, Schema, Challenge, Enrollmentbindung, Policyhash, Helperbinaryhash
und die Operation/Antwort-Zuordnung. Erst danach schreibt er genau 56 Bytes:
`RDPACK02` (8), ursprüngliche UUID-Challenge in UUID-Bytefolge (16), SHA-256 der
**exakt empfangenen JSON-Antwortbytes** (32). Es findet keine Re-Serialisierung
für diese Prüfsumme statt. Auch eine vollständig geprüfte `Denied`-Antwort wird
so transportseitig bestätigt, ohne sie in einen Erfolg umzuwandeln.
Der Helper prüft denselben bereits authentifizierten Peer vor dem Schreiben und
nach dem Lesen der Bestätigung. Schreiben, Empfang und Prüfung der Bestätigung
teilen dieselbe bisherige Antwortdeadline von fünf Sekunden; der Client behält
seine bisherige Gesamtdeadline. Erst danach trennt die Dienstschleife die Pipe.
Fehlende, falsche oder verspätete Bestätigung schließt den bestehenden Syncgate
und trennt die Verbindung über den bisherigen Fehlerpfad; statische Diagnosen
unterscheiden `server_drain_receipt` und `client_drain_receipt`. Es gibt keinen
weiteren Aufruf, Retry oder erneute Ausführung.
Diese Bestätigung bestätigt nur den Empfang der Antwortbytes. Sie ist kein
JobResult-, Journal-, SignedSync-, Grant-, Freigabe- oder Wirkungsbeleg und löscht
keinen dauerhaften Zustand. Ein bereits ausgeführter Auftrag wird durch einen
fehlenden Transport-ACK nicht zurückgenommen oder wiederholt.
`FlushFileBuffers` wird nicht verwendet: dieser synchrone Pipeaufruf wartet laut
Microsoft bis zum Lesen aller gepufferten Daten und bietet hier keine passende
begrenzte Warteoperation.
[FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers)
## Prüfung und verbleibender nativer Nachweis
Die bestehenden IPC-Codecfälle prüfen zusätzlich fremde/alte Frameversionen,
begrenzte Längen sowie manipulierte ACK-Tags, Challenge und Prüfsumme. Eine andere
JSON-Bytefolge mit gleichem JSON-Inhalt darf den ursprünglichen Frame nicht
bestätigen. Die bestehenden Unitfallzahlen bleiben dadurch unverändert.
Lokale Qualifikation wird separat in einem geschützten `devstate/`-Beleg mit
Quellen- und Artefakthashes erfasst. Cross-Clippy und Linken sind kein nativer
Pipebeleg. Vor einem Zielupgrade sind unabhängiger Quellreview, die nativen
Windows-Units des gleichen Manifests und ein eigener erhaltender Paarupgrade mit
explizitem Backup sowie anschließendem tatsächlichen Agent/Helper-Austausch
notwendig. Alle Produktgates bleiben geschlossen.
Lokale Ausführung: Default- und `system-helper`-Clippy für alle Windows-GNU-Targets
mit `-D warnings`, Release-Build beider EXEs und Linken beider Unitprogramme waren
erfolgreich. 61 gebundene Quelldateien blieben vor/nach dem Lauf gleich. Die
bestehenden 23 Library- und 7 Binary-Unitfälle sind weiterhin die **erwartete**
native Liste; hier wurde kein Windows-Testprogramm ausgeführt. Geschützter
Beleg: `devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json`.
## Separater Build-/Unitrunner
`deploy/windows/system_pipe_acceptance.py` erstellt einen neuen Pack unter
`devstate/windows-pipe-drain-build/`. Er prüft den unveränderten lokalen
Qualifikationsbeleg samt ursprünglichen Links und verwendet die bereits
bestandenen Clippy-/Release-/Unitlinkschritte wieder. Nur die fehlenden beiden
Release-Stateprobes werden ergänzt. Alle sechs Auslieferungsdateien erhalten
eine unveränderte `.linked`-Kopie; ausschließlich die Unit-Auslieferungskopien
werden von Debuginformationen befreit. Neue Quellen einschließlich Runner,
Compilerimage, Cargo-/Protoinputs und tatsächlich verwendeter Bootstrapmodule
sind vor/nach dem Build gebunden.
`--access-root` muss der ursprüngliche Hauptcheckout sein. Nur dort werden die
vorhandenen geschützten Zugangskonfigurationen für den bereits gepinnten
Bootstraptransport und die tatsächlichen Linux-80-/Windows-58-Corebelege gelesen.
Es werden keine Zugangsdaten oder Main-`devstate`-Bäume kopiert oder verlinkt.
Neue Build-, Upload- und Unitfallbelege gehören zum isolierten Pipeworktree.
Der Native-Unitfall verwendet den neuen Namespace `native-pipe-v2`. **Beide**
vollständigen nativen Listen müssen exakt den erwarteten 23 Library- und 7
Binary-Namen entsprechen, bevor irgendein Unitfall ausgeführt wird. Intent,
Listen, Start und einzelne Testergebnisse werden create-only gespeichert.
Nach einem Antwortverlust darf ausschließlich derselbe Fall gelesen werden;
auch ein fehlender oder unvollständiger Fall löst keinen erneuten Start aus.
Die Units laufen als Bootstrapadministrator, nicht als Produkt-LocalService,
und beweisen keinen tatsächlichen Pipeaustausch. Zentral gespeicherte
Gerätezähler und geschlossene Fault-/Policyflags werden vor/nach verglichen.
Der bestehende rohe `helper_peer_controls::raw`-Probe schreibt weiterhin einen
V1-Header. Sein Ablehnungsresultat ist deshalb **kein** V2-Peernegativnachweis;
Runner und Manifest behaupten ausdrücklich keine solche Qualifikation.
+5 -6
View File
@@ -1,11 +1,10 @@
# Windows PowerShell5.1: feste prozessbezogene RemoteSigned-Option
Stand2026-11-14, Spezifikation1.18. **Userentscheidung als Sourcekandidat im
isolierten Profilbranch umgesetzt und nativ Linux-first vertraglich geprüft.**
Die23 Domain-/Coreverträge bestanden auf der Cloud-Linux-VM; Windows22 und die
tatsächliche genehmigte PowerShellwirkung bleiben offen. Keine Capability-,
Clock- oder Jobkonfiguration aktiviert, kein Deployment. Hauptcheckout und
laufende Windowsartefakte bleiben unverändert. [Tatsächlicher Nachweis](windows-profile-acceptance.md).
Stand2026-11-14, Spezifikation1.18. **Userentscheidung dokumentiert,
Implementierungsentwurf noch nicht umgesetzt und nicht nativ abgenommen.**
Diese Arbeit liest Produktquellen und ändert ausschließlich Dokumentation.
Laufende Rust-/Artefaktbindungen bleiben unverändert. Keine VM-/Server-/Gitaktion
oder Capability-/Clock-/Jobkonfigurationsänderung gehört zu diesem Schritt.
## Autorisierter Umfang
-65
View File
@@ -1,65 +0,0 @@
# Native Prüfung des optionalen Windows-Prozessprofils
Stand2026-11-14: implementierter und unabhängig geprüfter Profilvertrag im
isolierten Branch `codex/windows-powershell-profile`. Domain-/Server-/Original-
Grantprüfungen, isolierter PostgreSQL-Fall, beide Windows-Cross-Clippy-Profile,
35Webtests, Typecheck und Webbuild lokal bestanden. Zwei UI-Aliasbefunde und
die zunächst akzeptierte Null-/Objekt-Profilform sind eng korrigiert.
Anschließend bestanden auf der tatsächlichen Cloud-Linux-VM alle23 Vertrags-
prüfungen ohne Skips, Fall `f463acc9-ab77-4b70-bcfb-a016f40c9410`.
Gemeinsamer Build `005b26fd-8269-40dd-8a35-798fabb024a5`, Manifest-SHA256
`26247a3a9c187e8ce315250ab3bb3a8b5c1fe681028b15143fb9f193e4af9c80`,
Linuxproof-SHA256 `7ecabd9a3ca8fac20aaa7a185b6e128735ea77f143988f058829ae642ad32d25`.
Danach bestanden alle22 Windows-Vertragstests ohne Skips, Fall
`9abd3e0d-d40f-4d6f-adc8-8fdbbefb98e8`, Windowsproof-SHA256
`47cee8c9c449a45699641d53c0fca48b89a53a90dd22cfd03a2ab7675c0a348d`.
Der Windowsbeleg bindet denselben Build und den vorangegangenen Linuxproof.
Kein Deployment oder tatsächlicher PowerShell-Job; neue Profilcapability nicht
veröffentlicht. Der Hauptcheckout und seine zuvor qualifizierten Artefakte
bleiben für die ausstehende Komponentenwartung unverändert.
`deploy/windows_profile_acceptance.py` ist ein eigener Bootstrap-Nachweisrunner,
kein RMM-Executor. Er verwendet ausschließlich zwei feste Unitprogramme:
Domain-Lib16 und Core-Contracts7 auf der Cloud-Linux-VM, danach Domain-Lib16 und
Core-Contracts6 auf der Windows-VM. Nur der Unix-OpenSSL-Paritätstest entfällt
unter Windows. Es werden keine Dienste, Produktjournale, PKI, Policies,
Capabilities oder RMM-Jobs verändert. SQLite-Fixturen entstehen ausschließlich
im eigenen temporären Testverzeichnis. Die Windows-Tests laufen als
Bootstrapadministrator; sie beweisen keinen LocalService- oder SYSTEM-Job.
Der lokale Build erhält Original-Linkdateien neben den gestrippten Lieferkopien,
prüft beide Clippy-Ziele und führt die tatsächlich lieferbaren Linuxbytes lokal
mit `--list` und ungefiltert aus. Alle Workspace-Cargomanifeste, Lock/Toolchain,
Domain/Core/Protocol/Proto sowie Runner und Bootstraptransport werden vorher und
nachher gehasht. Windows-Testnamen sind bis zur nativen Ausgabe nur erwartet.
Der lokale Linuxlauf ersetzt keinen Linux-VM-Nachweis.
**Aufrufschema; obige Fälle tatsächlich ausgeführt:**
```sh
python3 deploy/windows_profile_acceptance.py build-local
python3 deploy/windows_profile_acceptance.py linux --manifest devstate/windows-profile/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
python3 deploy/windows_profile_acceptance.py windows --manifest devstate/windows-profile/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
```
`--access-root` dient ausschließlich dem streng geparsten bestehenden
SSH-Zugang: Cloud-Linux `116.203.20.85` bzw. der unveränderten gepinnten
Windows-Reverse-SSH-Kette über Cloud-Loopback22240. Keine Credentialkopien,
Symlinks oder Hostkeyänderung. Alle Artefakte und lokalen Belege bleiben im
isolierten Profilworktree. Linux läuft mit geleerter Umgebung und eigener
Netzwerknamespace. Beide nativen Phasen prüfen vor dem ersten Teststart sämtliche
Testnamen beider Programme. Windows bindet den bereits verifizierten tatsächlichen
Linux-Beleg desselben Manifests über dessen SHA256.
Jeder Fall hat eigene Create-once-Intents und Startbelege. Eine verlorene Antwort
erlaubt ausschließlich beispielsweise `readback-linux --manifest … --case UUID
--access-root …` bzw. `readback-windows`. Dieser Pfad lädt nichts hoch und startet
keinen Prozess erneut. Er kann `remote_case_absent`, `prepared_without_start` oder
`started_without_result` als unvollständigen Stand berichten. Ein neuer Fall ist
keine automatische Fehlerwiederholung. Originale Readbacks bleiben an das feste
Manifest, Intents und Runner-/Remotescripthashes gebunden; spätere Änderungen an
Produktquellen erzwingen keine neue native Ausführung und verhindern ihren
Readback nicht. Neue Starts benötigen weiterhin die exakt qualifizierten
aktuellen Quellen. Vollständige Ausgaben/Transportfehler bleiben privat,
Standardausgabe enthält nur Status, Fallkennung und Nachweishashes.
+72 -3
View File
@@ -1,7 +1,8 @@
# Gemeinsames passives Windows-Komponentenupgrade
Stand 2026-11-14: **Source vorbereitet; dieser Upgradefall wurde noch nicht auf
der VM ausgeführt.** Lokale Guards und PowerShell-Parserprüfung ersetzen weder
Stand 2026-11-14: **Passive Wartung nach separat dokumentiertem ersten APIfehler und
enger Recovery abgeschlossen. Positive Pipeabnahme weiterhin fehlgeschlagen.**
Lokale Guards und PowerShell-Parserprüfung ersetzen weder
die neuen nativen Unitnachweise noch den tatsächlichen Erhaltungs-/Pipebeleg.
Der Notebookhost bleibt ausschließlich Entwicklungsrechner.
@@ -72,10 +73,78 @@ Runtimeindex per lokalem CAS um einen neuen Komponentenbeleg ergänzt. Ein noch
fehlgeschlagener Pipebeleg bleibt ausdrücklich fehlgeschlagen; ein erfolgreiches
passives Komponentenupgrade behauptet keine Jobfähigkeit.
Geplante Befehle, **nicht ausgeführt**:
Aufrufvorlagen; tatsächlichen Fallstand unten beachten:
```text
python3 deploy/windows/system_delegation_upgrade.py upgrade-passive --manifest <manifest.json> --qualification <passed.json>
python3 deploy/windows/system_delegation_upgrade.py readback --id <ursprüngliche UUID>
python3 deploy/windows/system_delegation_upgrade.py finish --id <ursprüngliche UUID>
```
## Tatsächlicher Fall6d2df065: erster Dateiaufruf fehlgeschlagen
Originalfall `6d2df065-0877-41c4-983c-2c9fdb6e5437` scheiterte zunächst vor dem
Server-Beforecheckpoint. Nach wiederhergestelltem gepinntem SSH-Zugang wurden
fehlender entfernter Fall/Activeintent und unveränderte Originalprozesse separat
lesend bestätigt. Ein zusätzlicher dauerhafter Fortsetzungsintent führte
ausschließlich die erste zuvor nicht erreichte Phase desselben Falls aus.
Originale Fehlermeldung und Quellen blieben erhalten, kein neuer Enrollment-
oder RMM-Jobkontext.
Native Stopps beider eigenen Dienste bestanden. Frozenbeleg und sämtliche vier
privaten Originalbackups wurden gespeichert. Beim ersten Dateitausch meldete
`[IO.File]::Replace($candidate,$destination,$null)` eine ArgumentException.
Sofortiger gesonderter Readback: Agent/HelperStopped, vier Zielhashesoriginal,
keine Replaced-/Swapped-/Startmarker. Eine weitere Nur-Leseprüfung bestätigt
Frozen-DBbytes, Zeilen, tatsächliche Dateiidentitäten und PKI-Metadaten erhalten.
Nur der erste Agentcandidate (exakter neuer Hash) und sein ursprünglicher
Replaceversuchsmarker existieren; andere Candidates/Replaceversuche fehlen.
Eigene native Einbyte-API-Fixture `45a21a07-a115-47ec-93e1-694aa519520a`:
Nullbackupaufruf reproduziert ArgumentException, Quelle/Destination unverändert;
separater Aufruf mit explizitem Backup schreibt erwartete Destination und
Originalbackup. Keine Runtime-Datei wurde durch diese Fixture berührt. Die
genauere interne PowerShell-/Framework-Konvertierungsursache wird daraus nicht
als bewiesen behauptet.
Der ursprüngliche Enter wird nicht erneut ausgeführt, Originalmarker und
Quellen nicht geändert. Eine separate create-only Recovery muss vor jeder
Fortsetzung diesen konkreten Vier-Dateien-/Frozen-/Nichtstartzustand bestätigen,
den existierenden ersten Candidate hashgeprüft erhalten und einen ausdrücklich
benannten zusätzlichen Nativebackup verwenden. Erst nach allen vier neuen
Datei-/ACL-/Frozenbelegen dürfen die bisher noch nicht versuchten eigenen
Helper-/Agentstarts folgen. Kein automatischer Retry oder Rücksetzen.
## Tatsächliche enge Recovery und Abschluss
Neue Quelle `deploy/windows/system_delegation_recovery.py`, SHA `64ced170…`,
Script `65e480f2…`, unabhängig geprüft und lokal Python-/PS-AST geprüft. Originale
Quelle `f8dc1c8f…` unverändert. Recoveryfall
`595dd1da-0d7f-4364-9040-a75e16c6da83` bestätigte separat den vollständigen
Stopped-/Frozen-/Datei-ID-/Candidatekontext und führte einmal vier Tausche mit
expliziten zusätzlichen Nativebackups durch. Alle vier neuen Dateien, ACLs und
Frozen-Datenbanken wurden vor dem ersten Start geprüft. Anschließend Helper,
danach Agent jeweils einmal gestartet; getrenntes Readback bindet dieselben
Phasen. Originalmarker und erste ArgumentException bleiben erhalten.
Originales `finish` war danach ausschließlich lesend: zwei frische WSS-
Heartbeats, konkretes Inventar-ACK/fortgeschrittene Sequenz, gleicher Tenant/
Geräteidentität und fremder Tenant verweigert. Journale/Dateiidentitäten/Zeilen,
Konfiguration und PKI-Metadaten erhalten. ZählerWindows0/0/0/0, Linux30/30/26/0
und geschlossene Flags/Rootpolicy unverändert. Runtime-/Komponentenindex erst
nach diesen Belegen lokal per CAS veröffentlicht. Kein OS-Reboot, kein Job,
kein Binding oder neuer Clock-/Wirkungsgate; Intentdateien weiter0Byte.
Tatsächlicher Agent `89004ad3…`, LocalService/Auto, PID8108, Geburtswert
`134391259111815072`; Helper `e6aacbdd…`, SYSTEM/Manual, PID2620, Geburtswert
`134391259068713651`. Policy `007adf5f…`, reziproker Pin `126670bc…`.
Privater Originalabschluss `result.json` SHA256
`ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460`;
Recoveryabschluss `acceptance.json` SHA256
`5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb`.
Die positive Pipeprobe bleibt ausdrücklich fehlgeschlagen: tatsächlicher neuer
Agent meldet `client_read_reply`/`HELPER_PIPE_IO`, Win32233, kein authentisierter
Austausch und kein privater Helperdiagnosebeleg. Dies ist ein erfolgreicher
passiver Erhaltungs-/Wartungsnachweis, kein SYSTEM-Sync-/Job-/Clocknachweis.
Kein erneutes Enter oder Wiederverwenden der ursprünglichen Startbefehle.
+53
View File
@@ -0,0 +1,53 @@
# Windows-Pipe v2: tatsächlicher Unitnachweis
Dieser Ergebnisnachtrag ergänzt den unveränderten, im Buildmanifest gebundenen
[Framing-/Drain-Entwurf](windows-helper-pipe-drain.md). Der Entwurf bleibt als
historischer Quellenstand erhalten; dieser Nachtrag verändert weder seinen Hash
noch das ursprüngliche Manifest.
## Tatsächlich auf Windows bestanden
Root führte im eigenen nativen Fall
`db25cd4a-bfd2-45d5-9f80-1881950853f7` die beiden konkreten Testprogramme des
Pipe-v2-Packs aus. Beide vollständigen nativen Listen wurden vor irgendeinem
Unitfall exakt geprüft. Alle23 Libraryfälle und alle7 Binaryfälle bestanden;
kein Fall war fehlgeschlagen, ignoriert oder gefiltert. Beide Listenprozesse
und beide Testprozesse endeten mit Exit0 ohne Timeout. Die gemeldete Testdauer
betrug2,76s für die Library und0,07s für das Binary.
| Gebundener Beleg | SHA256 |
| --- | --- |
| Neues Pipe-v2-Buildmanifest | `b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4` |
| Tatsächlicher Native-PASS | `19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713` |
| Begrenzter Unitrunner | `2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf` |
| Library-Lieferdatei | `3fc2b7314d755f5c5235c8383cf605cbe848180180497bb30540482f4910c2a1` |
| Binary-Lieferdatei | `a3b8f44e87df7af54f82c1d052753217e9a03c495fb28c8a16ba9fe7e1a0af23` |
Geschützter nativer Beleg im isolierten Pipeworktree:
`devstate/windows-client/native-pipe-v2/db25cd4a-bfd2-45d5-9f80-1881950853f7/passed.json`.
Das zugehörige unveränderliche Buildmanifest liegt unter
`devstate/windows-pipe-drain-build/build-59623db2-15ca-40cd-8728-861f84b2a550/manifest.json`.
Die vorherige Manifestgeneration `928841e7…`, ihre Links und sämtliche früheren
Belege bleiben erhalten.
## Was dieser PASS belegt
Die vorhandenen IPC-Codec-/Sicherheits-/Journal-/Runtimefälle liefen tatsächlich
auf Windows als Bootstrapadministrator. Der Beleg weist `no_jobs=true` aus.
Der Unitrunner begrenzt nach einem Timeout die Wartezeit auf das eigene
Testprozessende und auf beide Ausgabe-Tasks; eine verlorene Antwort erlaubt nur
den create-only gespeicherten Fall zu lesen. Das ist keine Änderung des
Produktjob- oder Installerabbruchs.
`local_service_proof`, `native_pipe_proof` und `clock_adapter_qualified` sind im
Native-PASS ausdrücklich weiterhin `false`. Dieser Unitlauf ist kein
Produkt-LocalService-zu-SYSTEM-Austausch, kein Nachweis, dass Drain v2 die zuvor
beobachtete233-Störung tatsächlich behebt, und keine SYSTEM-/Clock-/Jobfreigabe.
Der bestehende rohe V1-Control ist kein V2-Peernegativnachweis.
Der erhaltende Paarupgrade, die Bindung an den nach dem Konsolenneustart
vorhandenen tatsächlichen Prozesskontext und der anschließende reale
Agent/Helper-Austausch bleiben gesondert zu prüfen. Vor dessen Ausführung stehen
noch der unabhängige fokussierte Quellreview des neuen Upgrade-Runners und die
explizite Root-Zielaktion. Keine Paket-, SCM-Fixture-, Reboot- oder sonstige
RMM-Wirkung folgt aus dieser Unitabnahme.
+148
View File
@@ -0,0 +1,148 @@
# Windows Pipe-v2: erhaltender Paarupgrade nativ bestanden
Stand: 2026-11-14. Paarupgrade und tatsächlicher authentisierter Austausch des
laufenden LocalService-Agenten mit seinem SYSTEM-Helper sind bestanden.
Die ursprünglichen Vorbereitungsabschnitte unten bleiben Verlauf. RMM-Jobs,
TrustedClock und Helperwirkungen bleiben weiterhin gesperrt.
Die ursprüngliche quellengebundene
[Framingdokumentation](windows-helper-pipe-drain.md) bleibt unverändert. Diese
separate Datei beschreibt ausschließlich die späteren Upgradevorbereitungen.
Der Notebookhost bleibt reiner Entwicklungsrechner; Ziel ist die eigene
Windows-VM am endgültigen Cloudserver.
## Geprüfter Kandidat und begrenzter Bootstrapvertrag
Der neue Runner
[`system_pipe_upgrade.py`](../deploy/windows/system_pipe_upgrade.py) ist mit
SHA `e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0`
eingefroren. Sein frischer isolierter Prüfer bindet den neuen Pipe-Packtyp und
dessen Originalquellen, genaue native Listen mit **23 Library- und 7
Binarytests** sowie die erhaltenen Linux-first-Corebelege mit 80 Linux- und
58 Windowsfällen. Es gibt keine Umbenennung alter Delegationsmanifeste und
keine Umleitung des eigenen Source-Roots auf Main.
Der gebundene Pipe-Pack hat Manifest-SHA
`b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4`.
Die tatsächlichen 23+7 Windows-Administratorunits bestanden im Fall
`db25cd4a-bfd2-45d5-9f80-1881950853f7`; dessen `passed.json` hat SHA
`19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713`.
Das sind Unitnachweise, kein LocalService-/Pipe-/Clock-Erfolgsbeleg.
Die vorbereitete Mutation verlangt eine separat geprüfte frische Baseline mit
SCM-/Kernel-PID und tatsächlicher Prozessgeburt, Konto, aktivem Service-SID,
Imagehash und ACLs. Ein bereits gestoppter Manual-Helper erhält keinen
Vorabstart. Vor der ersten Ersetzung werden vier private Sicherungen erstellt;
jede Ersetzung verlangt zusätzlich einen eigenen zuvor fehlenden nativen
Backupnamen und frische Datei-ID-/Hash-/ACL-CAS-Prüfungen. Beide Dienste bleiben
bis zur vollständigen neuen EXE-/Policy-/Pingeneration gestoppt. Danach sind
Helper- und Agentstart jeweils create-once. Config-/CA-/Identitäts-/Zertifikats-
und Private-Key-Metadaten samt Datei-IDs werden auch nach den Ersetzungen,
vor dem Start und beim Finish unverändert verlangt.
`readback` ist rein lesend und kann auch einen fehlenden Zielpfad sowie einen
SCM-Pendingzustand ehrlich zeigen. Baseline, Enter und Finish behalten ihre
strengen Identitätsprüfungen. Nach verlorener Mutationsantwort gibt es keinen
automatischen Enter-/Start-/Rollbackretry. Ein Finish benötigt neue passive
Heartbeats und konkrete Inventar-ACKs; es schreibt nur einen lokalen Beleg.
Main-Indizes werden ausschließlich durch Root separat per CAS fortgeschrieben.
## Tatsächlicher Fall 14fb: Timeout und geprüfte erste Fortsetzung
Fallverzeichnis:
`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`.
Der erste `prepare`-Aufruf begann am `2026-11-14T12:39:48.414511+00:00`
und endete nach 180 Sekunden mit `TimeoutExpired` während des ersten
Stagingaufrufs. Zu diesem Zeitpunkt gab es lokal nur den Prepareintent und
Quellkopien, keine Baseline und keinen Enterintent. Die genaue Ursache des
SSH-/Bootstraptimeouts ist nicht nachgewiesen.
Ein danach gesondert ausgeführter lesender Check bestätigte: beide neuen
EXE-Stagingverzeichnisse, der neue entfernte Komponentenfall und der neue
Active-Marker waren noch nicht vorhanden. Der alte Agent lief, der alte Helper
war gestoppt. Auf dieser Abwesenheit beruhte die explizite create-once
Fortsetzung der tatsächlich noch unerreichten Vorbereitungsphase im selben
Fall; kein neuer Upgradefall und kein wiederholtes Enter.
| Erhaltener Beleg | SHA-256 |
| --- | --- |
| `prepare-first-stage-timeout.json` | `535faf7c6c4c7b3dba1f8d7b7889bc59acdee09fd51c2830fe397c3c9076f1e9` |
| `first-prepare-readonly-absence.json` | `983b38fcc2cdc8e907436eb3053f32ad2cd131e765a82dd1e9930346e1c6877b` |
| Private Fortsetzungsquelle `continue-first-prepare.py` | `86453aef4a1d59f73e423993b548e58ad0541205961a5952c80807403881cf3b` |
| `continue-first-prepare-intent.json` | `7420622b7866e7b43b34087d5334599444a046b95a89e7f48503aca0f4e03be0` |
| Neue lesende `baseline.json` | `57b79e9c918df6165cac0bb451b33fcd0c207933f15351afcd2ad6c400f4e2d7` |
Die Fortsetzung erzeugte schließlich den Baseline-/Intentbeleg und die
serverseitigen Vorherbeobachtungen. Das ursprüngliche Timeout und seine
Abwesenheitsmessung wurden nicht überschrieben.
## Baseline und verbleibende tatsächliche Abnahme
Die frische Baseline zeigt den weiterhin vorhandenen Agenten `89004ad3…`
unter LocalService (`S-1-5-19`), `Running/Auto`, PID `3172`, mit exakter
Kernel-FILETIME `134391328200102621`. Der vorhandene Helper `e6aacbdd…`
ist `Stopped/Manual`, PID `0`; dafür wird kein laufender Prozess behauptet.
Policy `007adf5f…` und Pin `126670bc…` gehören weiterhin zur alten Generation.
Die Telemetriedatenbank wurde lesend mit `integrity=ok`, Sequenz `2564` und
`pending_inventory_events=0` beobachtet. Ursprüngliche PKI-/DB-/Lock-Datei-IDs,
ACLs und die beiden uninitialisierten Nullbyte-Intentleaves sind im privaten
Baselinebeleg gebunden.
Vorherige Serverzählungen blieben:
Windows `jobs/outbox/permits/unresolved = 0/0/0/0`, Linux
`30/30/26/0`. Die beobachteten API-/Gateway-Transportfaultflags waren geschlossen;
dies ist eine konkrete Vorhermessung, kein künftiger Nachherbeleg.
Der vorbereitete Kandidat umfasst Agent `f10c78dd…`, Helper `5f8c62fa…`,
Policy `a3024467…` und Pin `af518db8…`. **Es existiert für diesen Fall noch kein
Enterintent oder tatsächlicher Stop-/Swap-/Start-/Finishbeleg.** Staging ist
keine Installation oder laufende Nutzung der neuen EXEs. Der alte SSH-Zugang
lief anschließend aus; seine getrennte
[Konsolenwiederherstellung](windows-dev-access-recovery.md) ist eine notwendige
Zugangsstrecke und kein Paarupgrade.
Nach tatsächlicher Wiederherstellung des Zugangs muss Root die Baseline vor
Mutation erneut bewerten. Geänderte PID/Birth-, Datei-, Index- oder andere
gebundene Werte dürfen nicht still übernommen werden. Erst danach können der
einmalige erhaltende Paarupgrade, zwei neue tatsächliche WSS-Heartbeats,
Inventar-ACK, Tenantverweigerung und unveränderte Job-/Policygrenzen geprüft
werden. Ein tatsächlicher authentisierter Austausch des laufenden
LocalService-Agenten mit dem neuen SYSTEM-Helper bleibt offen. Jobfreigabe,
Helperwirkungen und Clockqualifikation bleiben geschlossen.
## Tatsächlicher Abschluss im selben Fall
Nach der getrennt verifizierten SSH-Zugangswiederherstellung wurde derselbe
Fall14fb genau einmal betreten. Die frische CAS-Prüfung bestätigte vor der
Mutation die unveränderte ursprüngliche Baseline, beide lokalen Runtimeindizes
und die geschlossenen Serverzähler/Policies. Der bereits gestoppte Helper
wurde nicht vorab gestartet. Beide Dienste blieben während aller vier
Dateiersetzungen gestoppt; Originale und native Backups sind erhalten.
Das anschließende rein lesende Finish bestätigt:
- Agent `f10c78dd738e7fb277e0c4d24fadf0f61ae3269458399b9224570ba5e66abc2c`
läuft als LocalService/Auto, PID5528, Geburt `134391415551175930`.
- Helper `5f8c62fab6bc8ea1bbb009166b3d0e741c034c36690a4e32ea4e3cb2d7729a79`
läuft als SYSTEM/Manual, PID9464, Geburt `134391415512591188`.
- Tatsächliche Agentprobe: `authenticated_pipe_exchange=true` und
`client_service_pid_verified_by_helper=true`; Helperkonto/Service-SID und
feste EXE-/Policybindungen geprüft. Der frühere Win32233-Lauf bleibt
fehlgeschlagen; daraus wird keine rückwirkend bewiesene Fehlerursache.
- Zwei neue WSS-Heartbeats, ursprüngliche mTLS-Geräteidentität,
Inventar-ACK/Sequenz2813 und Tenantverweigerung bestätigt. Agent-/Helper-
DB-/Lock-/PKI-Datei-IDs, Historie und leere Intentleaves erhalten.
- Windows0/0/0/0, Linux30/30/26/0, geschlossene Testflags/Policies,
`helper_ready=false`, `helper_clock_qualified=false`, keine SYSTEMcapability
und keine Jobs oder Wirkung. Private Schlüssel wurden nicht gelesen.
Originaler `result.json`-SHA256:
`d5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed`.
Er wurde samt Intent/Baseline bytegleich im privaten Main-Evidenzpfad
archiviert. Erst danach veröffentlichte Root lokal beide Indizes per CAS unter
einem gemeinsamen Lock, mit erhaltenen Vorgängerdateien und eigener
Publikationsreceipt. Keine erneute Zielmutation:
Runtimeindex `e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2`,
Komponentenindex `005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562`.
Der Nachweis qualifiziert den Pipe-v2-Peertransport und die passive Erhaltung,
keine Clock, SYSTEM-Skriptkonsole oder Paketwirkung.
+75
View File
@@ -0,0 +1,75 @@
# Einmaliger Start des vorhandenen Windows-Zeitdiensts
Stand 2026-11-14: [Bootstrapquelle](../deploy/windows/time_service_start.py)
implementiert, unabhängig quellgeprüft, Python-Syntax und PowerShell-AST lokal
bestanden. **Einmaliger nativer Start und separater Readback bestanden.**
Der Nutzer hat den Start des vorhandenen
W32Time ausdrücklich erlaubt. Die Ausführung übernimmt der Root-Orchestrator
nach Quellenprüfung auf der Windows-VM; das Notebook bleibt Entwicklungsrechner.
Der einzige Dienstbefehl ist `Start-Service -Name W32Time`. Startart,
Dienstkonto, Imagepfad, Dienst-SDDL, SID-Typ, NTP-Konfiguration und Richtlinien
werden nicht geschrieben. Für einen gestoppten Dienst müssen außerdem null
Dienstabhängigkeiten vorliegen; sonst erfolgt kein Start. Pending-/unbekannte
Zustände blockieren. Ein bereits laufender Dienst wird nur als
`already_running` dokumentiert. Es gibt keinen Resyncbefehl, kein Policyupdate,
keinen RMM-Job und keinen Reboot. Ein natürlicher Zeitsync durch den gestarteten
Dienst ist erlaubt, aber **kein Nachweis einer qualifizierten Uhr**.
`prepare` verlangt die fünf unabhängig bekannten SHA256-Werte für Agent,
Helper, Agentkonfiguration, Helperkonfiguration und Agentpin. Es legt einen
privaten lokalen Fall an, bindet den bereits gespeicherten zentralen
Beforekontext `time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973`,
überträgt ausschließlich die feste, hashgeprüfte Bootstrapquelle und liest
den tatsächlichen Ausgangszustand. Der Start verwendet diese Originalpins und
diesen Fall unverändert. RMM-PIDs, Prozessentstehung, Dienstdefinitionen,
Binaryhashes sowie Konfigurations-/PKI-Metadaten müssen erhalten bleiben.
Der private Geräteschlüssel wird nur über Dateimetadaten und ACL-Hash geprüft;
seine Bytes werden nicht gelesen oder exportiert.
Die Registryprüfung hasht nur ausdrücklich aufgeführte stabile Dienst-, NTP-
und Policy-Konfigurationswerte. Sie gibt keine Rohwerte/NTP-Hostnamen aus.
Volatile LastSync-/Laufzeitwerte werden nicht als unveränderlich vorausgesetzt;
der Hash behauptet keine vollständige Abdeckung sämtlicher Registrywerte.
W32Time-Status und dessen PID dürfen sich durch den erlaubten Start ändern.
Vor dem einzigen Startaufruf werden ein privater Originalbeleg und zwei
dauerhafte, ausschließlich neu anlegbare Startreservierungen gespeichert:
im Fallverzeichnis und als globaler W32Time-Einmalbeleg. Auch lokal entsteht
vor dem SSH-Aufruf ein ausschließlich neu anlegbarer Startversuchsbeleg.
Eine verlorene Antwort, ein Fehler oder ein unvollständiger Beleg erlaubt nur
`readback --id ORIGINALFALL`; weder Startwiederholung noch automatischer
Rollback sind implementiert. Readback meldet den tatsächlichen aktuellen
Zustand und bewahrt unbestätigte Ergebnisse als solche. Frühere private
SSH-Fehler werden vor/nach Aufrufen versioniert erhalten.
Die folgenden Befehle sind **Aufrufvorlagen**; die Hashplatzhalter
müssen aus dem unabhängig bekannten aktuellen Deployment stammen:
```text
python3 deploy/windows/time_service_start.py prepare --agent-sha256 HASH --helper-sha256 HASH --config-sha256 HASH --policy-sha256 HASH --pin-sha256 HASH
python3 deploy/windows/time_service_start.py start --id ORIGINALFALL
python3 deploy/windows/time_service_start.py readback --id ORIGINALFALL
```
Vollständige Metadaten bleiben in geschützten lokalen/VM-Fallbelegen. Die CLI
gibt nur Fallkennung, Status, Running-/Erhaltungs-/Readback-Merkmale und den
ausdrücklich nicht geprüften Uhrvertrauensstatus aus. Lokaler Quellnachweis:
`devstate/windows-client/time-service-start-source/225c3208-4a3f-4528-8c17-b3846b70812f/qualification.json`;
PowerShell nur geparst, kein Windows-API-/VM-Aufruf und keine Produkttestsuite.
## Tatsächliche Ausführung
Fall `c3552c3f-24d1-4713-bd0b-544aee4ffd18` auf dem Windowsgast:
Vorbereitung bestätigte Stopped und die bekannten Originalhashes. Anschließend
genau ein `Start-Service W32Time`, Status Running, Erhaltungsprüfung bestanden.
Getrennter späterer Readback bestätigte denselben Originalresultbeleg und
Running ohne Startwiederholung. Agent5140 und Helper6240 unverändert;
Dienstdefinition/SDDL und ausgewählte NTP-/Policy-Konfigurationswerte erhalten.
Kein privater Schlüsselinhalt gelesen und keine Konfiguration geschrieben.
Zentraler Kontrollstand vorher/nachher identisch: Windows0Jobs/0Outbox/0Grants/
0ungeklärt, Linux30/30/26/0; Rootpolicyhash und geschlossene Transporthooks
unverändert. Geschützter Abschlussbeleg `acceptance.json` im Originalfall,
SHA256 `365d897d94f6fb16b3112fcb5126bdc09224b34e0a6ef46940ca8e7a651807fb`.
Quellhash `ef5d4ce8…`. **Kein Uhrqualifikations-, RMM-Job- oder Rebootbeleg.**
-18
View File
@@ -65,24 +65,6 @@ describe('JSON contract boundary', () => {
expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service');
validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } });
});
it('bounds the fixed Event Log source and exact 24h interval without rewriting Linux queries', () => {
const base: PlanInput = { tenant_id: 't', action: 'query_logs', targets: { asset_ids: ['a'] }, parameters: { execution_identity: 'agent_service', unit: 'windows.eventlog.application.rustdiscovery-mvp-test', since: '2026-11-14T00:00:00Z', until: '2026-11-15T00:00:00Z', max_lines: 1000, timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now()+60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed fixture logs' };
const before = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(before);
for (const change of [{ execution_identity: 'root' }, { execution_identity: 'system' }, { unit: 'windows.eventlog.security.other' }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { max_lines: 1001 }, { until: '2026-11-15T00:00:00.000000001Z' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, ...change } })).toThrow();
const linux = { ...base, parameters: { ...base.parameters, unit: 'rmm-test.service', execution_identity: 'root', timeout_seconds: 1, max_output_bytes: 512 } }; const original=JSON.stringify(linux); validateInput(linux); expect(JSON.stringify(linux)).toBe(original);
expect(() => validateInput({ ...linux, parameters: { ...linux.parameters, until: '2026-11-15T00:59:00Z' } })).toThrow('24Stunden');
});
it('accepts only the fixed Windows process profile without changing inherited variants', () => {
const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'fixed'\r\n" };
const base: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a'] }, parameters: { variants: [windows], execution_identity: 'agent_service', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed profile fixture' };
const original = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(original);
const profiled = { ...windows, windows_execution_profile: 'powershell_51_remote_signed' };
validateInput({ ...base, parameters: { ...base.parameters, variants: [profiled] } });
expect(() => validateInput({ ...base, parameters: { ...base.parameters, windows_execution_profile: 'powershell_51_remote_signed' } })).toThrow('Skriptvariante');
for (const windows_execution_profile of ['Bypass', 'Unrestricted', 'RemoteSigned', 'inherited', null, {}]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [{ ...windows, windows_execution_profile }] } })).toThrow('Windows-Ausführungsprofil');
for (const variant of [{ ...profiled, os_family: 'linux' }, { ...profiled, interpreter: 'bash' }, { ...profiled, interpreter: 'pwsh' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [variant] } })).toThrow();
for (const execution_identity of ['root', 'system']) expect(() => validateInput({ ...base, parameters: { ...base.parameters, execution_identity, variants: [profiled] } })).toThrow('agent_service');
});
it('allows SYSTEM only for exact bounded fixture SCM parameters without changing Linux restart', () => {
const input: PlanInput = { tenant_id: 't', action: 'set_service_state', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', unit: 'RmmDiscoveryFixtureService', state: 'running', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed SCM plan' };
const before = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(before);
+1 -37
View File
@@ -59,35 +59,6 @@ export const pretty = (v: unknown) => JSON.stringify(v, null, 2);
export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const;
export type Action = typeof actions[number];
export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const;
/** A missing field is inherited policy; a present field is never silently coerced. */
export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof windowsPowerShellRemoteSignedProfile {
if (!Object.prototype.hasOwnProperty.call(value, 'windows_execution_profile')) return 'inherited';
if (value.windows_execution_profile !== windowsPowerShellRemoteSignedProfile || value.interpreter !== 'powershell'
|| (value.os_family !== undefined && value.os_family !== 'windows')) throw new Error('Windows-Ausführungsprofil nur powershell_51_remote_signed für Windows PowerShell5.1');
return windowsPowerShellRemoteSignedProfile;
}
export const windowsEventLogFixtureSource = 'windows.eventlog.application.rustdiscovery-mvp-test';
export const windowsEventLogFixtureChannel = 'Application';
export const windowsEventLogFixtureProvider = 'RustDiscovery-MVP-Test';
/** Preserve sub-millisecond bounds; Date.parse alone would admit 24h + 1ns. */
export function logWindow(since: unknown, until: unknown): void {
const instant = (value: unknown): bigint => {
if (typeof value !== 'string') throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
const match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?(Z|[+-]\d\d:\d\d)$/.exec(value);
if (!match) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
const seconds = Date.parse(match[1]! + match[3]!);
if (!Number.isFinite(seconds)) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
return BigInt(seconds) * 1000000n + BigInt((match[2] ?? '').padEnd(9, '0'));
};
const start = instant(since), end = instant(until);
if (end <= start || end - start > 86400000000000n) throw new Error('Exaktes Log-Zeitfenster höchstens24Stunden erforderlich');
}
export function validateWindowsLogLimits(identity: unknown, runtime: unknown, output: unknown, since: unknown): void {
if (identity !== 'agent_service' || typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 10 || runtime > 120
|| typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1024 || output > 65536
|| typeof since !== 'string' || Date.parse(since) < 0) throw new Error('Windows-Fixture-Eventlog nur agent_service,10–120s und1024–65536Bytes');
}
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
export function expectedStdout(value: string, format: string): string | null {
@@ -97,7 +68,6 @@ export function expectedStdout(value: string, format: string): string | null {
return output;
}
export function validateInput(input: PlanInput): void {
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss an der festen Windows-Skriptvariante stehen');
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
if (!input.reason.trim()) throw new Error('Begründung erforderlich');
const start = Date.parse(input.schedule.not_before), end = Date.parse(input.schedule.start_before);
@@ -107,7 +77,6 @@ export function validateInput(input: PlanInput): void {
const variants = input.parameters.variants;
if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => {
const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : '';
windowsScriptProfile(variant);
const bytes = new TextEncoder().encode(script).length;
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
@@ -124,12 +93,7 @@ export function validateInput(input: PlanInput): void {
}
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
if (input.action === 'refresh_inventory') required('scope');
if (input.action === 'query_logs') {
const unit = required('unit'); logWindow(required('since'), required('until'));
if (unit.startsWith('windows.eventlog.') && unit !== windowsEventLogFixtureSource) throw new Error('Nur die feste Windows-Fixture-Eventlogquelle ist konfiguriert');
if (unit === windowsEventLogFixtureSource) validateWindowsLogLimits(input.parameters.execution_identity, input.parameters.timeout_seconds, input.parameters.max_output_bytes, input.parameters.since);
if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein');
}
if (input.action === 'query_logs') { required('unit'); const since = Date.parse(required('since')), until = Date.parse(required('until')); if (!Number.isFinite(since) || !Number.isFinite(until) || until <= since) throw new Error('Exaktes Log-Zeitfenster erforderlich'); if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein'); }
if (input.action === 'set_service_state') { required('unit'); if (!['running', 'stopped', 'restarted'].includes(required('state'))) throw new Error('Ungültiger Dienstzustand'); }
if (input.action === 'ensure_package') { for (const key of ['provider', 'recipe_version', 'package', 'version', 'architecture', 'installation_context']) required(key); }
if (input.action === 'apply_updates') { required('provider'); if (!Array.isArray(input.parameters.packages) || !input.parameters.packages.length || !input.parameters.packages.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Feste Updatepakete erforderlich'); if (input.parameters.reboot_policy !== 'never') throw new Error('Kein impliziter Reboot; eigenen festen Plan erstellen'); }
-30
View File
@@ -1,39 +1,9 @@
import { expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { sha256, verifyPlanIntegrity } from './safety';
// Import the actual renderer without mounting the application's network effects.
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
it('shows fixed Event Log source, half-open UTC window and both runtime bounds before approval', async () => {
const fetch=vi.fn();vi.stubGlobal('fetch',fetch);vi.stubGlobal('document',{getElementById:()=>({})});
try{
const {QueryLogsPlanNotice}=await import('./main');
const payload={jobs:[{payload:{asset_id:'win-fixture',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-14T01:00:00Z',max_lines:1000}}}]};
const raw=new TextEncoder().encode(JSON.stringify(payload)),plan={plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),plan_payload:payload};
expect(renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>)).toContain('role="alert"');await verifyPlanIntegrity(plan);
const html=renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>);for(const expected of ['Application','RustDiscovery-MVP-Test','1000','4096','30s','5000ms','kooperativ','2026-11-14T01:00:00Z)','Keine Bookmark'])expect(html).toContain(expected);
expect(html).not.toMatch(/<(button|input|form)\b/);expect(fetch).not.toHaveBeenCalled();
}finally{vi.unstubAllGlobals();}
});
it('shows the verified PowerShell process profile before approval without issuing requests', async () => {
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
try {
const { PowerShellPlanNotice } = await import('./main');
const payload = { jobs: [{ payload: { asset_id: 'fixed-windows', execution_identity: 'agent_service', action: { action: 'run_script', interpreter: 'powershell', script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', windows_execution_profile: 'powershell_51_remote_signed' } } }] };
const raw = new TextEncoder().encode(JSON.stringify(payload)), plan = { plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), plan_payload: payload };
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
await verifyPlanIntegrity(plan);
const html = renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>);
for (const expected of ['fixed-windows', 'Windows PowerShell5.1', 'RemoteSigned', 'nur Jobprozess', 'angeforderte Option']) expect(html).toContain(expected);
expect(html).not.toMatch(/<(button|input|form)\b/);
plan.plan_payload_bytes[0] = 0;
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
expect(fetch).not.toHaveBeenCalled();
} finally { vi.unstubAllGlobals(); }
});
it('renders hostile log content only as text, without executable nodes, approval controls or requests', async () => {
const fetch = vi.fn();
vi.stubGlobal('fetch', fetch);
+6 -23
View File
@@ -1,9 +1,9 @@
import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile } from './api';
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
import './style.css';
import { AdminControl, Catalog, TenantControls } from './management';
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs } from './safety';
import { allowed, availableActions, parseStrictJson, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety';
import { Login } from './login';
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
@@ -15,20 +15,6 @@ export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
if (!jobs.length) return null;
return <aside className="warning" aria-label="Feste SYSTEM-Dienstaktionen"><p>{systemWarning}</p><ul>{jobs.map((payload, i) => { const action = record(payload.action); return <li key={i}>Identität: system · Asset: {String(payload.asset_id)} · Dienst: {String(action.unit)} · Zielzustand: {String(action.state)}</li>; })}</ul><p>Diese Definitionen stammen aus den gespeicherten Planbytes; die vollständigen Zielpayloads und Hashes stehen darunter.</p></aside>;
}
export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = powerShellPlanJobs(plan);
if (!jobs.length) return null;
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · agent_service · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
} catch { return <aside role="alert" className="error">PowerShell-Planprofil ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
}
export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = queryLogsPlanJobs(plan);
if (!jobs.length) return null;
return <aside className="warning" aria-label="Feste Live-Logfenster"><p>UI-genehmigte Liveabfrage aus hashgeprüften gespeicherten Planbytes; kein passives Inventar, keine automatische Erhebung.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Quelle: {job.source}{job.windows ? <> · Kanal: {job.channel} · Provider: {job.provider} · agent_service</> : ' · Linux-Journal'} · UTC-Fenster: [{job.since}, {job.until}) · maximal {job.maxLines} {job.windows ? 'Events' : 'Zeilen'} · {job.outputBytes} Bytes · äußere Joblaufzeit {job.runtimeSeconds}s{job.windows && ' · inneres Abfragebudget höchstens5000ms, zwischen Win32-Aufrufen kooperativ geprüft'}</li>)}</ul><p>Grenzen, Abbruch, fehlende Rechte und Teilabdeckung bleiben sichtbar. Keine Bookmarkfortschreibung durch diesen Auftrag; die Abfrage behauptet keine vollständige Sammlung aller Systemlogs.</p></aside>;
} catch { return <aside role="alert" className="error">Logfenster ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
}
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
@@ -64,15 +50,14 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')), ...(scriptPlatform === 'windows' ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } : {}) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
{action === 'query_logs' && <p>Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.</p>}
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive. Einzelne neue Windowspläne binden fest RemoteSigned nur für den Jobprozess. Bei gemischten Varianten ist powershell_51_remote_signed ausdrücklich an der Windowsvariante zu setzen; fehlendes Profil bleibt geerbt. Jede tatsächliche Prozessoption steht vor Genehmigung je Ziel im festen Plan. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive; keine ExecutionPolicy-Umgehung. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
{identity === 'root' && <p className="warning">{rootWarning}</p>}
{identity === 'system' && <p className="warning">{systemWarning}</p>}
@@ -87,17 +72,15 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); return result; }, [tenantId, id]);
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [confirmed, setConfirmed] = useState(false), [submitted, setSubmitted] = useState(false), [pending, setPending] = useState(false);
const [idempotency] = useState(() => crypto.randomUUID());
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
const blockers = plan.data ? approvalBlockers(plan.data) : ['Plan noch nicht geladen'];
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
<SystemPlanNotice plan={plan.data}/>
<PowerShellPlanNotice plan={plan.data}/>
<QueryLogsPlanNotice plan={plan.data}/>
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews, Ausführungsprofile/Prozessumfänge und Auswirkungen dieses Plans geprüft.</label>
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews und Auswirkungen dieses Plans geprüft.</label>
<button className="danger" disabled={!confirmed || busy || !!plan.error || blockers.length > 0 || !(pending || plan.data.approval_state === 'pending_approval')} onClick={async () => { setBusy(true); setError(null); try {
const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen' : 'Diesen festen Plan ausdrücklich genehmigen'}</button>
+1 -54
View File
@@ -1,63 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { actions, PlanInput, Session, request, session } from './api';
import { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
import { adminIntent, allowed, availableActions, parseStrictJson, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
import { AdminControl } from './management';
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
describe('immutable PowerShell process profile', () => {
async function plan(profile: unknown = 'powershell_51_remote_signed', identity = 'agent_service', interpreter = 'powershell') {
const action = { action: 'run_script', interpreter, script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', ...(profile === undefined ? {} : { windows_execution_profile: profile }) };
const payload = { asset_id: 'fixed-windows', execution_identity: identity, action }, jobs = [{ asset_id: 'fixed-windows', job_payload_hash: 'a'.repeat(64), payload }];
const plan_payload = { jobs }, raw = new TextEncoder().encode(JSON.stringify(plan_payload));
return { plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs };
}
it('requires verified bytes, rejects all profile/view mutations and preserves inherited plans', async () => {
const value = await plan(); expect(() => powerShellPlanJobs(value)).toThrow('nicht aus hashgeprüften');
await verifyPlanIntegrity(value); expect(powerShellPlanJobs(value)).toEqual([{ assetId: 'fixed-windows', profile: 'powershell_51_remote_signed' }]);
expect(powerShellApprovalBlockers(value)).toEqual([]);
const changed = structuredClone(value); changed.jobs[0]!.payload.action.windows_execution_profile = 'Bypass';
await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
const viewOnly = { ...value, jobs: [{ ...value.jobs[0]!, payload: { ...value.jobs[0]!.payload, action: { ...value.jobs[0]!.payload.action, windows_execution_profile: 'Bypass' } } }] };
await expect(verifyPlanIntegrity(viewOnly)).rejects.toThrow('widerspricht');
const extraAlias = { ...value, resolved_targets: value.jobs, jobs: viewOnly.jobs };
await expect(verifyPlanIntegrity(extraAlias)).rejects.toThrow('widerspricht');
await expect(verifyPlanIntegrity({ ...value, payloads: viewOnly.jobs })).rejects.toThrow('widerspricht');
await expect(verifyPlanIntegrity({ ...value, payload: { jobs: viewOnly.jobs } })).rejects.toThrow('widerspricht');
const idsOnly = { ...value, resolved_targets: ['fixed-windows'] }; await verifyPlanIntegrity(idsOnly);
for (const alias of ['plan_payload', 'payload']) {
const later: Record<string, unknown> = { ...value, [alias]: value.plan_payload };
await verifyPlanIntegrity(later); later[alias] = { jobs: viewOnly.jobs };
expect(powerShellApprovalBlockers(later).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(later)).toThrow('widerspricht');
}
await expect(verifyPlanIntegrity({ ...value, plan_payload_bytes: undefined })).rejects.toThrow('gespeicherte Planbytes');
for (const profile of ['Bypass', null, {}, 'powershell_7_remote_signed']) await expect(verifyPlanIntegrity(await plan(profile))).rejects.toThrow('Windows-Ausführungsprofil');
for (const identity of ['root', 'system']) await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', identity))).rejects.toThrow('agent_service');
await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', 'agent_service', 'bash'))).rejects.toThrow();
const inherited = await plan(undefined); delete inherited.plan_payload.jobs[0]!.payload.action.windows_execution_profile;
const raw = new TextEncoder().encode(JSON.stringify(inherited.plan_payload)); inherited.plan_payload_bytes = Array.from(raw); inherited.plan_hash = await sha256(raw);
await verifyPlanIntegrity(inherited); expect(powerShellPlanJobs(inherited)[0]?.profile).toBe('inherited');
value.plan_payload_bytes[0] = 0; expect(powerShellApprovalBlockers(value).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(value)).toThrow('verändert');
});
});
describe('immutable live log window', () => {
it('binds source/window/limits and every supplied view to stored bytes, preserving Linux and SYSTEM plans', async () => {
const payload={asset_id:'windows-a',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-15T00:00:00Z',max_lines:1000}};
const plan_payload={jobs:[{payload}]},raw=new TextEncoder().encode(JSON.stringify(plan_payload));
const plan={plan_payload,plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),jobs:plan_payload.jobs,resolved_targets:['windows-a']};
expect(()=>queryLogsPlanJobs(plan)).toThrow();await verifyPlanIntegrity(plan);
expect(queryLogsApprovalBlockers(plan)).toEqual([]);expect(queryLogsPlanJobs(plan)[0]).toMatchObject({source:payload.action.unit,channel:'Application',provider:'RustDiscovery-MVP-Test',maxLines:1000,outputBytes:4096,runtimeSeconds:30});
await expect(verifyPlanIntegrity({...plan,plan_payload_bytes:undefined})).rejects.toThrow('gespeicherte');
for(const action of [{...payload.action,max_lines:999},{...payload.action,until:'2026-11-14T23:59:59Z'}]){
const bad={...plan,payloads:[{payload:{...payload,action}}]};await expect(verifyPlanIntegrity(bad)).rejects.toThrow('widerspricht');
}
const changed={...plan,jobs:[{payload:{...payload,max_output_bytes:2048}}]};await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
const cached={...plan};await verifyPlanIntegrity(cached);cached.jobs=[{payload:{...payload,max_runtime_seconds:31}}];expect(queryLogsApprovalBlockers(cached).length).toBeGreaterThan(0);
for(const execution_identity of ['root','system']){const p={jobs:[{payload:{...payload,execution_identity}}]};const b=new TextEncoder().encode(JSON.stringify(p));await expect(verifyPlanIntegrity({plan_payload_bytes:Array.from(b),plan_hash:await sha256(b)})).rejects.toThrow('agent_service');}
const linux={jobs:[{payload:{...payload,execution_identity:'root',action:{...payload.action,unit:'rmm-test.service'}}}]};const linuxBytes=new TextEncoder().encode(JSON.stringify(linux));const linuxPlan={plan_payload_bytes:Array.from(linuxBytes),plan_hash:await sha256(linuxBytes)};await verifyPlanIntegrity(linuxPlan);expect(queryLogsPlanJobs(linuxPlan)[0]?.windows).toBe(false);
const system={jobs:[{payload:{...payload,execution_identity:'system',action:{action:'set_service_state',unit:'RmmDiscoveryFixtureService',state:'running'}}}]};const systemBytes=new TextEncoder().encode(JSON.stringify(system));const systemPlan={plan_payload_bytes:Array.from(systemBytes),plan_hash:await sha256(systemBytes)};await verifyPlanIntegrity(systemPlan);expect(queryLogsPlanJobs(systemPlan)).toEqual([]);
});
});
async function manifest(acceptance = true) {
const transaction = { schema_version: 1, recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', platform: 'ubuntu-24.04-amd64', resolver_config_version: 'rmm-apt-local-v1', no_reboot: true, status_fingerprint: 'a'.repeat(64), baseline_sha256: 'b'.repeat(64), packages: [{ name: 'rmm-mvp-test', architecture: 'all', old_version: null, new_version: '1.0', origin: 'rmm-test', sha256: '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', size: 20672, archive_path: '/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb' }] };
const raw = new TextEncoder().encode(JSON.stringify(transaction));
+2 -138
View File
@@ -1,4 +1,4 @@
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider } from './api';
import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
export const hashPattern = /^[0-9a-f]{64}$/;
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
@@ -101,133 +101,7 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
if (!Array.isArray(parsed.jobs)) return [];
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
}
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
// Only successful verification writes this cache. Projection is copied from the
// verified bytes; later mutations of API views cannot change the displayed plan.
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly logJobs: readonly QueryLogsPlanJob[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
const verifiedPowerShellPlans = new WeakMap<RecordValue, VerifiedPowerShellPlan>();
export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJob[] {
const verified = verifiedPowerShellPlans.get(plan);
if (!verified) throw new Error('PowerShell-Plan wurde nicht aus hashgeprüften gespeicherten Bytes verifiziert');
if (verified.planBytes.length) {
const current = bytes(plan.plan_payload_bytes);
if (plan.plan_hash !== verified.planHash || current.length !== verified.planBytes.length || verified.planBytes.some((value, i) => current[i] !== value)) throw new Error('PowerShell-Planbytes wurden nach Verifikation verändert');
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(current)));
validatePlanAliases(plan, parsed);
validatePowerShellViews(plan, parsed.jobs);
validateQueryLogsViews(plan, parsed.jobs);
} else if (scriptPayloads(planTargetPreviews(plan)).some(hasPowerShellProfile)) {
throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
}
return verified.jobs.map(job => ({ ...job }));
}
export function powerShellApprovalBlockers(plan: RecordValue): string[] {
try { powerShellPlanJobs(plan); return []; }
catch (error) { return [error instanceof Error ? error.message : 'PowerShell-Profil ist nicht verifiziert']; }
}
function scriptPayloads(jobs: unknown): RecordValue[] {
if (!Array.isArray(jobs)) return [];
return jobs.flatMap(job => {
if (!job || typeof job !== 'object') return [];
const payload = record(job).payload;
return payload && typeof payload === 'object' ? [record(payload)] : [];
});
}
function hasPowerShellProfile(payload: RecordValue): boolean {
if (Object.prototype.hasOwnProperty.call(payload, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss Teil der festen Skriptaktion sein');
const action = payload.action;
return action !== null && typeof action === 'object' && (record(action).interpreter === 'powershell'
|| Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile'));
}
function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
return scriptPayloads(jobs).filter(hasPowerShellProfile).map(payload => {
const action = record(payload.action);
if (action.action !== 'run_script' || action.interpreter !== 'powershell' || payload.execution_identity !== 'agent_service') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service');
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : [])]);
if (typeof action.script_utf8 !== 'string' || !action.script_utf8 || new TextEncoder().encode(action.script_utf8).length > 32768 || action.script_utf8.includes('\0')
|| (!/^[\x00-\x7f]*$/.test(action.script_utf8) && !action.script_utf8.startsWith('\ufeff'))
|| !Array.isArray(action.arguments) || action.arguments.length > 32 || action.arguments.some(arg => typeof arg !== 'string' || new TextEncoder().encode(arg).length > 4096 || arg.includes('\0'))
|| !(action.expected_stdout === null || (typeof action.expected_stdout === 'string' && new TextEncoder().encode(action.expected_stdout).length <= 65536))) throw new Error('Vollständige unveränderte PowerShell-Skriptaktion erforderlich');
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action) };
});
}
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(parsed) !== canonical(plan[alias])) throw new Error('Planansicht widerspricht gespeicherten Bytes');
}
function validateFixedViews(plan: RecordValue, rawJobs: unknown, selected: (payload: RecordValue) => boolean, label: string, fields = ['action', 'execution_identity']): void {
const rawPayloads = scriptPayloads(rawJobs), views = [planTargetPreviews(plan)];
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
if (plan[alias] !== undefined && !Array.isArray(plan[alias])) throw new Error(`${label}-Zielpreview ist keine vollständige Liste`);
if (Array.isArray(plan[alias])) views.push(plan[alias]);
}
for (const collection of new Set(views)) if (collection !== null) {
if (!collection.some(value => value !== null && typeof value === 'object' && !Array.isArray(value) && 'payload' in value)) continue;
const viewPayloads = scriptPayloads(collection);
for (const fixed of rawPayloads.filter(selected)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error(`${label}-Zielpreview fehlt im festen Plan`);
for (const view of viewPayloads) {
const raw = rawPayloads.find(payload => payload.asset_id === view.asset_id);
if ((selected(view) || (raw && selected(raw))) && (!raw || fields.some(field => canonical(raw[field]) !== canonical(view[field])))) throw new Error(`${label}-Zielpreview widerspricht gespeicherten Planbytes`);
}
}
}
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): void {
validateFixedViews(plan, rawJobs, hasPowerShellProfile, 'PowerShell');
}
function isQueryLogs(payload: RecordValue): boolean {
return payload.action !== null && typeof payload.action === 'object' && record(payload.action).action === 'query_logs';
}
function validateQueryLogsViews(plan: RecordValue, rawJobs: unknown): void {
validateFixedViews(plan, rawJobs, isQueryLogs, 'Log', ['action', 'execution_identity', 'max_runtime_seconds', 'max_output_bytes']);
}
export interface QueryLogsPlanJob {
readonly assetId: string; readonly source: string; readonly since: string; readonly until: string;
readonly maxLines: number; readonly runtimeSeconds: number; readonly outputBytes: number; readonly windows: boolean;
readonly channel: string | null; readonly provider: string | null;
}
function projectQueryLogsJobs(jobs: unknown): QueryLogsPlanJob[] {
return scriptPayloads(jobs).filter(isQueryLogs).map(payload => {
const action = record(payload.action);
exact(action, ['action', 'unit', 'since', 'until', 'max_lines']);
const source = text(action.unit, 'Logquelle'), since = text(action.since, 'since'), until = text(action.until, 'until');
logWindow(since, until);
if (typeof action.max_lines !== 'number' || !Number.isSafeInteger(action.max_lines) || action.max_lines < 1 || action.max_lines > 1000
|| typeof payload.max_runtime_seconds !== 'number' || !Number.isSafeInteger(payload.max_runtime_seconds) || payload.max_runtime_seconds < 1 || payload.max_runtime_seconds > 3600
|| typeof payload.max_output_bytes !== 'number' || !Number.isSafeInteger(payload.max_output_bytes) || payload.max_output_bytes < 1 || payload.max_output_bytes > 262144) throw new Error('Vollständige feste Loglimits erforderlich');
const windows = source === windowsEventLogFixtureSource;
if (source.startsWith('windows.eventlog.') && !windows) throw new Error('Unbekannte Windows-Eventlogquelle');
if (windows) validateWindowsLogLimits(payload.execution_identity, payload.max_runtime_seconds, payload.max_output_bytes, since);
else if (!['agent_service', 'root'].includes(String(payload.execution_identity))) throw new Error('Unbekannte Log-Ausführungsidentität');
return { assetId: text(payload.asset_id, 'Log-Zielasset'), source, since, until, maxLines: action.max_lines,
runtimeSeconds: payload.max_runtime_seconds, outputBytes: payload.max_output_bytes, windows,
channel: windows ? windowsEventLogFixtureChannel : null, provider: windows ? windowsEventLogFixtureProvider : null };
});
}
export function queryLogsPlanJobs(plan: RecordValue): readonly QueryLogsPlanJob[] {
// Reuse the same verified-object/immutable-byte gate as the PowerShell view.
powerShellPlanJobs(plan);
const verified = verifiedPowerShellPlans.get(plan)!;
if (!verified.planBytes.length && ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
return verified.logJobs.map(job => ({ ...job }));
}
export function queryLogsApprovalBlockers(plan: RecordValue): string[] {
try { queryLogsPlanJobs(plan); return []; }
catch (error) { return [error instanceof Error ? error.message : 'Logplan ist nicht verifiziert']; }
}
export async function verifyPlanIntegrity(plan: RecordValue) {
verifiedPowerShellPlans.delete(plan);
const views = planTargetPreviews(plan), hasScriptView = scriptPayloads(views).some(hasPowerShellProfile)
|| scriptPayloads(plan.jobs).some(hasPowerShellProfile) || scriptPayloads(plan.payloads).some(hasPowerShellProfile)
|| scriptPayloads(plan.resolved_targets).some(hasPowerShellProfile)
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(hasPowerShellProfile)
|| scriptPayloads(record(plan.payload ?? {}).jobs).some(hasPowerShellProfile);
if (hasScriptView && plan.plan_payload_bytes === undefined) throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
const hasLogView = ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isQueryLogs) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isQueryLogs);
if (hasLogView && plan.plan_payload_bytes === undefined) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
let logJobs: QueryLogsPlanJob[] = [];
let powerShellJobs: PowerShellPlanJob[] = [];
let verifiedBytes: readonly number[] = [];
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
const payload = record(value).payload;
return payload !== null && typeof payload === 'object' && record(payload).execution_identity === 'system';
@@ -235,17 +109,8 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
if (plan.plan_payload_bytes !== undefined) {
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
verifiedBytes = Array.from(exactBytes);
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
validatePlanAliases(plan, parsed);
const rawJobs = record(parsed).jobs;
powerShellJobs = projectPowerShellJobs(rawJobs);
logJobs = projectQueryLogsJobs(rawJobs);
if (hasLogView || logJobs.length) validateQueryLogsViews(plan, rawJobs);
if (hasScriptView || powerShellJobs.length) {
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
validatePowerShellViews(plan, rawJobs);
}
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
}
for (const payload of systemPlanJobs(plan)) {
const action = record(payload.action);
@@ -257,7 +122,6 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
}
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), logJobs: logJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, planBytes: verifiedBytes });
}
export function recipeInput(value: unknown): RecordValue {
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);