feat: add approval bound full maintenance script console and executors
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# Rust RMM: Architektur und Implementierungsspezifikation
|
||||
|
||||
Version 1.19 · 2026-11-14 · Sprache: Deutsch
|
||||
Version 1.20 · 2026-11-14 · Sprache: Deutsch
|
||||
|
||||
**Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam.
|
||||
|
||||
@@ -33,6 +33,14 @@ Abandon mit Originalgrant, unabhängiger Helper-Lineage und vollständiger
|
||||
Snapshotbindung präzisiert. Mehrdeutige Übergaben bleiben Unknown; keine
|
||||
Abschwächung der vorhandenen Sync-/Verbrauchsinvarianten.
|
||||
|
||||
1.19 → 1.20 (2026-11-14): Der User priorisiert die vollständige, einzeln
|
||||
WebUI-genehmigte Shell-/PowerShell-Skriptkonsole für KI/MCP und Menschen.
|
||||
Ein ausdrücklich gebundenes Profil `full_maintenance_v1` ermöglicht nach
|
||||
getrennter Qualifikation Root-/SYSTEM-Hostwartung; bisherige begrenzte
|
||||
Dienst-/Paketprofile erhalten dadurch keine zusätzliche Erlaubnis. Batchstatus
|
||||
und abschließende begrenzte Rohbyteausgabe verwenden die bestehende Jobstrecke;
|
||||
interaktive PTY-/ConPTY-Sitzungen bleiben späterer eigener Umfang.
|
||||
|
||||
## Inhaltsverzeichnis
|
||||
|
||||
- [0 Auftrag und verbindliche Produktanforderungen](#0-auftrag-und-verbindliche-produktanforderungen)
|
||||
@@ -122,6 +130,106 @@ Deploymentdaten, offene Konfiguration und reale Nachweise:
|
||||
|
||||
### 0.1 Auftrag an die implementierende KI
|
||||
|
||||
**Userentscheidung Version1.20 — vollständige genehmigte Skriptkonsole zuerst:**
|
||||
Die KI darf über MCP gespeicherte Geräte-/Telemetriedaten im erlaubten Mandanten
|
||||
lesen, vollständige Shell-/PowerShell-Skripte schreiben und feste Aufträge als
|
||||
`pending_approval` beantragen. Ein berechtigter Mensch prüft und genehmigt in
|
||||
der WebUI die gespeicherten exakten Skriptbytes, Interpreter, Argumente, Ziele,
|
||||
Versuche, Identität und Grenzen. Erst dann darf der Agent ausführen. Der User
|
||||
wählt zunächst die Batch-Skriptkonsole mit Zustandsverfolgung und abschließender
|
||||
Ausgabe, ausdrücklich auch mit Root-/SYSTEM-Rechten zur vollständigen
|
||||
Hostwartung. Diese Strecke hat Vorrang vor weiteren Paketfixture-Erweiterungen.
|
||||
Die bisherige Einordnung interaktiver Terminals in M7 verschiebt diese
|
||||
Batchkonsole nicht; PTY/ConPTY, neue Sitzungen und laufendes Outputstreaming
|
||||
werden hierfür nicht eingeführt. Standardinventar/Heartbeats bleiben passiv;
|
||||
angeforderte Live-Skripte bleiben Jobs, auch wenn sie nur Logs lesen.
|
||||
|
||||
`run_script` erhält das additive optionale Stringfeld
|
||||
`privileged_script_profile="full_maintenance_v1"`. Fehlend wird es vollständig
|
||||
ausgelassen und erhält sämtliche alten Codec-/Hashbytes. Explizites `null`,
|
||||
unbekannte Werte und ein Profil bei `agent_service` sind ungültig. Das Profil
|
||||
gehört vor Genehmigung in die exakten Aktions-, Job- und Planbytes und wird von
|
||||
Signatur/Grant, zentraler Policy und lokaler Helperprüfung gebunden. Keine
|
||||
nachträgliche Hülle, implizite Profilauswahl oder Erweiterung alter Pläne.
|
||||
Windows-SYSTEM-Skripte benötigen dieses Profil; alte SYSTEM-SCM-/MSI-Policies
|
||||
erlauben sie weiterhin nicht. Historische Linux-Root-Skripte ohne Profil behalten
|
||||
ihren bisherigen begrenzten Ausführungsvertrag und werden nicht Vollwartung.
|
||||
|
||||
Planersteller und Freigeber benötigen jeweils aktuell `scripts:execute` und
|
||||
zusätzlich genau `root:execute` beziehungsweise `system:execute`; beide
|
||||
Identitäten bleiben getrennt. Das Profil braucht zusätzlich ein ausdrückliches,
|
||||
versioniertes zentrales und lokales Opt-in samt exakten Geräte-/Generations-/
|
||||
Principal-/Helperhashbindungen. Zentrale Linux-Policyversion2 und lokale
|
||||
General-Policyversion2 können `allowed_script_profiles` mit genau dem
|
||||
bekannten Profil enthalten; Windows-SYSTEM-Policyversion3 kann es getrennt von
|
||||
SCM und MSI enthalten. Fehlend bleibt deny für Vollwartung; vorhandene `null`-
|
||||
oder unbekannte Profile verweigern. Qualifizierte Capability
|
||||
`script.full_maintenance/1` kommt zusätzlich zu Aktion, Interpreter,
|
||||
`root:run_script` beziehungsweise `system:run_script`, Helperhash und signiertem
|
||||
Sync hinzu. Quelle, Build oder Policydatei allein veröffentlichen sie nicht.
|
||||
|
||||
Für das neue Linux-Fullprofil ist zusätzlich `helper_binary_sha256` im
|
||||
Schema2-Policy-/Pin-/zentralen Scope verpflichtend. Der Roothelper beobachtet
|
||||
sein eigenes tatsächlich laufendes Image über einen gehaltenen Dateideskriptor
|
||||
und prüft es vor Probe/neuer Zulassung gegen den geschützten Pin. Der Agent
|
||||
verifiziert diese Rootpeer-Probe, ohne fremde Root-/proc-Dateien lesen zu müssen,
|
||||
und meldet nur dann `helper.binary.sha256:<hash>`; die Zentrale verlangt denselben
|
||||
Hash. Neue optionale Metadaten bleiben bei General/APT vollständig ausgelassen;
|
||||
Schema1-Pins und deren alte Byte-/Hashverträge bleiben unverändert.
|
||||
|
||||
Linux erhält hierfür ein getrenntes explizites Helper-Ausführungsprofil
|
||||
`full_maintenance_v1`; bestehende General-/APT-Sandboxes bleiben erhalten.
|
||||
Seine systemd-Start-/Dateisystem-/Netzwerk-/Capabilitybedingungen müssen die
|
||||
zugesagte Hostwartung tatsächlich erlauben und vor Zieländerung überprüfbar
|
||||
feststehen. Windows führt mit dem eigenen SYSTEM-Token (SID18) aus, niemals
|
||||
mit einem nur umbenannten LocalService-Prozess (SID19). Beide verwenden weiter
|
||||
die unabhängige Originalsignaturprüfung, Peer-/Clock-/Boot-/Sync-/Fenceprüfung
|
||||
und dauerhaften atomaren Einmalverbrauch. Windows bewahrt zusätzlich Intent,
|
||||
Dispatchmarker, unabhängigen RawMirror und deny-only Abandon ohne Dateierzeugung
|
||||
oder Wirkung. Skriptdateien entstehen erst nach erfolgreichem Helperverbrauch
|
||||
in einem vom jeweiligen Helper geschützten Bereich. Journalidentitäten,
|
||||
File-IDs/Inodes, Schlüssel und vorhandene Verbräuche bleiben erhalten; keine
|
||||
Ledgerresets zur Einführung des Profils.
|
||||
|
||||
Die erste Vollwartungsstrecke erlaubt 1..32768 exakte UTF-8-Skriptbytes,
|
||||
höchstens32 Argumente gemäß bestehendem Vertrag und insgesamt höchstens65536
|
||||
stdout-/stderr-Rohbytes. Laufzeit bleibt ausdrücklich begrenzt: Linux1..300s,
|
||||
Windows1..120s, zusätzlich zur engeren genehmigten/lokalen Grenze. Interpreter
|
||||
und argv bleiben fest (`/bin/sh` oder qualifiziertes `/bin/bash` mit privater
|
||||
Datei; Windows PowerShell5.1 mit `-NoLogo -NoProfile -NonInteractive -File`).
|
||||
Die getrennte explizite, vor Genehmigung gebundene Prozessoption `RemoteSigned`
|
||||
aus1.18 darf hinzukommen; kein Executorfallback oder Maschinen-/GPO-Override.
|
||||
Encoding/BOM/Zeilenenden werden nach Genehmigung nicht verändert.
|
||||
|
||||
**Vollwartung ist volle Hostautorität:** Ein genehmigtes Root-/SYSTEM-Skript
|
||||
kann Dateien, Netzwerk, Konten, Dienste, Agent und Schlüsselbestand ändern und
|
||||
auch einen Neustart auslösen. Kein Sandbox-, No-Reboot-, Rollback- oder
|
||||
Geheimnisschutzversprechen für beliebigen privilegierten Code. Nachgeladene
|
||||
Programme/Netzwerkdaten sind ohne eigenen Vertrag nicht automatisch auf ihren
|
||||
Inhalt festgelegt. Der Plan zeigt diese Autorität ausdrücklich. Dies ersetzt
|
||||
keine einzelne Genehmigung und autorisiert keine unangekündigten destruktiven
|
||||
Abnahmen. Ein Skriptneustart ist keine typisierte Rebootabnahme; fehlender
|
||||
Abschluss bleibt `unknown` und wird nach Wiederkontakt nicht automatisch erneut
|
||||
versucht. Exit0 belegt Prozessabschluss, keine beliebige fachliche Wirkung.
|
||||
|
||||
Abbruch/Fence/Timeout müssen während der Ausführung beobachtet und ehrlich
|
||||
berichtet werden. Nur eigene Prozessgruppe beziehungsweise atomar zugewiesenes
|
||||
Windows-JobObject und erhaltene Handles dürfen beendet werden. Keine Übernahme
|
||||
fremder PIDs, kein globaler Kill und kein Anspruch, dass ein privilegiertes
|
||||
Skript keine unabhängigen Dienste/Tasks erzeugen kann. Bereits eingetretene
|
||||
Teilwirkung bleibt möglich; unklarer Abschluss bleibt `unknown`. Eigene laufende
|
||||
Kinder/Handles und lokale Sperre bleiben bis belegtem Abschluss kontrolliert;
|
||||
ein spätes Exit0 heilt keinen Timeout/Abbruch. Bestehende finale Rohbytes samt
|
||||
Trunkierung werden unverändert gespeichert; WebUI/MCP erhalten die gespeicherten
|
||||
Plan-/Ergebnisdaten im berechtigten Mandanten. Vollständige Skriptanzeige vor
|
||||
Genehmigung und sichere Textdarstellung der abschließenden Ausgabe sind Pflicht,
|
||||
kein behauptetes Livestreaming.
|
||||
|
||||
Dieser Abschnitt normiert den Vertrag und ersetzt keine Quellen-, Build-,
|
||||
VM- oder Capabilitynachweise; aktuelle getrennte Belege stehen in
|
||||
`deploy/linux/full-maintenance-README.md`. Zuerst Linux-Cloud-VM,
|
||||
anschließend getrennte native Windows-VM-Abnahme; Notebook nur Entwicklung.
|
||||
|
||||
**Ausdrückliche Userentscheidungen Version1.18 — begrenzte Windowsfreigaben:**
|
||||
Für jeden zuvor mit seinem unveränderlichen Plan in der WebUI genehmigten
|
||||
Windows-PowerShell5.1-Jobprozess darf die feste Option `RemoteSigned` ausschließlich
|
||||
|
||||
@@ -33,6 +33,7 @@ impl Binding {
|
||||
);
|
||||
ensure!(
|
||||
j.action.validate()
|
||||
&& j.action.valid_execution_identity(&j.execution_identity)
|
||||
&& j.action
|
||||
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
|
||||
&& j.not_before < j.start_before,
|
||||
|
||||
@@ -41,6 +41,7 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - Duration::minutes(1),
|
||||
@@ -181,6 +182,7 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
|
||||
@@ -868,6 +868,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -606,6 +606,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -85,6 +85,12 @@ impl ScriptRequest {
|
||||
}
|
||||
|
||||
pub fn run_script(request: &ScriptRequest) -> Result<ScriptOutput> {
|
||||
run_script_controlled(request, || Ok(()))
|
||||
}
|
||||
pub fn run_script_controlled(
|
||||
request: &ScriptRequest,
|
||||
observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<ScriptOutput> {
|
||||
ensure!(
|
||||
request.interpreter.available(),
|
||||
"UNSUPPORTED_CAPABILITY: interpreter unavailable"
|
||||
@@ -115,11 +121,12 @@ pub fn run_script(request: &ScriptRequest) -> Result<ScriptOutput> {
|
||||
path.to_str().context("non-UTF8 temp path")?.to_owned(),
|
||||
];
|
||||
args.extend(request.arguments.clone());
|
||||
process::run(
|
||||
process::run_controlled(
|
||||
request.interpreter.path(),
|
||||
&args,
|
||||
request.timeout,
|
||||
request.max_output_bytes,
|
||||
observe,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+232
-108
@@ -15,11 +15,19 @@ pub struct Output {
|
||||
pub stderr: Vec<u8>,
|
||||
pub truncated: bool,
|
||||
pub timed_out: bool,
|
||||
pub interrupted: bool,
|
||||
}
|
||||
|
||||
// Nonblocking pipes avoid both unbounded output and reader threads held open by
|
||||
// grandchildren. The child has a separate process group, cleaned even on success.
|
||||
pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize) -> Result<Output> {
|
||||
run_controlled(program, args, timeout, cap, || Ok(()))
|
||||
}
|
||||
pub(crate) fn run_controlled(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
timeout: Duration,
|
||||
cap: usize,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Output> {
|
||||
ensure!(!timeout.is_zero() && cap > 0, "invalid process limits");
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
@@ -34,144 +42,260 @@ pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.process_group(0);
|
||||
observe()?;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("spawn {program}"))?;
|
||||
struct Group(u32);
|
||||
// Keep the group leader unreaped until AFTER the last signal and cleanup.
|
||||
// Its reserved PID prevents the numerical PGID from becoming a foreign group.
|
||||
struct Group {
|
||||
pid: u32,
|
||||
reserved: bool,
|
||||
}
|
||||
impl Group {
|
||||
fn kill(&self) {
|
||||
if self.reserved {
|
||||
unsafe {
|
||||
libc::kill(-(self.pid as i32), libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Group {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: negative PID addresses only the group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(self.0 as i32), libc::SIGKILL);
|
||||
}
|
||||
self.kill();
|
||||
}
|
||||
}
|
||||
let group = Group(child.id());
|
||||
let mut group = Group {
|
||||
pid: child.id(),
|
||||
reserved: true,
|
||||
};
|
||||
let mut stdout = child.stdout.take().context("missing stdout")?;
|
||||
let mut stderr = child.stderr.take().context("missing stderr")?;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
// SAFETY: these are live owned pipe descriptors; flags are not pointers.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
}
|
||||
fn drain(
|
||||
pipe: &mut impl Read,
|
||||
target: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<bool> {
|
||||
let mut bytes = [0; 4096];
|
||||
// Bound each pass too: a continuously writing child cannot starve timeout.
|
||||
for _ in 0..16 {
|
||||
match pipe.read(&mut bytes) {
|
||||
Ok(0) => return Ok(true),
|
||||
Ok(n) => {
|
||||
let keep = n.min(*remaining);
|
||||
target.extend_from_slice(&bytes[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < n;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut result = Output {
|
||||
let began = Instant::now();
|
||||
let mut output = Output {
|
||||
code: None,
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
truncated: false,
|
||||
timed_out: false,
|
||||
interrupted: false,
|
||||
};
|
||||
let mut remaining = cap;
|
||||
let status = loop {
|
||||
let drained = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)
|
||||
.and_then(|_| {
|
||||
let mut failure = None;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
failure = Some(anyhow::Error::from(std::io::Error::last_os_error()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if failure.is_none() {
|
||||
loop {
|
||||
if let Err(e) = drain(
|
||||
&mut stdout,
|
||||
&mut output.stdout,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
.and_then(|_| {
|
||||
drain(
|
||||
&mut stderr,
|
||||
&mut output.stderr,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
}) {
|
||||
failure = Some(e);
|
||||
break;
|
||||
}
|
||||
// WNOWAIT deliberately observes without releasing this child's PID.
|
||||
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
|
||||
let state = unsafe {
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
child.id(),
|
||||
info.as_mut_ptr(),
|
||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||
)
|
||||
};
|
||||
if state < 0 {
|
||||
let e = std::io::Error::last_os_error();
|
||||
if e.kind() == std::io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if e.raw_os_error() == Some(libc::ECHILD) {
|
||||
group.reserved = false;
|
||||
}
|
||||
failure = Some(e.into());
|
||||
break;
|
||||
}
|
||||
if unsafe { info.assume_init().si_pid() } != 0 {
|
||||
break;
|
||||
}
|
||||
let fenced = observe().is_err();
|
||||
if began.elapsed() >= timeout || fenced {
|
||||
output.timed_out = began.elapsed() >= timeout;
|
||||
output.interrupted = fenced;
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
if !group.reserved {
|
||||
// An unexpected external reap destroyed the group identity proof. Never
|
||||
// signal/adopt a numerical replacement; caller records Unknown.
|
||||
return Err(failure.unwrap_or_else(|| anyhow::anyhow!("OWNED_GROUP_IDENTITY_LOST")));
|
||||
}
|
||||
group.kill();
|
||||
let cleanup = Instant::now();
|
||||
loop {
|
||||
// A setup error may have left a blocking pipe. It must not become an
|
||||
// unbounded cleanup read; retain only group ownership in that path.
|
||||
let out_closed = if failure.is_some() {
|
||||
Ok(true)
|
||||
} else {
|
||||
drain(
|
||||
&mut stdout,
|
||||
&mut output.stdout,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
};
|
||||
let err_closed = if failure.is_some() {
|
||||
Ok(true)
|
||||
} else {
|
||||
drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut output.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
&mut output.truncated,
|
||||
)
|
||||
});
|
||||
if let Err(e) = drained {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e);
|
||||
};
|
||||
if out_closed.is_err() || err_closed.is_err() {
|
||||
output.truncated = true;
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e.into());
|
||||
// Only zombies may remain while the *owned* leader stays unreaped.
|
||||
// They cannot execute or retain pipe writers. Unclear /proc state keeps
|
||||
// this owner and the caller's executor lock instead of a replacement.
|
||||
if group_has_no_live_members(group.pid) {
|
||||
if out_closed.unwrap_or(true) && err_closed.unwrap_or(true) {
|
||||
break;
|
||||
}
|
||||
// A privileged script may deliberately give a pipe to an unrelated
|
||||
// process. That process is outside our ownership; never kill it.
|
||||
if cleanup.elapsed() >= Duration::from_millis(250) {
|
||||
output.truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if started.elapsed() >= timeout {
|
||||
result.timed_out = true;
|
||||
// SAFETY: this is the dedicated group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as i32), libc::SIGKILL);
|
||||
}
|
||||
break child.wait()?;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
let pgid = child.id();
|
||||
drop(group);
|
||||
// SIGKILL delivery is asynchronous. A single WouldBlock is not EOF and
|
||||
// does not prove that descendants have stopped. Bound both cleanup waiting
|
||||
// and output draining, and withhold a successful exit code if unconfirmed.
|
||||
let cleanup_started = Instant::now();
|
||||
loop {
|
||||
let stdout_closed = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let stderr_closed = drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
// SAFETY: signal zero only probes the dedicated process group.
|
||||
let absent = unsafe { libc::kill(-(pgid as i32), 0) } == -1
|
||||
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
|
||||
if stdout_closed && stderr_closed && absent {
|
||||
result.code = status.code();
|
||||
break;
|
||||
}
|
||||
if cleanup_started.elapsed() >= Duration::from_millis(250) {
|
||||
result.truncated |= !stdout_closed || !stderr_closed;
|
||||
// None explicitly means no confirmed successful completion. This
|
||||
// can also occur for lingering zombies: never guess their state.
|
||||
result.code = None;
|
||||
break;
|
||||
if cleanup.elapsed() >= Duration::from_millis(250) {
|
||||
output.timed_out = true;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok(result)
|
||||
// Disarm BEFORE releasing the reserved leader PID: no later Drop can signal
|
||||
// a reused PGID. All assigned living members have already ended.
|
||||
group.reserved = false;
|
||||
let status = child.wait()?;
|
||||
if let Some(e) = failure {
|
||||
return Err(e);
|
||||
}
|
||||
output.interrupted |= observe().is_err();
|
||||
output.code = if output.timed_out || began.elapsed() >= timeout {
|
||||
None
|
||||
} else {
|
||||
status.code()
|
||||
};
|
||||
Ok(output)
|
||||
}
|
||||
fn drain(
|
||||
pipe: &mut impl Read,
|
||||
target: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<bool> {
|
||||
let mut bytes = [0; 4096];
|
||||
for _ in 0..16 {
|
||||
match pipe.read(&mut bytes) {
|
||||
Ok(0) => return Ok(true),
|
||||
Ok(n) => {
|
||||
let keep = n.min(*remaining);
|
||||
target.extend_from_slice(&bytes[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < n;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
fn group_has_no_live_members(pgid: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||
return false;
|
||||
};
|
||||
for entry in entries {
|
||||
let Ok(entry) = entry else {
|
||||
return false;
|
||||
};
|
||||
if entry.file_name().to_string_lossy().parse::<u32>().is_err() {
|
||||
continue;
|
||||
}
|
||||
let bytes = match std::fs::read_to_string(entry.path().join("stat")) {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let Some((_, rest)) = bytes.rsplit_once(") ") else {
|
||||
return false;
|
||||
};
|
||||
let fields: Vec<_> = rest.split_whitespace().take(3).collect();
|
||||
if fields.len() != 3 {
|
||||
return false;
|
||||
}
|
||||
let Ok(group) = fields[2].parse::<u32>() else {
|
||||
return false;
|
||||
};
|
||||
if group == pgid && fields[0] != "Z" && fields[0] != "X" {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cancellation_observation_terminates_only_owned_group_and_keeps_raw_bounded_output() {
|
||||
let began = Instant::now();
|
||||
let output = run_controlled(
|
||||
"/bin/sh",
|
||||
&[
|
||||
"-c".into(),
|
||||
"printf before; printf err >&2; sleep 10".into(),
|
||||
],
|
||||
Duration::from_secs(5),
|
||||
64,
|
||||
|| {
|
||||
ensure!(
|
||||
began.elapsed() < Duration::from_millis(80),
|
||||
"TEST_CANCELLED"
|
||||
);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(output.interrupted);
|
||||
assert!(!output.timed_out);
|
||||
assert_eq!(output.stdout, b"before");
|
||||
assert_eq!(output.stderr, b"err");
|
||||
assert_ne!(output.code, Some(0));
|
||||
assert!(began.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn exited_leader_does_not_leave_background_effects_or_open_pipes() {
|
||||
let directory =
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::{
|
||||
/// 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>> {
|
||||
pub(crate) fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
arguments,
|
||||
@@ -26,7 +26,9 @@ fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
anyhow::bail!("SCRIPT_REQUIRED")
|
||||
};
|
||||
ensure!(
|
||||
job.execution_identity == "agent_service"
|
||||
(job.execution_identity == "agent_service"
|
||||
|| (job.execution_identity == "system" && job.action.full_maintenance()))
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& interpreter == "powershell"
|
||||
&& job.action.validate(),
|
||||
"WINDOWS_SCRIPT_PROFILE_BINDING"
|
||||
@@ -303,6 +305,7 @@ mod tests {
|
||||
arguments: vec!["-ExecutionPolicy".into(), "Bypass".into()],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -470,6 +470,14 @@ fn verified_mirror_row(
|
||||
Ok(outcome)
|
||||
}
|
||||
fn system_shape(job: &JobPayload) -> bool {
|
||||
if job.action.full_maintenance() {
|
||||
return job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job.action.valid_execution_identity("system")
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
|
||||
}
|
||||
if job.action.windows_msi().is_some() {
|
||||
return job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
@@ -544,6 +552,41 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if job.action.full_maintenance() {
|
||||
let Action::RunScript {
|
||||
script_utf8,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("SYSTEM_SCRIPT_REQUIRED")
|
||||
};
|
||||
let e = &outcome.evidence;
|
||||
ensure!(
|
||||
system_shape(job)
|
||||
&& outcome.exit_code == Some(0)
|
||||
&& !outcome.output_truncated
|
||||
&& !outcome.reboot_required
|
||||
&& e["postconditions_passed"] == true
|
||||
&& e["privileged_script_profile"] == "full_maintenance_v1"
|
||||
&& e["execution_sid"] == "S-1-5-18"
|
||||
&& e["script_sha256"] == rmm_domain::jobs::hash(script_utf8.as_bytes())
|
||||
&& expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| outcome.stdout == s.as_bytes()),
|
||||
"SYSTEM_SCRIPT_POSTCONDITION_BINDING"
|
||||
);
|
||||
if windows_execution_profile.is_some() {
|
||||
ensure!(
|
||||
e["windows_execution_profile"] == "powershell_51_remote_signed"
|
||||
&& e["execution_policy_requested"] == "RemoteSigned"
|
||||
&& e["execution_policy_scope"] == "process",
|
||||
"SYSTEM_SCRIPT_PROCESS_PROFILE_BINDING"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Action::SetServiceState { unit, state } = &job.action else {
|
||||
anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED");
|
||||
};
|
||||
@@ -585,6 +628,49 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod script_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn system_script_success_requires_exact_profile_identity_bytes_and_raw_output() {
|
||||
let mut job = msi_test_job();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hi\r\n".into()),
|
||||
windows_execution_profile: Some(
|
||||
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
|
||||
),
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
assert!(system_shape(&job));
|
||||
let mut outcome = Outcome {
|
||||
state: "succeeded".into(),
|
||||
stdout: b"hi\r\n".to_vec(),
|
||||
stderr: vec![],
|
||||
exit_code: Some(0),
|
||||
output_truncated: false,
|
||||
reboot_required: false,
|
||||
error_code: String::new(),
|
||||
evidence: json!({"postconditions_passed":true,"privileged_script_profile":"full_maintenance_v1","execution_sid":"S-1-5-18","script_sha256":rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n"),"windows_execution_profile":"powershell_51_remote_signed","execution_policy_requested":"RemoteSigned","execution_policy_scope":"process"}),
|
||||
};
|
||||
checked_outcome(&job, &outcome).unwrap();
|
||||
outcome.evidence["execution_sid"] = "S-1-5-19".into();
|
||||
assert!(checked_outcome(&job, &outcome).is_err());
|
||||
outcome.evidence["execution_sid"] = "S-1-5-18".into();
|
||||
outcome.stdout = b"other".to_vec();
|
||||
assert!(checked_outcome(&job, &outcome).is_err());
|
||||
outcome.state = "unknown".into();
|
||||
outcome.evidence = serde_json::Value::Null;
|
||||
checked_outcome(&job, &outcome).unwrap();
|
||||
job.execution_identity = "root".into();
|
||||
assert!(!system_shape(&job));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn msi_test_job() -> JobPayload {
|
||||
use rmm_domain::windows_execution::*;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! SYSTEM service with an independent signed-sync gate and durable ledger.
|
||||
//! Only fixed, policy-pinned SCM state changes exist; no arbitrary SYSTEM CLI.
|
||||
//! Versioned policy independently admits fixed SCM/MSI actions or the explicit
|
||||
//! full_maintenance_v1 SYSTEM script profile; none inherit another's authority.
|
||||
//!
|
||||
//! Bootstrap contract (not performed by this module): install exactly
|
||||
//! `RmmDiscoverySystemHelper` as an OWN_PROCESS LocalSystem service with its
|
||||
@@ -75,6 +76,12 @@ pub struct Settings {
|
||||
deserialize_with = "strict_recipe_hashes"
|
||||
)]
|
||||
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
}
|
||||
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
d: D,
|
||||
@@ -83,7 +90,7 @@ fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
}
|
||||
impl Settings {
|
||||
fn permits_msi(&self, job: &JobPayload) -> bool {
|
||||
self.schema_version == 2
|
||||
self.schema_version >= 2
|
||||
&& job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
@@ -96,10 +103,24 @@ impl Settings {
|
||||
.is_some_and(|h| h.contains(&m.recipe_sha256))
|
||||
})
|
||||
}
|
||||
fn permits_script(&self, job: &JobPayload) -> bool {
|
||||
self.schema_version == 3
|
||||
&& job.execution_identity == "system"
|
||||
&& job.action.full_maintenance()
|
||||
&& job.action.valid_execution_identity("system")
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& job.max_runtime_seconds <= self.max_runtime_seconds
|
||||
&& self.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||
matches!(self.schema_version, 1..=3)
|
||||
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||
&& (self.schema_version == 3 || self.allowed_script_profiles.is_none())
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
@@ -112,6 +133,9 @@ impl Settings {
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& self.allowed_script_profiles.as_deref().is_none_or(
|
||||
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
|
||||
)
|
||||
&& !self.allow_reboot
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
&& self.allowed_services.len() <= 16,
|
||||
@@ -1018,7 +1042,8 @@ impl SystemHelper {
|
||||
job.execution_identity == "system"
|
||||
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
|
||||
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|
||||
|| self.settings.permits_msi(&job)),
|
||||
|| self.settings.permits_msi(&job)
|
||||
|| self.settings.permits_script(&job)),
|
||||
"SYSTEM_ABANDON_POLICY_DENIED"
|
||||
);
|
||||
self.sync()?;
|
||||
@@ -1109,6 +1134,9 @@ impl SystemHelper {
|
||||
),
|
||||
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
||||
);
|
||||
if job.action.full_maintenance() {
|
||||
return self.execute_script(generation, request, &job, &permit, peer);
|
||||
}
|
||||
if job.action.windows_msi().is_some() {
|
||||
return self.execute_msi(generation, request, &job, &permit, peer);
|
||||
}
|
||||
@@ -1150,6 +1178,78 @@ impl SystemHelper {
|
||||
ledger::finish(&self.db, &permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn execute_script(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
request: &Request,
|
||||
job: &JobPayload,
|
||||
permit: &ExecutionPermitPayload,
|
||||
peer: &mut ipc::PeerProof,
|
||||
) -> Result<Outcome> {
|
||||
let began = Instant::now();
|
||||
ensure!(
|
||||
self.settings.permits_script(job),
|
||||
"SYSTEM_SCRIPT_POLICY_DENIED"
|
||||
);
|
||||
self.observe_unsettled_msi()?;
|
||||
ensure!(
|
||||
self.unsettled_msi.is_none(),
|
||||
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
||||
);
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
let (_, fresh, recorded_at) =
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
ensure!(
|
||||
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
||||
"SYSTEM_SCRIPT_START_FENCED"
|
||||
);
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
ledger::begin_execution(
|
||||
&mut self.db,
|
||||
permit,
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
recorded_at,
|
||||
)?;
|
||||
self.sync.as_mut().unwrap().close();
|
||||
let helper_sid = self.settings.helper.service_sid.clone();
|
||||
let result = crate::system_script::execute(
|
||||
job,
|
||||
permit.grant_id,
|
||||
&helper_sid,
|
||||
began,
|
||||
|before_start| {
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
self.clock.now()?;
|
||||
ensure!(!STOP.load(Ordering::SeqCst), "SYSTEM_SCRIPT_CANCELLED");
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
if before_start {
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
let outcome =
|
||||
result.unwrap_or_else(|_| Outcome::unknown("SYSTEM_SCRIPT_EFFECT_UNRESOLVED"));
|
||||
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
||||
self.guard.check(&self.db)?;
|
||||
ledger::finish(&self.db, permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn execute_msi(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
@@ -1517,6 +1617,7 @@ mod tests {
|
||||
enable_effects: false,
|
||||
allow_reboot: false,
|
||||
allowed_msi_recipe_sha256: None,
|
||||
allowed_script_profiles: None,
|
||||
};
|
||||
let legacy = serde_json::to_value(&settings).unwrap();
|
||||
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
|
||||
@@ -1538,6 +1639,29 @@ mod tests {
|
||||
settings.max_runtime_seconds = 30;
|
||||
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
||||
assert!(!settings.permits_msi(&job));
|
||||
let mut script = job.clone();
|
||||
script.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
assert!(!settings.permits_script(&script));
|
||||
settings.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(!settings.permits_script(&script));
|
||||
settings.schema_version = 3;
|
||||
assert!(settings.permits_script(&script));
|
||||
script.execution_identity = "root".into();
|
||||
assert!(!settings.permits_script(&script));
|
||||
let mut null = legacy;
|
||||
null["allowed_script_profiles"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<Settings>(null).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn service_adapter_exposes_only_implemented_states() {
|
||||
|
||||
@@ -18,15 +18,17 @@ pub mod inventory;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
pub mod package;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub mod msi_cache;
|
||||
#[cfg(windows)]
|
||||
pub mod native;
|
||||
pub mod package;
|
||||
#[cfg(windows)]
|
||||
pub mod process;
|
||||
#[cfg(windows)]
|
||||
pub mod service;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod system_script;
|
||||
|
||||
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
|
||||
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
|
||||
|
||||
@@ -194,9 +194,31 @@ pub fn run(
|
||||
seconds: u32,
|
||||
max_bytes: usize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<Output> {
|
||||
run_observed(
|
||||
executable,
|
||||
arguments,
|
||||
cwd,
|
||||
Duration::from_secs(seconds.into()),
|
||||
max_bytes,
|
||||
cancel,
|
||||
|| Ok(()),
|
||||
)
|
||||
}
|
||||
pub(crate) fn run_observed(
|
||||
executable: &Path,
|
||||
arguments: &[OsString],
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
max_bytes: usize,
|
||||
cancel: &AtomicBool,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Output> {
|
||||
ensure!(
|
||||
executable.is_absolute() && cwd.is_absolute() && seconds > 0 && max_bytes <= 512 * 1024,
|
||||
executable.is_absolute()
|
||||
&& cwd.is_absolute()
|
||||
&& !timeout.is_zero()
|
||||
&& max_bytes <= 512 * 1024,
|
||||
"PROCESS_LIMITS"
|
||||
);
|
||||
let (stdout, out_write) = pipe()?;
|
||||
@@ -268,7 +290,17 @@ pub fn run(
|
||||
// Minimal environment: no inherited tokens, proxy secrets, device paths,
|
||||
// PSModulePath overrides, user profile or caller-controlled executable PATH.
|
||||
let mut environment = Vec::new();
|
||||
let system_text = system
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("SYSTEM_DIRECTORY_ENCODING"))?;
|
||||
ensure!(
|
||||
system_text.as_bytes().get(1) == Some(&b':')
|
||||
&& system_text.as_bytes()[0].is_ascii_alphabetic(),
|
||||
"SYSTEM_DRIVE_REQUIRED"
|
||||
);
|
||||
let system_drive = &system_text[..2];
|
||||
for value in [
|
||||
format!("SystemDrive={system_drive}"),
|
||||
format!("PATH={}\\System32;{}", system.display(), system.display()),
|
||||
format!("SystemRoot={}", system.display()),
|
||||
format!("TEMP={}", cwd.display()),
|
||||
@@ -279,6 +311,11 @@ pub fn run(
|
||||
}
|
||||
environment.push(0);
|
||||
let mut process: PROCESS_INFORMATION = unsafe { zeroed() };
|
||||
observe()?;
|
||||
ensure!(
|
||||
!cancel.load(Ordering::SeqCst),
|
||||
"PROCESS_CANCELLED_BEFORE_START"
|
||||
);
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateProcessW(
|
||||
@@ -303,32 +340,101 @@ pub fn run(
|
||||
drop(stdin);
|
||||
drop(out_write);
|
||||
drop(err_write);
|
||||
let mut result = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
exit_code: None,
|
||||
truncated: false,
|
||||
interrupted: false,
|
||||
cancelled: false,
|
||||
};
|
||||
let began = Instant::now();
|
||||
let mut remaining = max_bytes;
|
||||
loop {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
let result = (|| -> Result<Output> {
|
||||
let mut result = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
exit_code: None,
|
||||
truncated: false,
|
||||
interrupted: false,
|
||||
cancelled: false,
|
||||
};
|
||||
let began = Instant::now();
|
||||
let mut remaining = max_bytes;
|
||||
loop {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectBasicAccountingInformation,
|
||||
ptr::addr_of_mut!(accounting).cast(),
|
||||
size_of_val(&accounting) as u32,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_TREE_STATE"
|
||||
);
|
||||
if accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
}
|
||||
let fenced = observe().is_err();
|
||||
if !result.interrupted
|
||||
&& (began.elapsed() >= timeout || cancel.load(Ordering::SeqCst) || fenced)
|
||||
{
|
||||
result.cancelled = cancel.load(Ordering::SeqCst) || fenced;
|
||||
result.interrupted = true;
|
||||
ensure!(
|
||||
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||
"PROCESS_TREE_TERMINATION"
|
||||
);
|
||||
// This wait proves termination, not absence of effects.
|
||||
ensure!(
|
||||
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||
);
|
||||
// Keep this JobObject/process handle owner until *all* assigned
|
||||
// processes are observed inactive. Waiting for the leader alone
|
||||
// cannot release the helper lane or heal an interrupted outcome.
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||
for _ in 0..8 {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
}
|
||||
let mut code = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||
&& code != STILL_ACTIVE as u32,
|
||||
"PROCESS_EXIT_UNCONFIRMED"
|
||||
);
|
||||
result.exit_code = Some(code as i32);
|
||||
Ok(result)
|
||||
})();
|
||||
if result.is_err() {
|
||||
// Keep exact owned handles and the caller's helper lane on any observer
|
||||
// or I/O error. Termination/leader exit alone cannot prove the whole
|
||||
// assigned tree inactive; never drop ownership and admit replacement.
|
||||
unsafe {
|
||||
TerminateJobObject(job.as_raw_handle(), 1);
|
||||
}
|
||||
loop {
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
let ok = unsafe {
|
||||
QueryInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectBasicAccountingInformation,
|
||||
@@ -336,52 +442,14 @@ pub fn run(
|
||||
size_of_val(&accounting) as u32,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_TREE_STATE"
|
||||
);
|
||||
if accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
};
|
||||
if ok != 0 && accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if began.elapsed() >= Duration::from_secs(seconds.into()) || cancel.load(Ordering::SeqCst) {
|
||||
result.cancelled = cancel.load(Ordering::SeqCst);
|
||||
result.interrupted = true;
|
||||
ensure!(
|
||||
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||
"PROCESS_TREE_TERMINATION"
|
||||
);
|
||||
// This wait proves termination, not absence of effects.
|
||||
ensure!(
|
||||
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||
);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||
drop(job);
|
||||
for _ in 0..8 {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
}
|
||||
let mut code = 0;
|
||||
ensure!(
|
||||
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||
&& code != STILL_ACTIVE as u32,
|
||||
"PROCESS_EXIT_UNCONFIRMED"
|
||||
);
|
||||
result.exit_code = Some(code as i32);
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Exact approved SYSTEM script bytes, created only after helper consumption.
|
||||
use crate::helper_ipc::PinnedFile;
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::auth::Outcome;
|
||||
use rmm_domain::jobs::{Action, JobPayload, WindowsExecutionProfile, hash};
|
||||
use std::{
|
||||
fs::OpenOptions,
|
||||
io::Write,
|
||||
os::windows::fs::OpenOptionsExt,
|
||||
path::Path,
|
||||
sync::atomic::AtomicBool,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub(crate) fn execute(
|
||||
job: &JobPayload,
|
||||
grant: uuid::Uuid,
|
||||
helper_sid: &str,
|
||||
began: Instant,
|
||||
mut observe: impl FnMut(bool) -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
ensure!(
|
||||
job.execution_identity == "system"
|
||||
&& job.action.full_maintenance()
|
||||
&& job.action.valid_execution_identity("system")
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes),
|
||||
"SYSTEM_SCRIPT_PROFILE_REQUIRED"
|
||||
);
|
||||
let Action::RunScript {
|
||||
script_utf8,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("SYSTEM_SCRIPT_REQUIRED")
|
||||
};
|
||||
let directory = Path::new(crate::helper_system::STATE_ROOT);
|
||||
let writers = [helper_sid.to_owned()];
|
||||
let mut root = PinnedFile::open(directory, true, &[], &writers, false)?;
|
||||
let path = directory.join(format!("script-{}-{}.ps1", job.attempt_id, grant));
|
||||
let mut file = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.share_mode(windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ)
|
||||
.open(&path)?;
|
||||
file.write_all(script_utf8.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(path.clone());
|
||||
let mut pinned = PinnedFile::open(&path, false, &[], &writers, false)?;
|
||||
ensure!(
|
||||
std::fs::read(&path)? == script_utf8.as_bytes(),
|
||||
"SYSTEM_SCRIPT_BYTES_CHANGED"
|
||||
);
|
||||
let executable = crate::actions::powershell()?;
|
||||
let arguments = crate::actions::script_arguments(job, &path)?;
|
||||
let timeout = Duration::from_secs(job.max_runtime_seconds.into());
|
||||
let remaining = timeout
|
||||
.checked_sub(began.elapsed())
|
||||
.filter(|d| !d.is_zero())
|
||||
.ok_or_else(|| anyhow::anyhow!("SYSTEM_SCRIPT_PREPARATION_TIMEOUT"))?;
|
||||
let mut first = true;
|
||||
let output = crate::process::run_observed(
|
||||
&executable,
|
||||
&arguments,
|
||||
directory,
|
||||
remaining,
|
||||
job.max_output_bytes as usize,
|
||||
&AtomicBool::new(false),
|
||||
|| {
|
||||
root.check()?;
|
||||
pinned.check()?;
|
||||
observe(first)?;
|
||||
first = false;
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
let expected = expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| output.stdout == s.as_bytes());
|
||||
let interrupted = output.interrupted || began.elapsed() >= timeout || observe(false).is_err();
|
||||
let success = !interrupted && output.exit_code == Some(0) && expected && !output.truncated;
|
||||
let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
|
||||
"script_sha256":hash(script_utf8.as_bytes()),"privileged_script_profile":"full_maintenance_v1",
|
||||
"execution_sid":"S-1-5-18","output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
|
||||
"execution_policy":"inherited","own_job_object_tree_bounded":true,"full_host_effects_not_contained":true,"full_host_authority":true,
|
||||
"cancel_or_fence_observed":output.cancelled,"termination_does_not_prove_absence_of_effects":interrupted});
|
||||
if windows_execution_profile == &Some(WindowsExecutionProfile::PowerShell51RemoteSigned) {
|
||||
evidence["windows_execution_profile"] = "powershell_51_remote_signed".into();
|
||||
evidence["execution_policy"] = "process_remote_signed_requested".into();
|
||||
evidence["execution_policy_requested"] = "RemoteSigned".into();
|
||||
evidence["execution_policy_scope"] = "process".into();
|
||||
}
|
||||
Ok(Outcome {
|
||||
state: if interrupted {
|
||||
"unknown"
|
||||
} else if success {
|
||||
"succeeded"
|
||||
} else {
|
||||
"failed"
|
||||
}
|
||||
.into(),
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
exit_code: output.exit_code,
|
||||
output_truncated: output.truncated,
|
||||
reboot_required: false,
|
||||
error_code: if success {
|
||||
""
|
||||
} else if interrupted {
|
||||
"SYSTEM_SCRIPT_INTERRUPTED_EFFECT_UNKNOWN"
|
||||
} else if output.truncated {
|
||||
"OUTPUT_LIMIT_REACHED"
|
||||
} else if !expected {
|
||||
"STDOUT_POSTCONDITION_FAILED"
|
||||
} else {
|
||||
"POWERSHELL_PROCESS_FAILED"
|
||||
}
|
||||
.into(),
|
||||
evidence,
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,12 @@ pub fn socket_for(
|
||||
general: Option<OsString>,
|
||||
apt: Option<OsString>,
|
||||
) -> Result<PathBuf> {
|
||||
if job.action.full_maintenance() {
|
||||
return Ok(PathBuf::from(
|
||||
std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
||||
.context("FULL_MAINTENANCE_SOCKET_NOT_CONFIGURED")?,
|
||||
));
|
||||
}
|
||||
select_socket(provider::is_apt_action(job), general, apt)
|
||||
}
|
||||
fn select_socket(
|
||||
@@ -216,6 +222,23 @@ pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result<
|
||||
rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds)
|
||||
}
|
||||
|
||||
pub fn invoke_with_control(
|
||||
binding: &Binding,
|
||||
job: &JobPayload,
|
||||
request: &Request,
|
||||
observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
if !job.action.full_maintenance() {
|
||||
return invoke(binding, job, request);
|
||||
}
|
||||
ensure!(
|
||||
crate::helper_sync::general_supported(binding, job),
|
||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
||||
);
|
||||
let socket = socket_for(job, None, None)?;
|
||||
rmm_privileged_helper::invoke_controlled(&socket, request, job.max_runtime_seconds, observe)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -354,6 +377,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -9,6 +9,7 @@ struct Endpoint {
|
||||
socket: PathBuf,
|
||||
profile: String,
|
||||
hash: String,
|
||||
binary_hash: Option<String>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Helpers {
|
||||
@@ -39,24 +40,44 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot {
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn general(binding: &Binding) -> Result<control::Response> {
|
||||
let socket = std::env::var_os("RMM_HELPER_SOCKET").context("NO_GENERAL_HELPER")?;
|
||||
let path = std::env::var_os("RMM_HELPER_POLICY_FILE").context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
fn general(binding: &Binding, full: bool) -> Result<control::Response> {
|
||||
let (socket_name, pin_name, profile) = if full {
|
||||
(
|
||||
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
||||
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
||||
"full_maintenance_v1",
|
||||
)
|
||||
} else {
|
||||
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general")
|
||||
};
|
||||
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
|
||||
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH");
|
||||
control::general_probe(Path::new(&socket), binding, &pin)
|
||||
}
|
||||
impl Helpers {
|
||||
pub fn configured(binding: &Binding) -> Result<Self> {
|
||||
let mut endpoints = vec![];
|
||||
if let Some(socket) = std::env::var_os("RMM_HELPER_SOCKET") {
|
||||
let path = std::env::var_os("RMM_HELPER_POLICY_FILE")
|
||||
.context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
endpoints.push(Endpoint {
|
||||
socket: socket.into(),
|
||||
profile: "general".into(),
|
||||
hash: pin.policy_sha256,
|
||||
});
|
||||
for (socket_name, pin_name, profile) in [
|
||||
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general"),
|
||||
(
|
||||
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
||||
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
||||
"full_maintenance_v1",
|
||||
),
|
||||
] {
|
||||
if let Some(socket) = std::env::var_os(socket_name) {
|
||||
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH");
|
||||
endpoints.push(Endpoint {
|
||||
socket: socket.into(),
|
||||
profile: profile.into(),
|
||||
hash: pin.policy_sha256,
|
||||
binary_hash: pin.helper_binary_sha256,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(socket) = std::env::var_os("RMM_APT_HELPER_SOCKET") {
|
||||
ensure!(
|
||||
@@ -70,6 +91,7 @@ impl Helpers {
|
||||
socket: socket.into(),
|
||||
profile: "apt_only".into(),
|
||||
hash: pin.provider_stack_sha256,
|
||||
binary_hash: None,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
@@ -79,7 +101,9 @@ impl Helpers {
|
||||
}
|
||||
fn validate(&self, e: &Endpoint, r: &control::Response) -> Result<()> {
|
||||
ensure!(
|
||||
r.profile == e.profile && r.policy_sha256 == e.hash,
|
||||
r.profile == e.profile
|
||||
&& r.policy_sha256 == e.hash
|
||||
&& r.helper_binary_sha256 == e.binary_hash,
|
||||
"HELPER_PIN_PROFILE_MISMATCH"
|
||||
);
|
||||
Ok(())
|
||||
@@ -153,13 +177,39 @@ impl Helpers {
|
||||
}
|
||||
}
|
||||
pub fn general_capabilities(binding: &Binding) -> Vec<String> {
|
||||
let mut caps = profile_capabilities(binding, false);
|
||||
caps.extend(profile_capabilities(binding, true));
|
||||
caps.sort();
|
||||
caps.dedup();
|
||||
caps
|
||||
}
|
||||
fn profile_capabilities(binding: &Binding, full: bool) -> Vec<String> {
|
||||
(|| -> Result<Vec<String>> {
|
||||
let response = general(binding)?;
|
||||
let response = general(binding, full)?;
|
||||
let policy = response.policy.context("NO_GENERAL_POLICY")?;
|
||||
let mut caps = vec![
|
||||
"helper.root.v1".into(),
|
||||
format!("helper.policy.sha256:{}", response.policy_sha256),
|
||||
];
|
||||
if full {
|
||||
ensure!(
|
||||
policy.schema_version == 2
|
||||
&& policy.profile == "full_maintenance_v1"
|
||||
&& policy.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]),
|
||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
||||
);
|
||||
let binary = policy
|
||||
.helper_binary_sha256
|
||||
.as_ref()
|
||||
.context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?;
|
||||
ensure!(
|
||||
response.helper_binary_sha256.as_ref() == Some(binary),
|
||||
"FULL_MAINTENANCE_BINARY_PROOF_REQUIRED"
|
||||
);
|
||||
caps.push(format!("helper.binary.sha256:{binary}"));
|
||||
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
|
||||
}
|
||||
let mut actions = vec![];
|
||||
if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
||||
actions.push("run_script");
|
||||
@@ -180,10 +230,22 @@ pub fn general_capabilities(binding: &Binding) -> Vec<String> {
|
||||
}
|
||||
pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
|
||||
(|| -> Result<bool> {
|
||||
let p = general(binding)?.policy.context("NO_GENERAL_POLICY")?;
|
||||
let p = general(binding, job.action.full_maintenance())?
|
||||
.policy
|
||||
.context("NO_GENERAL_POLICY")?;
|
||||
Ok(match &job.action {
|
||||
rmm_domain::jobs::Action::RunScript { interpreter, .. } => {
|
||||
p.allow_root_scripts
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| p.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
}))
|
||||
&& match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
|
||||
@@ -50,6 +50,7 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
inventory_tx: tokio::sync::mpsc::Sender<Result<(Vec<u8>, i64)>>,
|
||||
inventory_rx: tokio::sync::mpsc::Receiver<Result<(Vec<u8>, i64)>>,
|
||||
inventory_inflight: bool,
|
||||
running_cancels: std::collections::HashMap<(String, String), Arc<AtomicBool>>,
|
||||
sync: Option<reconcile::ClientSync>,
|
||||
sync_clock: C,
|
||||
helpers: Option<helper_sync::Helpers>,
|
||||
@@ -61,6 +62,7 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct EffectFence {
|
||||
running_generation: AtomicU64,
|
||||
generation: AtomicU64,
|
||||
deadline: AtomicI64,
|
||||
root: AtomicBool,
|
||||
@@ -80,6 +82,14 @@ fn report_closed_gate(error: &anyhow::Error) {
|
||||
}
|
||||
impl EffectFence {
|
||||
fn close(&self) {
|
||||
self.running_generation.store(0, Ordering::SeqCst);
|
||||
self.close_starts();
|
||||
}
|
||||
// A signed Sync/start lease authorizes NEW starts. Its natural expiry
|
||||
// cannot retroactively stop an approved bounded process (spec22.3).
|
||||
// Running effects instead observe their exact cancellation and current
|
||||
// connection generation; transport/signed refusal closes both fences.
|
||||
fn close_starts(&self) {
|
||||
self.generation.store(0, Ordering::SeqCst);
|
||||
self.root.store(false, Ordering::SeqCst);
|
||||
}
|
||||
@@ -117,7 +127,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
})
|
||||
}
|
||||
async fn start_sync(&mut self, wire: &wire_channel::Handle, generation: u64) -> Result<()> {
|
||||
self.fence.close();
|
||||
self.fence.close_starts();
|
||||
let helpers = self.helpers.clone();
|
||||
let snapshot = tokio::task::spawn_blocking(move || match helpers {
|
||||
Some(h) => h.snapshot(generation),
|
||||
@@ -182,6 +192,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.as_ref()
|
||||
.and_then(|s| s.validity_deadline())
|
||||
.context("SIGNED_LEASE_REQUIRED")?;
|
||||
self.fence
|
||||
.running_generation
|
||||
.store(generation, Ordering::SeqCst);
|
||||
self.fence
|
||||
.deadline
|
||||
.store(deadline.timestamp_millis(), Ordering::SeqCst);
|
||||
@@ -189,6 +202,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.root
|
||||
.store(self.ready(generation, true), Ordering::SeqCst);
|
||||
self.fence.generation.store(generation, Ordering::SeqCst);
|
||||
} else {
|
||||
// A valid signed refusal is a fence too, not just parse/I/O errors.
|
||||
self.fence.close();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -322,6 +338,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}));
|
||||
jobs::event(&tx, &envelope)?;
|
||||
tx.commit()?;
|
||||
let cancellation = Arc::new(AtomicBool::new(false));
|
||||
self.running_cancels.insert(
|
||||
(offer.job_id.clone(), offer.attempt_id.clone()),
|
||||
cancellation.clone(),
|
||||
);
|
||||
let completed = self.completed_tx.clone();
|
||||
let clock = self.clock.clone();
|
||||
let fence = self.fence.clone();
|
||||
@@ -334,7 +355,16 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
{
|
||||
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
|
||||
} else if job.execution_identity == "root" {
|
||||
apt::invoke(&binding, &job, &request).unwrap_or_else(|_| {
|
||||
apt::invoke_with_control(&binding, &job, &request, || {
|
||||
ensure!(
|
||||
!cancellation.load(Ordering::SeqCst)
|
||||
&& fence.running_generation.load(Ordering::SeqCst) == generation
|
||||
&& clock.trusted(),
|
||||
"SCRIPT_RUNNING_CANCEL_OR_FENCE"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|_| {
|
||||
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
|
||||
})
|
||||
} else {
|
||||
@@ -537,6 +567,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
rusqlite::params![cancel.job_id,cancel.attempt_id], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?
|
||||
};
|
||||
if let Some((bytes,state,grant)) = row {
|
||||
if let Some(flag) = self.running_cancels.get(&(cancel.job_id.clone(),cancel.attempt_id.clone())) { flag.store(true,Ordering::SeqCst); }
|
||||
self.db.execute("UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2", rusqlite::params![cancel.job_id,cancel.attempt_id])?;
|
||||
if state == "accepted" { self.record(generation, &JobOffer::decode(bytes.as_slice())?, &grant, jobs::no_start("cancelled", "CANCELLED_BEFORE_START"))?; }
|
||||
// Running script cancellation is not confirmed by an
|
||||
@@ -549,6 +580,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
}
|
||||
Some((offer, grant, outcome)) = self.completed_rx.recv() => {
|
||||
self.running_cancels.remove(&(offer.job_id.clone(),offer.attempt_id.clone()));
|
||||
// First preserve the original completion without unlocking.
|
||||
// A startup can replay it if the journal transaction is lost.
|
||||
let state = outcome.state.clone();
|
||||
@@ -807,6 +839,7 @@ async fn main() -> Result<()> {
|
||||
inventory_tx,
|
||||
inventory_rx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync,
|
||||
sync_clock: reconcile::NativeClock::default(),
|
||||
helpers,
|
||||
|
||||
@@ -51,6 +51,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("fixture only; never executed\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
@@ -139,6 +140,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
inventory_tx: itx,
|
||||
inventory_rx: irx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync: Some(reconcile::ClientSync::new(binding.clone())),
|
||||
sync_clock: Clock(true),
|
||||
helpers: None,
|
||||
@@ -525,6 +527,7 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
|
||||
inventory_tx: itx,
|
||||
inventory_rx: irx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync: Some(reconcile::ClientSync::new(binding)),
|
||||
sync_clock: Clock(trusted),
|
||||
helpers: None,
|
||||
|
||||
@@ -595,6 +595,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Reproducible Rust-codec fixtures consumed directly by the WebUI tests.
|
||||
use rmm_domain::jobs::*;
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
fn main() {
|
||||
let cases = [
|
||||
(
|
||||
"legacy_linux_agent",
|
||||
"agent_service",
|
||||
"posix_sh",
|
||||
"printf 'hello\\n'\n",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"linux_root_full",
|
||||
"root",
|
||||
"posix_sh",
|
||||
"id\nprintf 'root stdout\\n'\nprintf 'root stderr\\n' >&2\n",
|
||||
None,
|
||||
Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
),
|
||||
(
|
||||
"windows_system_full",
|
||||
"system",
|
||||
"powershell",
|
||||
"Write-Output 'SYSTEM stdout'\r\n[Console]::Error.WriteLine('SYSTEM stderr')\r\n",
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
),
|
||||
];
|
||||
let values: Vec<_> = cases.into_iter().enumerate().map(|(index, (name, identity, interpreter, script, windows_execution_profile, privileged_script_profile))| {
|
||||
let tenant = Uuid::from_u128(1);
|
||||
let job = JobPayload {
|
||||
schema_version: 1, tenant_id: tenant, asset_id: Uuid::from_u128(2), agent_id: Uuid::from_u128(3),
|
||||
enrollment_generation: 1, assignment_version: 1, job_id: Uuid::from_u128(4+index as u128*10), attempt_id: Uuid::from_u128(5+index as u128*10),
|
||||
action: Action::RunScript { interpreter: interpreter.into(), script_utf8: script.into(), arguments: vec![], expected_stdout: None, windows_execution_profile, privileged_script_profile },
|
||||
execution_identity: identity.into(), not_before: "2026-11-14T12:00:00Z".parse().unwrap(), start_before: "2026-11-14T13:00:00Z".parse().unwrap(), max_runtime_seconds: 30, max_output_bytes: 4096,
|
||||
};
|
||||
let job_bytes = encode(&job).unwrap();
|
||||
let job_hash = hash(&job_bytes);
|
||||
let script_sha256 = hash(script.as_bytes());
|
||||
let plan = PlanPayload { schema_version: 1, plan_id: Uuid::from_u128(6+index as u128*10), tenant_id: tenant, principal: "simulated-dev-script-console".into(), reason: format!("Codec fixture: {name}; no native execution"), jobs: vec![PlannedJob { payload: job, job_payload_hash: job_hash.clone(), script_sha256: Some(script_sha256.clone()) }], max_parallel: 1, halt_after_failures: 1, recipe_references: vec![], artifact_references: vec![] };
|
||||
let bytes = encode(&plan).unwrap();
|
||||
json!({"name":name,"plan_payload_bytes":bytes,"plan_hash":hash(&bytes),"job_payload_bytes":job_bytes,"job_payload_hash":job_hash,"script_sha256":script_sha256})
|
||||
}).collect();
|
||||
println!("{}", serde_json::to_string_pretty(&values).unwrap());
|
||||
}
|
||||
+240
-3
@@ -48,6 +48,61 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit authority for a separately qualified, fully privileged script.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
pub enum PrivilegedScriptProfile {
|
||||
#[serde(rename = "full_maintenance_v1")]
|
||||
FullMaintenanceV1,
|
||||
}
|
||||
pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1";
|
||||
pub fn deserialize_privileged_script_profile<'de, D>(
|
||||
d: D,
|
||||
) -> Result<Option<PrivilegedScriptProfile>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(d)?;
|
||||
match value.as_str() {
|
||||
"full_maintenance_v1" => Ok(Some(PrivilegedScriptProfile::FullMaintenanceV1)),
|
||||
_ => Err(serde::de::Error::unknown_variant(
|
||||
&value,
|
||||
&["full_maintenance_v1"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// Optional metadata pins preserve old codecs when missing, reject null or
|
||||
/// noncanonical digests when explicitly supplied.
|
||||
pub fn deserialize_optional_sha256<'de, D>(d: D) -> Result<Option<String>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(d)?;
|
||||
if value.len() != 64
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || b"abcdef".contains(&b))
|
||||
{
|
||||
return Err(serde::de::Error::custom("lowercase SHA256 required"));
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
/// Policy lists are strict when present; omission is deny, never a wildcard.
|
||||
pub fn deserialize_script_profiles<'de, D>(
|
||||
d: D,
|
||||
) -> Result<Option<Vec<PrivilegedScriptProfile>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let values = Vec::<String>::deserialize(d)?;
|
||||
if values.len() != 1 || values[0] != "full_maintenance_v1" {
|
||||
return Err(serde::de::Error::custom(
|
||||
"exact full_maintenance_v1 profile required",
|
||||
));
|
||||
}
|
||||
Ok(Some(vec![PrivilegedScriptProfile::FullMaintenanceV1]))
|
||||
}
|
||||
|
||||
/// Missing preserves Linux codecs; explicit null/nonobject is never a manifest.
|
||||
pub fn deserialize_windows_msi_manifest<'de, D>(
|
||||
deserializer: D,
|
||||
@@ -74,6 +129,13 @@ pub enum Action {
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_privileged_script_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "PrivilegedScriptProfile")]
|
||||
privileged_script_profile: Option<PrivilegedScriptProfile>,
|
||||
},
|
||||
RefreshInventory {
|
||||
scope: String,
|
||||
@@ -160,6 +222,7 @@ impl Action {
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} => {
|
||||
matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell")
|
||||
&& (windows_execution_profile.is_none() || interpreter == "powershell")
|
||||
@@ -296,6 +359,26 @@ impl Action {
|
||||
(matches!(self,Self::SetServiceState{state,..} if matches!(state.as_str(),"running"|"stopped"))
|
||||
&& self.validate())
|
||||
|| (identity == "system" && self.windows_msi().is_some() && self.validate())
|
||||
|| (identity == "system"
|
||||
&& self.full_maintenance()
|
||||
&& self.script_platform() == Some("windows")
|
||||
&& self.validate())
|
||||
}
|
||||
pub fn full_maintenance(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::RunScript {
|
||||
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
pub fn valid_execution_identity(&self, identity: &str) -> bool {
|
||||
!self.full_maintenance()
|
||||
|| matches!(
|
||||
(identity, self.script_platform()),
|
||||
("root", Some("linux")) | ("system", Some("windows"))
|
||||
)
|
||||
}
|
||||
pub fn is_windows_event_log_fixture(&self) -> bool {
|
||||
matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE)
|
||||
@@ -304,6 +387,14 @@ impl Action {
|
||||
/// 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)
|
||||
&& (!self.full_maintenance()
|
||||
|| (output_bytes <= 65536
|
||||
&& runtime_seconds
|
||||
<= if self.script_platform() == Some("windows") {
|
||||
120
|
||||
} else {
|
||||
300
|
||||
}))
|
||||
&& (self.windows_msi().is_none()
|
||||
|| ((10..=120).contains(&runtime_seconds)
|
||||
&& (1024..=65536).contains(&output_bytes)))
|
||||
@@ -325,11 +416,23 @@ impl Action {
|
||||
}
|
||||
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
|
||||
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
|
||||
if identity == "system" && !self.valid_helper_denial_shape(identity) {
|
||||
if !self.valid_execution_identity(identity)
|
||||
|| (identity == "system" && !self.valid_helper_denial_shape(identity))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
if !has(self.name()) {
|
||||
if !has(self.name())
|
||||
|| (self.full_maintenance()
|
||||
&& !(has(FULL_MAINTENANCE_CAPABILITY)
|
||||
&& has("rmm.sync.v1")
|
||||
&& has(&format!("{}:run_script", identity))
|
||||
&& has(if identity == "root" {
|
||||
"helper.root.v1"
|
||||
} else {
|
||||
"helper.system.v1"
|
||||
})))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
@@ -338,7 +441,7 @@ impl Action {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} if interpreter == "powershell" => {
|
||||
identity == "agent_service"
|
||||
(identity == "agent_service" || (identity == "system" && self.full_maintenance()))
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
@@ -643,6 +746,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let mut all = caps;
|
||||
all.extend(["run_script".into(), "script.powershell/1".into()]);
|
||||
@@ -653,6 +757,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let reboot = Action::Reboot {
|
||||
reason: "fixed test".into(),
|
||||
@@ -675,6 +780,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
@@ -744,6 +850,136 @@ mod tests {
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_is_explicit_strict_identity_and_capability_bound() {
|
||||
let legacy = br#"{"action":"run_script","interpreter":"posix_sh","script_utf8":"id\n","arguments":[],"expected_stdout":null}"#;
|
||||
let mut action: Action = serde_json::from_slice(legacy).unwrap();
|
||||
assert_eq!(encode(&action).unwrap(), legacy);
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!({"FullMaintenanceV1":null}),
|
||||
serde_json::json!("latest"),
|
||||
serde_json::json!(true),
|
||||
] {
|
||||
let mut input: serde_json::Value = serde_json::from_slice(legacy).unwrap();
|
||||
input["privileged_script_profile"] = value;
|
||||
assert!(serde_json::from_value::<Action>(input).is_err());
|
||||
}
|
||||
if let Action::RunScript {
|
||||
privileged_script_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*privileged_script_profile = Some(PrivilegedScriptProfile::FullMaintenanceV1);
|
||||
}
|
||||
assert!(action.validate());
|
||||
assert!(action.valid_execution_identity("root"));
|
||||
assert!(!action.valid_execution_identity("agent_service"));
|
||||
assert!(!action.valid_execution_identity("system"));
|
||||
assert!(action.valid_job_limits(300, 65536));
|
||||
assert!(!action.valid_job_limits(301, 65536));
|
||||
assert!(!action.valid_job_limits(300, 65537));
|
||||
let caps: Vec<String> = [
|
||||
"linux.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.root.v1",
|
||||
"run_script",
|
||||
"root:run_script",
|
||||
FULL_MAINTENANCE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert!(action.available_for("root", &caps));
|
||||
for missing in &caps {
|
||||
assert!(
|
||||
!action.available_for(
|
||||
"root",
|
||||
&caps
|
||||
.iter()
|
||||
.filter(|c| *c != missing)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(!action.available_for("agent_service", &caps));
|
||||
if let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*interpreter = "powershell".into();
|
||||
*script_utf8 = "Write-Output 'hi'\r\n".into();
|
||||
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
}
|
||||
assert!(action.valid_helper_denial_shape("system"));
|
||||
assert!(!action.valid_helper_denial_shape("root"));
|
||||
assert!(action.valid_job_limits(120, 65536));
|
||||
assert!(!action.valid_job_limits(121, 65536));
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.system.v1",
|
||||
"run_script",
|
||||
"system:run_script",
|
||||
"script.powershell/1",
|
||||
"script.powershell.process_remote_signed/1",
|
||||
FULL_MAINTENANCE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert!(action.available_for("system", &caps));
|
||||
for missing in &caps {
|
||||
assert!(
|
||||
!action.available_for(
|
||||
"system",
|
||||
&caps
|
||||
.iter()
|
||||
.filter(|c| *c != missing)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(!action.available_for("root", &caps));
|
||||
}
|
||||
#[test]
|
||||
fn script_console_golden_plans_use_actual_rust_codec() {
|
||||
let cases: Vec<serde_json::Value> = serde_json::from_str(include_str!(
|
||||
"../../../tests/script_console/codec-golden.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(cases.len(), 3);
|
||||
for case in cases {
|
||||
let bytes: Vec<u8> =
|
||||
serde_json::from_value(case["plan_payload_bytes"].clone()).unwrap();
|
||||
let plan: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(encode(&plan).unwrap(), bytes);
|
||||
assert_eq!(hash(&bytes), case["plan_hash"]);
|
||||
let job = &plan.jobs[0];
|
||||
let job_bytes = encode(&job.payload).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&job_bytes).unwrap(),
|
||||
case["job_payload_bytes"]
|
||||
);
|
||||
assert_eq!(hash(&job_bytes), job.job_payload_hash);
|
||||
assert_eq!(job.job_payload_hash, case["job_payload_hash"]);
|
||||
assert!(job.payload.action.validate());
|
||||
assert!(
|
||||
job.payload
|
||||
.action
|
||||
.valid_execution_identity(&job.payload.execution_identity)
|
||||
);
|
||||
let Action::RunScript { script_utf8, .. } = &job.payload.action else {
|
||||
panic!("script fixture")
|
||||
};
|
||||
assert_eq!(hash(script_utf8.as_bytes()), case["script_sha256"]);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn codec_golden_and_exact_script_bytes() {
|
||||
let a = Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
@@ -751,6 +987,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
assert_eq!(
|
||||
String::from_utf8(encode(&a).unwrap()).unwrap(),
|
||||
|
||||
@@ -482,6 +482,7 @@ fn signed_request() -> (
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now - chrono::Duration::seconds(1),
|
||||
|
||||
@@ -69,6 +69,18 @@ pub struct Policy {
|
||||
pub allowed_services: Vec<String>,
|
||||
pub allow_root_scripts: bool,
|
||||
pub allow_reboot: bool,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
impl Policy {
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
@@ -90,6 +102,12 @@ pub struct Response {
|
||||
pub ledger_inode: u64,
|
||||
pub lock_device: u64,
|
||||
pub lock_inode: u64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -98,6 +116,12 @@ pub struct GeneralPin {
|
||||
pub profile: String,
|
||||
pub identity: Identity,
|
||||
pub policy_sha256: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
impl GeneralPin {
|
||||
pub fn read(path: &Path, binding: &Binding) -> Result<Self> {
|
||||
@@ -105,8 +129,12 @@ impl GeneralPin {
|
||||
ensure!(fs::metadata(path)?.len() <= 8192, "POLICY_PIN_LIMIT");
|
||||
let pin: Self = serde_json::from_slice(&fs::read(path)?)?;
|
||||
ensure!(
|
||||
pin.schema_version == 1
|
||||
((pin.schema_version == 1
|
||||
&& pin.profile == "general"
|
||||
&& pin.helper_binary_sha256.is_none())
|
||||
|| (pin.schema_version == 2
|
||||
&& pin.profile == "full_maintenance_v1"
|
||||
&& pin.helper_binary_sha256.as_ref().is_some_and(|h| digest(h))))
|
||||
&& pin.identity == Identity::from_binding(binding)?
|
||||
&& digest(&pin.policy_sha256),
|
||||
"POLICY_PIN_BINDING"
|
||||
@@ -199,9 +227,20 @@ pub fn validate_response(request: &Request, response: &Response, binding: &Bindi
|
||||
&& response.challenge == challenge
|
||||
&& &response.identity == identity
|
||||
&& response.identity == Identity::from_binding(binding)?
|
||||
&& matches!(response.profile.as_str(), "general" | "apt_only")
|
||||
&& matches!(
|
||||
response.profile.as_str(),
|
||||
"general" | "apt_only" | "full_maintenance_v1"
|
||||
)
|
||||
&& response.ledger_inode != 0
|
||||
&& response.lock_inode != 0,
|
||||
&& response.lock_inode != 0
|
||||
&& if response.profile == "full_maintenance_v1" {
|
||||
response
|
||||
.helper_binary_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|h| digest(h))
|
||||
} else {
|
||||
response.helper_binary_sha256.is_none()
|
||||
},
|
||||
"HELPER_CONTROL_RESPONSE_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
@@ -214,8 +253,23 @@ pub fn general_probe(socket: &Path, binding: &Binding, pin: &GeneralPin) -> Resu
|
||||
let response = call(socket, binding, &request)?;
|
||||
let policy = response.policy.as_ref().context("GENERAL_POLICY_MISSING")?;
|
||||
ensure!(
|
||||
response.profile == "general"
|
||||
&& policy.profile == "general"
|
||||
response.profile == pin.profile
|
||||
&& policy.profile == pin.profile
|
||||
&& ((policy.schema_version == 1
|
||||
&& policy.profile == "general"
|
||||
&& policy.allowed_script_profiles.is_none()
|
||||
&& policy.helper_binary_sha256.is_none()
|
||||
&& pin.helper_binary_sha256.is_none())
|
||||
|| (policy.schema_version == 2
|
||||
&& policy.profile == "full_maintenance_v1"
|
||||
&& policy.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& policy.helper_binary_sha256 == pin.helper_binary_sha256
|
||||
&& response.helper_binary_sha256 == pin.helper_binary_sha256
|
||||
&& pin.helper_binary_sha256.is_some()
|
||||
&& policy.allow_root_scripts
|
||||
&& !policy.allow_reboot
|
||||
&& policy.allowed_services.is_empty()))
|
||||
&& response.policy_sha256 == pin.policy_sha256
|
||||
&& policy.sha256()? == pin.policy_sha256
|
||||
&& policy.identity == pin.identity,
|
||||
@@ -264,8 +318,21 @@ mod tests {
|
||||
ledger_inode: 2,
|
||||
lock_device: 1,
|
||||
lock_inode: 3,
|
||||
helper_binary_sha256: None,
|
||||
};
|
||||
validate_response(&q, &r, &b).unwrap();
|
||||
let legacy = serde_json::to_value(&r).unwrap();
|
||||
assert!(legacy.get("helper_binary_sha256").is_none());
|
||||
let mut null = legacy.clone();
|
||||
null["helper_binary_sha256"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<Response>(null).is_err());
|
||||
r.profile = "full_maintenance_v1".into();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.helper_binary_sha256 = Some("ab".repeat(32));
|
||||
validate_response(&q, &r, &b).unwrap();
|
||||
r.profile = "general".into();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.helper_binary_sha256 = None;
|
||||
r.challenge = Uuid::new_v4();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.challenge = challenge;
|
||||
@@ -313,6 +380,8 @@ mod tests {
|
||||
allowed_services: vec!["rmm-acceptance.service".into()],
|
||||
allow_root_scripts: false,
|
||||
allow_reboot: false,
|
||||
allowed_script_profiles: None,
|
||||
helper_binary_sha256: None,
|
||||
};
|
||||
let old = p.sha256().unwrap();
|
||||
let mut changed = p.clone();
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Root observes its own *running* executable. An agent-readable configured
|
||||
//! pathname or a build claim is never substituted for this descriptor.
|
||||
use anyhow::{Result, ensure};
|
||||
use openssl::sha::Sha256;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Seek, SeekFrom},
|
||||
os::unix::fs::MetadataExt,
|
||||
};
|
||||
|
||||
pub struct RunningImage {
|
||||
file: File,
|
||||
expected: String,
|
||||
}
|
||||
impl RunningImage {
|
||||
pub fn current(expected: &str) -> Result<Self> {
|
||||
let mut value = Self {
|
||||
file: File::open("/proc/self/exe")?,
|
||||
expected: expected.into(),
|
||||
};
|
||||
value.verify()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub fn verify(&mut self) -> Result<String> {
|
||||
let before = self.file.metadata()?;
|
||||
ensure!(
|
||||
before.is_file()
|
||||
&& before.uid() == 0
|
||||
&& before.mode() & 0o022 == 0
|
||||
&& before.len() > 0
|
||||
&& before.len() <= 128 * 1024 * 1024,
|
||||
"RUNNING_HELPER_IMAGE_METADATA"
|
||||
);
|
||||
let identity = |m: &std::fs::Metadata| {
|
||||
(
|
||||
m.dev(),
|
||||
m.ino(),
|
||||
m.len(),
|
||||
m.uid(),
|
||||
m.mode(),
|
||||
m.mtime(),
|
||||
m.mtime_nsec(),
|
||||
m.ctime(),
|
||||
m.ctime_nsec(),
|
||||
)
|
||||
};
|
||||
self.file.seek(SeekFrom::Start(0))?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut buffer = [0u8; 65536];
|
||||
let mut length = 0u64;
|
||||
loop {
|
||||
let n = self.file.read(&mut buffer)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
length += n as u64;
|
||||
ensure!(
|
||||
length <= before.len(),
|
||||
"RUNNING_HELPER_IMAGE_LENGTH_CHANGED"
|
||||
);
|
||||
hash.update(&buffer[..n]);
|
||||
}
|
||||
let actual = hex::encode(hash.finish());
|
||||
ensure!(
|
||||
length == before.len()
|
||||
&& identity(&before) == identity(&self.file.metadata()?)
|
||||
&& actual == self.expected,
|
||||
"RUNNING_HELPER_IMAGE_PIN_MISMATCH"
|
||||
);
|
||||
Ok(actual)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn actual_running_image_is_independent_of_a_claimed_path_or_digest() {
|
||||
let metadata = std::fs::metadata("/proc/self/exe").unwrap();
|
||||
let bytes = std::fs::read("/proc/self/exe").unwrap();
|
||||
let actual = hex::encode(openssl::sha::sha256(&bytes));
|
||||
if metadata.uid() == 0 && metadata.mode() & 0o022 == 0 {
|
||||
let mut image = RunningImage::current(&actual).unwrap();
|
||||
assert_eq!(image.verify().unwrap(), actual);
|
||||
} else {
|
||||
// An untrusted-owned/writable executable must fail even if its
|
||||
// content hash is correct. This is a tested denial, never a skip.
|
||||
assert!(RunningImage::current(&actual).is_err());
|
||||
}
|
||||
assert!(RunningImage::current(&"00".repeat(32)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -124,13 +124,17 @@ pub fn save_start(
|
||||
}
|
||||
|
||||
pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script};
|
||||
script_controlled(job, || Ok(()))
|
||||
}
|
||||
pub fn script_controlled(job: &JobPayload, observe: impl FnMut() -> Result<()>) -> Result<Outcome> {
|
||||
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
|
||||
let rmm_domain::jobs::Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile: None,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("NOT_SCRIPT")
|
||||
@@ -147,14 +151,15 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
std::time::Duration::from_secs(job.max_runtime_seconds.into()),
|
||||
job.max_output_bytes as usize,
|
||||
)?;
|
||||
let output = run_script(&request)?;
|
||||
let output = run_script_controlled(&request, observe)?;
|
||||
let passed = output.code == Some(0)
|
||||
&& !output.timed_out
|
||||
&& !output.interrupted
|
||||
&& expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| !output.truncated && output.stdout == s.as_bytes());
|
||||
Ok(Outcome {
|
||||
state: if output.timed_out || output.code.is_none() {
|
||||
state: if output.timed_out || output.interrupted || output.code.is_none() {
|
||||
"unknown"
|
||||
} else if passed {
|
||||
"succeeded"
|
||||
@@ -167,9 +172,11 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
exit_code: output.code,
|
||||
output_truncated: output.truncated,
|
||||
reboot_required: false,
|
||||
evidence: serde_json::json!({"postconditions_passed":passed}),
|
||||
evidence: serde_json::json!({"postconditions_passed":passed,"script_sha256":rmm_domain::jobs::hash(script_utf8.as_bytes()),"privileged_script_profile":if job.action.full_maintenance(){Some("full_maintenance_v1")}else{None},"execution_uid":unsafe{libc::geteuid()},"output_encoding":"raw_native_bytes","cancel_or_fence_observed":output.interrupted,"termination_does_not_prove_absence_of_effects":output.interrupted||output.timed_out}),
|
||||
error_code: if passed {
|
||||
""
|
||||
} else if output.interrupted {
|
||||
"CANCEL_OR_FENCE_EFFECT_UNKNOWN"
|
||||
} else if output.timed_out {
|
||||
"TIMEOUT_EFFECT_UNKNOWN"
|
||||
} else {
|
||||
@@ -210,6 +217,14 @@ pub struct TrustedClock {
|
||||
/// Local client authenticates the root process as well as the root-owned socket.
|
||||
/// A malicious same-user Unix server must not be able to forge helper success.
|
||||
pub fn invoke(socket: &Path, request: &Request, max_runtime_seconds: u32) -> Result<Outcome> {
|
||||
invoke_controlled(socket, request, max_runtime_seconds, || Ok(()))
|
||||
}
|
||||
pub fn invoke_controlled(
|
||||
socket: &Path,
|
||||
request: &Request,
|
||||
max_runtime_seconds: u32,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
os::{
|
||||
@@ -256,16 +271,50 @@ pub fn invoke(socket: &Path, request: &Request, max_runtime_seconds: u32) -> Res
|
||||
stream.set_read_timeout(Some(Duration::from_secs(
|
||||
u64::from(max_runtime_seconds) + 10,
|
||||
)))?;
|
||||
observe()?;
|
||||
let bytes = serde_json::to_vec(request)?;
|
||||
ensure!(bytes.len() <= 512 * 1024, "HELPER_REQUEST_SIZE");
|
||||
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
||||
stream.write_all(&bytes)?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(50)))?;
|
||||
let started = std::time::Instant::now();
|
||||
let mut closed = false;
|
||||
let mut read = |stream: &mut UnixStream, mut target: &mut [u8]| -> Result<()> {
|
||||
while !target.is_empty() {
|
||||
if !closed && observe().is_err() {
|
||||
// Half-close only this exact authenticated request stream. The
|
||||
// helper treats its EOF as cancellation; result reads continue.
|
||||
stream.shutdown(std::net::Shutdown::Write)?;
|
||||
closed = true;
|
||||
}
|
||||
ensure!(
|
||||
started.elapsed() < Duration::from_secs(u64::from(max_runtime_seconds) + 10),
|
||||
"HELPER_RESPONSE_TIMEOUT_EFFECT_UNKNOWN"
|
||||
);
|
||||
match stream.read(target) {
|
||||
Ok(0) => anyhow::bail!("HELPER_RESPONSE_CLOSED_EFFECT_UNKNOWN"),
|
||||
Ok(n) => target = &mut target[n..],
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
| std::io::ErrorKind::TimedOut
|
||||
| std::io::ErrorKind::Interrupted
|
||||
) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let mut length = [0; 4];
|
||||
stream.read_exact(&mut length)?;
|
||||
read(&mut stream, &mut length)?;
|
||||
let length = u32::from_be_bytes(length) as usize;
|
||||
ensure!(length <= 2 * 1024 * 1024, "HELPER_RESPONSE_SIZE");
|
||||
let mut bytes = vec![0; length];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
read(&mut stream, &mut bytes)?;
|
||||
let outcome: Outcome = serde_json::from_slice(&bytes)?;
|
||||
ensure!(
|
||||
outcome.stdout.len() + outcome.stderr.len() <= 262144,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod image;
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::jobs::Action;
|
||||
use rmm_privileged_helper::{
|
||||
@@ -33,6 +34,16 @@ struct Config {
|
||||
allowed_services: Vec<String>,
|
||||
allow_reboot: bool,
|
||||
allow_root_scripts: bool,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
helper_binary_sha256: Option<String>,
|
||||
#[serde(default)]
|
||||
apt_provider: Option<rmm_privileged_helper::apt::ProviderConfig>,
|
||||
}
|
||||
@@ -42,16 +53,28 @@ enum HelperProfile {
|
||||
#[default]
|
||||
General,
|
||||
AptOnly,
|
||||
FullMaintenanceV1,
|
||||
}
|
||||
impl Config {
|
||||
fn general_policy(&self) -> Result<control::Policy> {
|
||||
Ok(control::Policy {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
schema_version: if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
profile: if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
"full_maintenance_v1"
|
||||
} else {
|
||||
"general"
|
||||
}
|
||||
.into(),
|
||||
identity: rmm_privileged_helper::readiness::Identity::from_binding(&self.binding)?,
|
||||
allowed_services: self.allowed_services.clone(),
|
||||
allow_root_scripts: self.allow_root_scripts,
|
||||
allow_reboot: self.allow_reboot,
|
||||
allowed_script_profiles: self.allowed_script_profiles.clone(),
|
||||
helper_binary_sha256: self.helper_binary_sha256.clone(),
|
||||
})
|
||||
}
|
||||
fn validate_profile(&self) -> Result<()> {
|
||||
@@ -60,7 +83,19 @@ impl Config {
|
||||
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE),
|
||||
"SHARED_HELPER_LEDGER_REQUIRED"
|
||||
);
|
||||
if self.profile == HelperProfile::AptOnly {
|
||||
if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
ensure!(
|
||||
self.apt_provider.is_none()
|
||||
&& self.allowed_services.is_empty()
|
||||
&& !self.allow_reboot
|
||||
&& self.allow_root_scripts
|
||||
&& self.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& self.socket.as_path()
|
||||
!= std::path::Path::new(rmm_privileged_helper::readiness::SOCKET),
|
||||
"FULL_MAINTENANCE_PROFILE"
|
||||
);
|
||||
} else if self.profile == HelperProfile::AptOnly {
|
||||
ensure!(
|
||||
self.agent_uid == 993
|
||||
&& self.socket.as_path()
|
||||
@@ -79,6 +114,19 @@ impl Config {
|
||||
"GENERAL_HELPER_CANNOT_RUN_APT"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
self.profile == HelperProfile::FullMaintenanceV1
|
||||
|| self.allowed_script_profiles.is_none(),
|
||||
"FULL_MAINTENANCE_EXPLICIT_PROFILE_REQUIRED"
|
||||
);
|
||||
ensure!(
|
||||
if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
self.helper_binary_sha256.is_some()
|
||||
} else {
|
||||
self.helper_binary_sha256.is_none()
|
||||
},
|
||||
"FULL_MAINTENANCE_BINARY_PIN_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -138,9 +186,21 @@ fn policy(config: &Config, job: &rmm_domain::jobs::JobPayload) -> Result<()> {
|
||||
config.profile != HelperProfile::AptOnly,
|
||||
"APT_ONLY_CROSS_ACTION_DENIED"
|
||||
);
|
||||
ensure!(
|
||||
config.profile != HelperProfile::FullMaintenanceV1 || job.action.full_maintenance(),
|
||||
"FULL_MAINTENANCE_ONLY_SCRIPT"
|
||||
);
|
||||
match &job.action {
|
||||
Action::RunScript { interpreter, .. } => {
|
||||
ensure!(config.allow_root_scripts, "ROOT_SCRIPT_DENIED");
|
||||
ensure!(
|
||||
job.action.full_maintenance()
|
||||
== (config.profile == HelperProfile::FullMaintenanceV1)
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| (job.max_runtime_seconds <= 300 && job.max_output_bytes <= 65536)),
|
||||
"ROOT_SCRIPT_PROFILE_DENIED"
|
||||
);
|
||||
let available = match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
@@ -267,6 +327,7 @@ fn handle(
|
||||
clock: &rmm_privileged_helper::TrustedClock,
|
||||
sync: &mut reconcile::HelperSync,
|
||||
sync_clock: &reconcile::NativeClock,
|
||||
mut image: Option<&mut image::RunningImage>,
|
||||
) -> Result<()> {
|
||||
use rusqlite::OptionalExtension;
|
||||
peer_allowed(stream, config.agent_uid)?;
|
||||
@@ -278,6 +339,11 @@ fn handle(
|
||||
ensure!(size <= 8 * 1024 * 1024, "REQUEST_SIZE");
|
||||
let mut bytes = vec![0; size];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
let binary_sha256 = image.as_mut().map(|i| i.verify()).transpose()?;
|
||||
ensure!(
|
||||
binary_sha256 == config.helper_binary_sha256,
|
||||
"RUNNING_HELPER_BINARY_CHANGED"
|
||||
);
|
||||
let request: Request = match serde_json::from_slice::<Incoming>(&bytes)? {
|
||||
Incoming::Job(request) => {
|
||||
ensure!(size <= 512 * 1024, "JOB_REQUEST_SIZE");
|
||||
@@ -328,11 +394,11 @@ fn handle(
|
||||
unlocked = applied.unlocked_grants;
|
||||
}
|
||||
control::Request::Policy { .. } => ensure!(
|
||||
config.profile == HelperProfile::General,
|
||||
config.profile != HelperProfile::AptOnly,
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
),
|
||||
}
|
||||
let general = config.profile == HelperProfile::General;
|
||||
let general = config.profile != HelperProfile::AptOnly;
|
||||
let policy = if general {
|
||||
Some(config.general_policy()?)
|
||||
} else {
|
||||
@@ -355,7 +421,14 @@ fn handle(
|
||||
schema_version: 1,
|
||||
challenge,
|
||||
identity: identity.clone(),
|
||||
profile: if general { "general" } else { "apt_only" }.into(),
|
||||
profile: if config.profile == HelperProfile::FullMaintenanceV1 {
|
||||
"full_maintenance_v1"
|
||||
} else if general {
|
||||
"general"
|
||||
} else {
|
||||
"apt_only"
|
||||
}
|
||||
.into(),
|
||||
policy_sha256,
|
||||
policy,
|
||||
snapshot,
|
||||
@@ -364,6 +437,7 @@ fn handle(
|
||||
ledger_inode: ledger.ino(),
|
||||
lock_device: lock.dev(),
|
||||
lock_inode: lock.ino(),
|
||||
helper_binary_sha256: binary_sha256.clone(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&response)?;
|
||||
ensure!(bytes.len() <= 8 * 1024 * 1024, "CONTROL_RESPONSE_LIMIT");
|
||||
@@ -441,6 +515,10 @@ fn handle(
|
||||
if let Some(apt) = &apt {
|
||||
apt.verify_retry_history(db)?;
|
||||
}
|
||||
ensure!(
|
||||
image.as_mut().map(|i| i.verify()).transpose()? == config.helper_binary_sha256,
|
||||
"RUNNING_HELPER_BINARY_CHANGED"
|
||||
);
|
||||
rmm_privileged_helper::begin_execution(db, &permit, &request)?;
|
||||
let mut outcome =
|
||||
if !clock.trusted() || config.binding.verify(&request, chrono::Utc::now()).is_err() {
|
||||
@@ -454,7 +532,31 @@ fn handle(
|
||||
apt.execute(db)
|
||||
.unwrap_or_else(|_| Outcome::unknown("APT_HELPER_EFFECT_UNKNOWN"))
|
||||
} else {
|
||||
execute(&job).unwrap_or_else(|_| Outcome::unknown("HELPER_EFFECT_UNKNOWN"))
|
||||
if job.action.full_maintenance() {
|
||||
rmm_privileged_helper::script_controlled(&job, || {
|
||||
ensure!(clock.trusted(), "CLOCK_UNTRUSTED");
|
||||
peer_allowed(stream, config.agent_uid)?;
|
||||
let mut byte = 0u8;
|
||||
let read = unsafe {
|
||||
libc::recv(
|
||||
stream.as_raw_fd(),
|
||||
(&mut byte as *mut u8).cast(),
|
||||
1,
|
||||
libc::MSG_PEEK | libc::MSG_DONTWAIT,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
read < 0
|
||||
&& std::io::Error::last_os_error().kind()
|
||||
== std::io::ErrorKind::WouldBlock,
|
||||
"SCRIPT_CALLER_CANCELLED_OR_DISCONNECTED"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|_| Outcome::unknown("HELPER_SCRIPT_EFFECT_UNKNOWN"))
|
||||
} else {
|
||||
execute(&job).unwrap_or_else(|_| Outcome::unknown("HELPER_EFFECT_UNKNOWN"))
|
||||
}
|
||||
}
|
||||
};
|
||||
if rmm_privileged_helper::apt::is_apt_action(&job) {
|
||||
@@ -497,7 +599,7 @@ fn run() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args == [std::ffi::OsString::from("--help")] {
|
||||
println!(
|
||||
"rmm-privileged-helper [--help|--inspect-general-profile|--inspect-apt-profile|--probe-native|--install-apt-provider]\nRMM_HELPER_CONFIG=/etc/rmm/helper.json (root-owned 0600).\nDaemon mode accepts only authenticated typed IPC; all effects need independent signed Sync and a fresh consumed grant. Administrative install/probe modes are explicit bootstrap actions, never network commands."
|
||||
"rmm-privileged-helper [--help|--inspect-general-profile|--inspect-full-maintenance-profile|--inspect-apt-profile|--probe-native|--install-apt-provider]\nRMM_HELPER_CONFIG=/etc/rmm/helper.json (root-owned 0600).\nDaemon mode accepts only authenticated typed IPC; all effects need independent signed Sync and a fresh consumed grant. Administrative install/probe modes are explicit bootstrap actions, never network commands."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -510,7 +612,11 @@ fn run() -> Result<()> {
|
||||
args.is_empty()
|
||||
|| args == [std::ffi::OsString::from("--probe-native")]
|
||||
|| args == [std::ffi::OsString::from("--inspect-apt-profile")]
|
||||
|| args == [std::ffi::OsString::from("--inspect-general-profile")],
|
||||
|| args == [std::ffi::OsString::from("--inspect-general-profile")]
|
||||
|| args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile"
|
||||
)],
|
||||
"UNKNOWN_HELPER_MODE"
|
||||
);
|
||||
let path = PathBuf::from(
|
||||
@@ -533,17 +639,38 @@ fn run() -> Result<()> {
|
||||
config.binding.public_key_hex = key.public_key_hex;
|
||||
}
|
||||
config.validate_profile()?;
|
||||
if args == [std::ffi::OsString::from("--inspect-general-profile")] {
|
||||
let mut running_image = config
|
||||
.helper_binary_sha256
|
||||
.as_deref()
|
||||
.map(image::RunningImage::current)
|
||||
.transpose()?;
|
||||
if args == [std::ffi::OsString::from("--inspect-general-profile")]
|
||||
|| args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile",
|
||||
)]
|
||||
{
|
||||
ensure!(
|
||||
config.profile == HelperProfile::General,
|
||||
(config.profile == HelperProfile::General
|
||||
&& args == [std::ffi::OsString::from("--inspect-general-profile")])
|
||||
|| (config.profile == HelperProfile::FullMaintenanceV1
|
||||
&& args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile"
|
||||
)]),
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
);
|
||||
let policy = config.general_policy()?;
|
||||
let pin = control::GeneralPin {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
schema_version: if config.profile == HelperProfile::FullMaintenanceV1 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
profile: policy.profile.clone(),
|
||||
identity: policy.identity.clone(),
|
||||
policy_sha256: policy.sha256()?,
|
||||
helper_binary_sha256: running_image.as_mut().map(|i| i.verify()).transpose()?,
|
||||
};
|
||||
println!("{}", serde_json::to_string(&pin)?);
|
||||
return Ok(());
|
||||
@@ -627,6 +754,7 @@ fn run() -> Result<()> {
|
||||
&clock,
|
||||
&mut sync,
|
||||
&sync_clock,
|
||||
running_image.as_mut(),
|
||||
) {
|
||||
let code = safe_error_code(&error);
|
||||
eprintln!("helper request rejected: {code}");
|
||||
@@ -704,6 +832,34 @@ mod tests {
|
||||
assert!(config.validate_profile().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_is_a_separate_explicit_profile_and_shared_ledger() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
let mut config:Config=serde_json::from_value(serde_json::json!({"profile":"general","binding":{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"public_key_hex":"00".repeat(32)},"agent_uid":993,"socket_gid":993,"socket":"/run/rmm-helper-maintenance/control.sock","state":rmm_privileged_helper::readiness::SHARED_STATE,"allowed_services":[],"allow_reboot":false,"allow_root_scripts":true})).unwrap();
|
||||
config.validate_profile().unwrap();
|
||||
let mut job:rmm_domain::jobs::JobPayload=serde_json::from_value(serde_json::json!({"schema_version":1,"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"job_id":id,"attempt_id":id,"execution_identity":"root","not_before":now,"start_before":now+chrono::Duration::minutes(1),"max_runtime_seconds":30,"max_output_bytes":4096,"action":{"action":"run_script","interpreter":"posix_sh","script_utf8":"id\n","arguments":[],"expected_stdout":null,"privileged_script_profile":"full_maintenance_v1"}})).unwrap();
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(config.validate_profile().is_err());
|
||||
config.profile = HelperProfile::FullMaintenanceV1;
|
||||
assert!(config.validate_profile().is_err());
|
||||
config.helper_binary_sha256 = Some("ab".repeat(32));
|
||||
config.validate_profile().unwrap();
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
let proof = config.general_policy().unwrap();
|
||||
assert_eq!(proof.schema_version, 2);
|
||||
assert_eq!(proof.profile, "full_maintenance_v1");
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "rmm-mvp-test.service".into(),
|
||||
state: "running".into(),
|
||||
};
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.state = "/var/lib/another-ledger".into();
|
||||
assert!(config.validate_profile().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn peer_acl_does_not_trust_request_identity() {
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
@@ -733,6 +889,8 @@ mod tests {
|
||||
allowed_services: vec!["rmm-acceptance.service".into()],
|
||||
allow_reboot: false,
|
||||
allow_root_scripts: false,
|
||||
allowed_script_profiles: None,
|
||||
helper_binary_sha256: None,
|
||||
apt_provider: None,
|
||||
};
|
||||
let now = chrono::Utc::now();
|
||||
@@ -751,6 +909,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
@@ -763,6 +922,13 @@ mod tests {
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.allow_root_scripts = true;
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
// The additive full profile must not alter historical local General
|
||||
// ceilings; the independent central legacy policy remains unchanged.
|
||||
job.max_runtime_seconds = 301;
|
||||
job.max_output_bytes = 65537;
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
job.max_runtime_seconds = 180;
|
||||
job.max_output_bytes = 4096;
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "not-approved.service".into(),
|
||||
state: "running".into(),
|
||||
|
||||
@@ -34,6 +34,7 @@ fn fixture() -> (
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello World\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - chrono::Duration::seconds(60),
|
||||
|
||||
@@ -433,6 +433,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -519,6 +519,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: c.issued_at,
|
||||
|
||||
@@ -292,6 +292,21 @@ fn windows_event_log_success_evidence(
|
||||
|
||||
// The profile records the requested process option, never an effective GPO policy.
|
||||
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
|
||||
if action.full_maintenance() {
|
||||
let Action::RunScript { script_utf8, .. } = action else {
|
||||
unreachable!()
|
||||
};
|
||||
ensure!(
|
||||
evidence["privileged_script_profile"] == "full_maintenance_v1"
|
||||
&& evidence["script_sha256"] == hash(script_utf8.as_bytes())
|
||||
&& match action.script_platform() {
|
||||
Some("linux") => evidence["execution_uid"] == 0,
|
||||
Some("windows") => evidence["execution_sid"] == "S-1-5-18",
|
||||
_ => false,
|
||||
},
|
||||
"full maintenance identity/profile evidence mismatch"
|
||||
);
|
||||
}
|
||||
if let Action::RunScript {
|
||||
script_utf8,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
@@ -411,6 +426,7 @@ mod script_profile_tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
|
||||
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
|
||||
@@ -628,7 +644,8 @@ pub async fn permit(
|
||||
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|
||||
|| (matches!(payload.action, Action::RunScript { .. })
|
||||
&& !crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?)
|
||||
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
|
||||
@@ -162,6 +162,13 @@ pub struct Variant {
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WebParameters {
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_privileged_script_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "PrivilegedScriptProfile")]
|
||||
privileged_script_profile: Option<PrivilegedScriptProfile>,
|
||||
execution_identity: String,
|
||||
timeout_seconds: u32,
|
||||
max_output_bytes: u32,
|
||||
@@ -230,6 +237,7 @@ impl PlanRequest {
|
||||
arguments: p.arguments.clone().unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: p.privileged_script_profile,
|
||||
}
|
||||
}
|
||||
"refresh_inventory" => Action::RefreshInventory {
|
||||
@@ -329,6 +337,7 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
if v.encoding != "utf-8"
|
||||
|| action.script_platform() != Some(v.os_family.as_str())
|
||||
@@ -346,6 +355,15 @@ fn capabilities(value: Value) -> Result<Vec<String>> {
|
||||
serde_json::from_value(value).map_err(|_| fail("UNSUPPORTED_CAPABILITY"))
|
||||
}
|
||||
fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
if !input
|
||||
.action
|
||||
.valid_execution_identity(&input.execution_identity)
|
||||
|| (input.execution_identity == "system"
|
||||
&& matches!(input.action, Action::RunScript { .. })
|
||||
&& !input.action.full_maintenance())
|
||||
{
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if input.script_variants.is_empty() {
|
||||
return Ok(input.action.clone());
|
||||
}
|
||||
@@ -356,6 +374,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
privileged_script_profile,
|
||||
} = &input.action
|
||||
else {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
@@ -364,7 +383,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
if interpreter != &first.interpreter
|
||||
|| script_utf8 != &first.script_utf8
|
||||
|| windows_execution_profile != &first.windows_execution_profile
|
||||
|| (input.execution_identity != "agent_service"
|
||||
|| (input.execution_identity == "root"
|
||||
&& input
|
||||
.script_variants
|
||||
.iter()
|
||||
@@ -391,6 +410,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
arguments: arguments.clone(),
|
||||
expected_stdout: expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: *privileged_script_profile,
|
||||
})
|
||||
}
|
||||
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
|
||||
@@ -413,6 +433,9 @@ pub async fn plan(
|
||||
if input.targets.asset_ids.is_empty()
|
||||
|| input.targets.asset_ids.len() > 100
|
||||
|| !input.action.validate_plan_shape()
|
||||
|| !input
|
||||
.action
|
||||
.valid_execution_identity(&input.execution_identity)
|
||||
|| !matches!(
|
||||
input.execution_identity.as_str(),
|
||||
"agent_service" | "root" | "system"
|
||||
@@ -821,6 +844,9 @@ async fn authorize_http(
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
if matches!(job.payload.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?;
|
||||
}
|
||||
if let Some(permission) =
|
||||
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
||||
{
|
||||
@@ -1116,6 +1142,28 @@ mod windows_contract_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_web_profile_is_action_wide_strict_and_identity_bound() {
|
||||
let request = serde_json::json!({"tenant_id":Uuid::nil(),"action":"run_script","targets":{"asset_ids":[Uuid::nil()]},"parameters":{"execution_identity":"system","timeout_seconds":30,"max_output_bytes":4096,"privileged_script_profile":"full_maintenance_v1","variants":[{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n","windows_execution_profile":"powershell_51_remote_signed"}]},"schedule":{"not_before":"2026-11-14T12:00:00Z","start_before":"2026-11-14T13:00:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
|
||||
let resolved = serde_json::from_value::<PlanRequest>(request.clone())
|
||||
.unwrap()
|
||||
.resolve(Uuid::nil())
|
||||
.unwrap();
|
||||
let action = target_action(&resolved, &["windows.base/1".into()]).unwrap();
|
||||
assert!(action.full_maintenance());
|
||||
let mut invalid = resolved.clone();
|
||||
invalid.execution_identity = "agent_service".into();
|
||||
assert!(target_action(&invalid, &["windows.base/1".into()]).is_err());
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("unknown"),
|
||||
serde_json::json!({"full_maintenance_v1":null}),
|
||||
] {
|
||||
let mut request = request.clone();
|
||||
request["parameters"]["privileged_script_profile"] = value;
|
||||
assert!(serde_json::from_value::<PlanRequest>(request).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
|
||||
let mut i = input();
|
||||
let legacy_linux = encode(&i.action).unwrap();
|
||||
@@ -1130,6 +1178,7 @@ mod windows_contract_tests {
|
||||
windows,
|
||||
Action::RunScript {
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
@@ -28,9 +28,19 @@ struct RootScope {
|
||||
assignment_version: u64,
|
||||
principals: Vec<String>,
|
||||
helper_policy_sha256: String,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
helper_binary_sha256: Option<String>,
|
||||
acceptance_evidence_id: String,
|
||||
allowed_services: Vec<String>,
|
||||
allow_root_scripts: bool,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
allow_reboot: bool,
|
||||
#[serde(default)]
|
||||
apt: Option<RootAptPolicy>,
|
||||
@@ -96,6 +106,9 @@ impl RootPolicy {
|
||||
}
|
||||
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
|
||||
let mut permissions = vec!["root:execute"];
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
permissions.push("scripts:execute");
|
||||
}
|
||||
if matches!(job.action, Action::AptNativeAcceptance { .. }) {
|
||||
permissions.push("apt:native_acceptance");
|
||||
}
|
||||
@@ -205,7 +218,21 @@ impl RootScope {
|
||||
&& (20..=3600).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
}
|
||||
Action::RunScript { .. } => self.allow_root_scripts && job.max_runtime_seconds <= 300,
|
||||
Action::RunScript { .. } => {
|
||||
self.allow_root_scripts
|
||||
&& job.max_runtime_seconds <= 300
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| (self.helper_binary_sha256.as_ref().is_some_and(|h| {
|
||||
capabilities.contains(&format!("helper.binary.sha256:{h}"))
|
||||
}) && self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
}) && capabilities
|
||||
.iter()
|
||||
.any(|c| c == rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY)))
|
||||
}
|
||||
Action::SetServiceState { unit, state } => {
|
||||
self.allowed_services.contains(unit)
|
||||
&& matches!(state.as_str(), "running" | "stopped")
|
||||
@@ -265,7 +292,12 @@ fn load() -> Result<RootPolicy, Error> {
|
||||
}
|
||||
let policy: RootPolicy =
|
||||
serde_json::from_slice(&fs::read(path).map_err(|_| disabled())?).map_err(|_| disabled())?;
|
||||
if policy.schema_version != 1
|
||||
if !matches!(policy.schema_version, 1 | 2)
|
||||
|| (policy.schema_version == 1
|
||||
&& policy
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|s| s.allowed_script_profiles.is_some() || s.helper_binary_sha256.is_some()))
|
||||
|| policy.profile != "development"
|
||||
|| policy.expires_at <= Utc::now()
|
||||
|| policy.scopes.is_empty()
|
||||
@@ -342,7 +374,7 @@ mod tests {
|
||||
fn no_capability_or_relabel_shortcut() {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let job = JobPayload {
|
||||
let mut job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
@@ -357,6 +389,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
@@ -364,7 +397,7 @@ mod tests {
|
||||
max_runtime_seconds: 60,
|
||||
max_output_bytes: 1024,
|
||||
};
|
||||
let scope = RootScope {
|
||||
let mut scope = RootScope {
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
@@ -372,9 +405,11 @@ mod tests {
|
||||
assignment_version: 1,
|
||||
principals: vec!["selected".into()],
|
||||
helper_policy_sha256: "ab".repeat(32),
|
||||
helper_binary_sha256: None,
|
||||
acceptance_evidence_id: "native-test-record".into(),
|
||||
allowed_services: vec![],
|
||||
allow_root_scripts: true,
|
||||
allowed_script_profiles: None,
|
||||
allow_reboot: false,
|
||||
apt: None,
|
||||
root_logs: None,
|
||||
@@ -389,6 +424,26 @@ mod tests {
|
||||
assert!(scope.permits("selected", &job, &caps, None));
|
||||
assert!(!scope.permits("automation", &job, &caps, None));
|
||||
assert!(!scope.permits("selected", &job, &caps[..4], None));
|
||||
if let Action::RunScript {
|
||||
privileged_script_profile,
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
*privileged_script_profile =
|
||||
Some(rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1);
|
||||
}
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
scope.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
let mut caps = caps;
|
||||
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
scope.helper_binary_sha256 = Some("cd".repeat(32));
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
caps.push(format!("helper.binary.sha256:{}", "cd".repeat(32)));
|
||||
assert!(scope.permits("selected", &job, &caps, None));
|
||||
let mut windows = caps;
|
||||
windows.push("windows.base/1".into());
|
||||
assert!(!scope.permits("selected", &job, &windows, None));
|
||||
|
||||
@@ -40,6 +40,11 @@ struct SystemScope {
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
max_runtime_seconds: u32,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
}
|
||||
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
@@ -106,6 +111,10 @@ impl SystemScope {
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& self
|
||||
.allowed_script_profiles
|
||||
.as_deref()
|
||||
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(
|
||||
@@ -114,6 +123,7 @@ impl SystemScope {
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
allow_msi: bool,
|
||||
allow_scripts: bool,
|
||||
) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
@@ -145,6 +155,20 @@ impl SystemScope {
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
}
|
||||
Action::RunScript { .. } => {
|
||||
allow_scripts
|
||||
&& job.action.full_maintenance()
|
||||
&& self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
})
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& job.action.available_for("system", capabilities)
|
||||
}
|
||||
_ if allow_msi => job.action.windows_msi().is_some_and(|m| {
|
||||
job.action.validate()
|
||||
&& job
|
||||
@@ -164,12 +188,17 @@ impl SystemScope {
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2
|
||||
matches!(self.schema_version, 1..=3)
|
||||
&& (self.schema_version >= 2
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
|
||||
&& (self.schema_version == 3
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_script_profiles.is_none()))
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
@@ -184,10 +213,15 @@ impl SystemPolicy {
|
||||
now: DateTime<Utc>,
|
||||
) -> bool {
|
||||
self.valid(now)
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2))
|
||||
&& self.scopes.iter().any(|scope| {
|
||||
scope.permits(
|
||||
principal,
|
||||
job,
|
||||
capabilities,
|
||||
self.schema_version >= 2,
|
||||
self.schema_version == 3,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
@@ -310,6 +344,9 @@ pub async fn authorize(
|
||||
}
|
||||
// Independent DB permission; root:execute never implies this scope.
|
||||
crate::permissions::require(tx, principal, "system:execute").await?;
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require(tx, principal, "scripts:execute").await?;
|
||||
}
|
||||
let policy = load()?;
|
||||
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(caps)?;
|
||||
@@ -422,6 +459,42 @@ mod tests {
|
||||
assert!(!policy.permits("selected", &job, &caps, policy.expires_at));
|
||||
}
|
||||
#[test]
|
||||
fn full_script_requires_v3_explicit_scope_and_does_not_inherit_scm_or_msi() {
|
||||
let (mut policy, mut job, mut caps) = fixture();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
caps.extend([
|
||||
"run_script".into(),
|
||||
"system:run_script".into(),
|
||||
"script.powershell/1".into(),
|
||||
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
|
||||
]);
|
||||
for version in [1, 2, 3] {
|
||||
policy.schema_version = version;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
policy.scopes[0].allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
for version in [1, 2] {
|
||||
policy.schema_version = version;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
policy.schema_version = 3;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
|
||||
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() {
|
||||
let (mut policy, mut job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
@@ -443,6 +516,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.action = Action::SetServiceState {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
# Explizite Hostwartung mit full_maintenance_v1
|
||||
|
||||
Stand 2026-11-14, Spezifikation1.20. Die Batch-Skriptkonsole und der unabhängig
|
||||
geprüfte Fullhelper-Binärpinfix sind lokal implementiert und neu quellqualifiziert.
|
||||
Kein FullMaintenanceprofil wurde durch diese Dateien auf einem Ziel installiert,
|
||||
kein RMM-Job ausgeführt oder genehmigt. Cloud-Linux-VM zuerst, Windowsgast separat;
|
||||
Notebook ausschließlich Entwicklung.
|
||||
|
||||
## Aktueller korrigierter lokaler Nachweis
|
||||
|
||||
Der neue eigenständige Pack liegt privat unter
|
||||
`devstate/script-console-qualification/run-29461892-343f-42f4-b469-88703535425e/`.
|
||||
Manifest-SHA256:
|
||||
`ddd1a78d1cd289b02b1f98572f9652171ec00be84e01ce099fd722d689bcaacd`.
|
||||
158 vollständige Compiler-/Include-/Fixture-/Deploymentinputs vor/nach identisch.
|
||||
Sourcearchiv-SHA256:
|
||||
`fcb57f69ad81ea4acde15af6022d5c2da32f5699ebd39886c530c77882b369cc`.
|
||||
|
||||
Tatsächlich ausgeführt: Formatprüfung, Linux-Workspace-Alltargets-Clippy mit
|
||||
`-D warnings`,285 lokale Tests bestanden (5DB-Fälle zunächst ausgelassen), danach
|
||||
sämtliche45 Serververträge inklusive dieser5 gegen frisches isoliertes PostgreSQL
|
||||
bestanden (0ignored). Windows-GNU-Alltargets-Clippy mit -Dwarnings im Default-
|
||||
und SYSTEM-Helperprofil bestanden. Kein geänderter Test unterdrückt; die neue
|
||||
Imageprüfung führt auch bei nicht vertrauenswürdigem Dateibesitz echte
|
||||
Verweigerungsassertions aus, keinen stillen Early-return-Skip.
|
||||
|
||||
Neue tatsächliche Linux-Unitlisten: Domain22, Linuxruntime16, Helperpolicy6,
|
||||
Serververträge45. Auf Cloud-Linux ohne isolierte DB erwartet:84PASS und5explizite
|
||||
DBignored; diese5 sind separat im lokalen45er-DB-Lauf tatsächlich bestanden.
|
||||
Alle vier vollständigen Listen müssen vor irgendeinem Unitstart geprüft sein.
|
||||
Linux-Release-Helper SHA256
|
||||
`79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf`;
|
||||
Agent `0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f`;
|
||||
Server `610017637a9f9e55a6cb3cd8264937b953996af84e86dd49f2ea00c8e59739cd`.
|
||||
Keine dieser neuen Binaries ist durch den Builder auf einem Ziel installiert.
|
||||
Native Cloud-Linux-/Windows-Units, Erhaltungsbootstrap und WebUI-genehmigter
|
||||
FullMaintenancejob bleiben ausdrücklich offen.
|
||||
|
||||
## Frühere lokale Nachweise und der danach behobene Binärpinbefund
|
||||
|
||||
Das eingefrorene Paket liegt ausschließlich privat unter
|
||||
`devstate/script-console-qualification/run-de34d47c-985e-460c-b18c-3f0d1b3fd315/`.
|
||||
Manifest-SHA256:
|
||||
`60a50262f9f8d85c11eb58e1a9e0f6e03be6cd5db7a59bc1745fb7d9dc8a6f65`.
|
||||
157 Compiler-, Include-, Fixture- und Deploymentinputs wurden vor/nach dem
|
||||
vollständigen Lauf identisch geprüft. `reviewed-sources.tar.gz`:
|
||||
`ef822b2e2ec6f8ad3d828f0923b2aa886d462fba328affb61bd80e98acf2c357`.
|
||||
|
||||
Tatsächlich lokal ausgeführt: Formatprüfung; Linux-Workspace-Clippy mit allen
|
||||
Targets und `-D warnings`; Workspace284PASS bei fünf zunächst ausgelassenen
|
||||
DB-Fällen; anschließend sämtliche45 Servertests mit `--include-ignored` in
|
||||
frischem isoliertem PostgreSQL17.6:45PASS,0ignored. DB ohne veröffentlichten Port,
|
||||
Netzwerknamespace ausschließlich intern, frische Rollen/Migrationen, danach
|
||||
entfernt. Keine Produktionsdatenbank. Windows-GNU-Alltargets-Clippy separat im
|
||||
Default- und SYSTEM-Helperprofil jeweils bestanden; keine native Windowsausführung.
|
||||
Linux-Releasebinaries und vier native Linux-Testprogramme dieses früheren
|
||||
Quellenstands sind gebaut/gehasht, noch nicht auf der Cloud-VM ausgeführt oder
|
||||
installiert. **Nachträglicher unabhängiger Reviewblocker:** Dieser Pack bindet
|
||||
noch nicht den tatsächlichen laufenden Linux-Fullhelpercodehash. Er berechtigt
|
||||
keine Fullprofilaktivierung. Der danach separat geprüfte und im neuen Pack qualifizierte enge Corefix ergänzt ausschließlich
|
||||
im Fullprofil tatsächliches gehaltenes `/proc/self/exe`, geschützten Binärpin,
|
||||
authentisierte Probe, zusätzliche Binärcapability und zentrale Hashprüfung.
|
||||
General/APT lassen neue Metadaten vollständig aus. Der neue lokale Stand steht
|
||||
oben; dieser alte Pack bleibt ausdrücklich der ursprüngliche Beleg.
|
||||
|
||||
Die ersten Packvorbereitungen erzeugten kein qualifiziertes Manifest: Der erste
|
||||
before/after-Schutz bemerkte die währenddessen vervollständigte Builderinputliste;
|
||||
der zweite hielt bei PostgreSQLs temporärer Initialisierungsphase an. Der finale
|
||||
oben genannte Lauf wartet auf den endgültigen TCP-Endpunkt und besteht vollständig.
|
||||
Diese Vorbereitungsläufe werden nicht zu bestandenen Abnahmen umgedeutet.
|
||||
|
||||
## Separater Linux-first-Unitrunner
|
||||
|
||||
Der Runner `deploy/script_console_acceptance.py` ist separat reviewbar und kein
|
||||
Teil der158 eingefrorenen Compilerinputs; er baut und verändert diese nicht.
|
||||
Er ist ausdrücklich auf den neuen Pack29461892 und dessen Manifestddd1a78d…
|
||||
gebunden; bei veränderten Compilerinputs wird ein neuer Start verweigert. Die
|
||||
ursprüngliche Vorbereitung für Packde34 bleibt ein früherer, nie ausgeführter
|
||||
Runnerstand. Die jetzigen Counts beruhen auf den tatsächlich erzeugten Listen.
|
||||
Runnerquellhash:
|
||||
`2b3ba8d548d18627643a9f73c9a4f7bacce4ac2cd5495745c6760d088e078145`.
|
||||
Supportquellen werden vor Import und jedem Zielaufruf inklusive Readback exakt
|
||||
geprüft und in Intent/Payload/Result gebunden: Runtime-Bootstraphelper
|
||||
`833ad8806c90a19342aa6fbc71c33e81975caffb1746550e9b0fbdca7fa0c7ab`,
|
||||
Zugangsparser
|
||||
`5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd`.
|
||||
Der finale Readback verlangt product_state_writes, rmm_jobs,
|
||||
capabilities_activated und approvals ausdrücklich jeweils false.
|
||||
Er verwendet ausschließlich den vorhandenen strikten Bootstraptransport und
|
||||
`credentials/linux-vm.conf` im ursprünglichen Hauptcheckout, ausschließlich als root auf der festgelegten Linux-Test-VM, mit vorhandenem
|
||||
SSH-Key und strenger Hostprüfung. Keine
|
||||
Zugangsdatenkopie ins Scriptworktree, keine alternative IP oder Passwortfallback.
|
||||
|
||||
**Geplant, noch nicht ausgeführt:**
|
||||
|
||||
```bash
|
||||
python3 deploy/script_console_acceptance.py execute-linux
|
||||
```
|
||||
|
||||
Es entstehen nur neue private Scratchdateien unter
|
||||
`/var/lib/rmm-script-console-contracts/<case-id>/`. Erst werden alle vier exakten
|
||||
ELF-Hashes und vollständigen Listen geprüft; kein Unitstart vor dem gesamten
|
||||
Listenbeleg. Danach feste Testargumente, geleerte Umgebung, eigenes TMPDIR,
|
||||
eigener Netzwerknamespace und CPU-/Speicher-/Dateilimits. Erwartet werden84PASS
|
||||
und fünf ausdrücklich ausgelassene DB-Fälle auf der VM ohne DB; dieselben fünf
|
||||
DB-Verträge sind bereits im isolierten lokalen45er-Lauf belegt. Keine Installation,
|
||||
Enrollment-, Dienst-, Policy-, Paket-, Schlüssel-, Journal- oder Capabilityänderung.
|
||||
|
||||
Bei verlorenem Ergebnis ausschließlich denselben ursprünglichen Fall lesen:
|
||||
|
||||
```bash
|
||||
python3 deploy/script_console_acceptance.py read-linux --case <urspruengliche-case-id>
|
||||
```
|
||||
|
||||
Readback erzeugt keinen zweiten Remote-Start. Ein vorhandener Create-once-
|
||||
Startmarker erlaubt kein erneutes `run`; Teilergebnisse bleiben erhalten. Ein
|
||||
unvollständiger/fehlender Beleg ist keine bestandene Abnahme und wird nicht blind
|
||||
wiederholt. Native Units sind keine RMM-Dienst-/WebUI-/FullMaintenanceabnahme.
|
||||
|
||||
## Bootstrapvorbereitung nach gesondertem Erhaltungsreview
|
||||
|
||||
Die folgenden Schritte sind nur geplant. Aktuelle Cloudbelege, Geräte-/Boot-/
|
||||
Journalidentitäten, Inodes, Verbrauchszeilen und Dienstzustände werden vor einer
|
||||
Änderung durch den verantwortlichen Rootprozess unabhängig gegengeprüft. Die
|
||||
bisherigen General-/APT-Units und Pins sowie deren Historie bleiben erhalten;
|
||||
keine Ledgerkopie, kein Reset und kein stilles Öffnen alter Scopes.
|
||||
|
||||
Die neue Unit ist `deploy/linux/rmm-full-maintenance-helper.service` mit eigenem
|
||||
Runtimeverzeichnis `/run/rmm-helper-maintenance`. Sie verweist auf
|
||||
`/etc/rmm-remote/helper-full-maintenance.json`. Diese Konfiguration erhält exakt
|
||||
die bestehende provisionierte öffentliche Bindingidentität und dieselben
|
||||
Root-Sharedledger-/Lockdateien; neue Auswahl:
|
||||
|
||||
```json
|
||||
{
|
||||
"profile": "full_maintenance_v1",
|
||||
"allowed_services": [],
|
||||
"allow_reboot": false,
|
||||
"allow_root_scripts": true,
|
||||
"allowed_script_profiles": ["full_maintenance_v1"],
|
||||
"helper_binary_sha256": "<tatsaechlicher SHA256 der qualifizierten laufenden Helperbinary>"
|
||||
}
|
||||
```
|
||||
|
||||
Das ist ein Ausschnitt, keine vollständige einsatzfähige Konfiguration. Socket,
|
||||
Agent-UID/GID, Zustandspfad und bestehendes Binding müssen aus dem tatsächlich
|
||||
geprüften Bestand kommen. Kein `apt_provider`. `allow_reboot=false` verweigert
|
||||
nur die typisierte Rebootaction; genehmigter Rootcode besitzt volle Hostautorität.
|
||||
|
||||
Der separat geschützte Policy-Pin bindet Profil `full_maintenance_v1`, bestehende
|
||||
Identität, tatsächlichen lokalen Policyhash und unabhängig beobachteten
|
||||
laufenden Binärhash. Das neue Fullprofil benötigt Schema2 im Pin; der Helper
|
||||
kann diesen nach selbst geprüftem Rootimage mit dem ausdrücklich getrennten
|
||||
Bootstrapmodus `--inspect-full-maintenance-profile` ausgeben. Generalpin
|
||||
Schema1 bleibt unverändert. Agentumgebung ausschließlich
|
||||
additiv um `RMM_FULL_MAINTENANCE_HELPER_SOCKET` und
|
||||
`RMM_FULL_MAINTENANCE_POLICY_FILE` ergänzen. Kein Fallback auf General/APT und
|
||||
keine Änderung deren bestehender Umgebung. Die zentrale Rootpolicy braucht
|
||||
Schema2 und einen ausdrücklich begrenzten Scope mit neuen exakten Helperpins
|
||||
sowie `allowed_script_profiles=["full_maintenance_v1"]`. Aktuelle Rechte beider
|
||||
Planakteure, Helper-Sync, TrustedClock, ursprünglicher Grant und Einmalverbrauch
|
||||
bleiben zusätzlich erforderlich. Eine Policy ist keine Jobgenehmigung.
|
||||
|
||||
Vor Installation werden zusammengesetzte systemd-Unit und etwaige Drop-ins
|
||||
geprüft: Vollwartung darf keine General-Sandbox erben, die Hostdateisystem oder
|
||||
Netzwerk unerwartet sperrt. Dienst- und Binärwechsel nur mit qualifizierten
|
||||
Artefakten und explizitem Erhaltungsplan. Insbesondere darf eine neue allgemeine
|
||||
Helperbinary nicht still die alten APT-Codepins überschreiben/öffnen. Gegebenenfalls
|
||||
eigenen qualifizierten Binärpfad für die neue FullMaintenanceunit wählen und die
|
||||
bestehenden Providerpfade unverändert erhalten. Native Erhaltung und Sync nachweisen,
|
||||
bevor neue Capabilities/Scopes geöffnet werden.
|
||||
|
||||
Erster tatsächlicher FullMaintenancejob nur nach bereitgestellter WebUI und
|
||||
expliziter Genehmigung der unveränderlichen Skript-/Profil-/Ziel-/Rechtebytes.
|
||||
Abgestimmter Scope: harmlose Identität/stdout/stderr und kontrollierte lesende
|
||||
Dateisystem-/Netzwerkbeobachtung; kein Betriebssystemupdate oder Neustart. Volle
|
||||
Hostautorität wird sichtbar erklärt; kein Sandbox-, No-Reboot- oder Rollbackversprechen.
|
||||
Windows-SYSTEM folgt nach eigenem Clock-/Pipe-/Profilnachweis. Die vorhandene
|
||||
PipeV2-Datei ist unverändert SHA256
|
||||
`ce525dab23f2e4faa2c9816280c1a5a8b40e56d0e63a350256e83b2df1d9229d`;
|
||||
ursprüngliche native Pipebelege werden nicht als Belege der neuen Runtime ausgegeben.
|
||||
|
||||
## Anschließend auf der tatsächlichen Cloud-Linux-VM bestanden
|
||||
|
||||
Root führte ausschließlich den korrigierten Pack29461892 nativ aus: Fall
|
||||
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, **84PASS,5explizite DBignored**.
|
||||
Die vier vollständigen tatsächlichen Listen wurden vor irgendeinem Unitstart
|
||||
exakt geprüft; anschließend liefen alle vier festen ELFs im eigenen Scratch,
|
||||
mit geleerter Umgebung, Netzwerknamespace und Ressourcenlimits. Die5DB-Verträge
|
||||
bleiben diesem VM-Lauf ausdrücklich nicht zugerechnet; sie sind im separaten
|
||||
isolierten45er-PostgreSQL-Lauf belegt. Kein stiller Testskip oder Produktjob.
|
||||
|
||||
Beleg `passed-e214cd9b-21ac-48ce-82dc-d10364329d04.json`, SHA256
|
||||
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
|
||||
Keine Agent-/Helperinstallation, Änderung bestehender Dienste/Policies/PKI/
|
||||
Datenbanken, veröffentlichte Capability oder WebUI-Genehmigung durch diesen
|
||||
Unitlauf. Der oben ursprünglich geplante Unitaufruf ist damit abgeschlossen;
|
||||
Bootstrap, tatsächlicher FullMaintenancejob und Windowsabnahme bleiben offen.
|
||||
@@ -0,0 +1,31 @@
|
||||
[Unit]
|
||||
Description=RMM explicitly approved full host maintenance script helper
|
||||
After=time-sync.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
# Deliberate full host authority for separately approved full_maintenance_v1
|
||||
# scripts. This is NOT a sandbox and cannot promise no reboot or agent changes.
|
||||
User=root
|
||||
Group=rmm-agent
|
||||
StateDirectory=rmm-helper
|
||||
StateDirectoryMode=0700
|
||||
RuntimeDirectory=rmm-helper-maintenance
|
||||
RuntimeDirectoryMode=0750
|
||||
UMask=0077
|
||||
Environment=RMM_HELPER_CONFIG=/etc/rmm-remote/helper-full-maintenance.json
|
||||
ExecStart=/usr/local/libexec/rmm-privileged-helper
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# Retain the host filesystem, network, home paths, capabilities and syscalls.
|
||||
# General/APT units keep their existing restrictions. No inherited hardening
|
||||
# drop-in may silently contradict this profile; inspect merged unit predeploy.
|
||||
PrivateTmp=false
|
||||
PrivateNetwork=false
|
||||
ProtectSystem=false
|
||||
ProtectHome=false
|
||||
NoNewPrivileges=false
|
||||
KillMode=control-group
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fixed frozen Linux unit pack: prepare/run once, same-case readback only.
|
||||
|
||||
Uses existing strict bootstrap transport. No agent installation, RMM job,
|
||||
approval, policy, package, service or device-identity change.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SUPPORT_FILES = {
|
||||
'deploy/windows_msi_runtime_acceptance.py': '833ad8806c90a19342aa6fbc71c33e81975caffb1746550e9b0fbdca7fa0c7ab',
|
||||
'deploy/vm_access_check.py': '5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd',
|
||||
}
|
||||
|
||||
def verify_support():
|
||||
for name, digest in SUPPORT_FILES.items():
|
||||
path=ROOT/name
|
||||
if path.is_symlink() or hashlib.sha256(path.read_bytes()).hexdigest()!=digest:
|
||||
raise RuntimeError("Pinned bootstrap support source changed")
|
||||
|
||||
# Check helpers before import and again before every target call/readback.
|
||||
verify_support()
|
||||
import windows_msi_runtime_acceptance as support
|
||||
if Path(support.__file__).resolve()!=ROOT/'deploy/windows_msi_runtime_acceptance.py' or Path(support.access.__file__).resolve()!=ROOT/'deploy/vm_access_check.py':
|
||||
raise RuntimeError("Unexpected bootstrap support module origin")
|
||||
PACK = ROOT / 'devstate/script-console-qualification/run-29461892-343f-42f4-b469-88703535425e'
|
||||
MANIFEST_SHA = 'ddd1a78d1cd289b02b1f98572f9652171ec00be84e01ce099fd722d689bcaacd'
|
||||
STATE = ROOT / 'devstate/script-console-native'
|
||||
REMOTE = '/var/lib/rmm-script-console-contracts'
|
||||
PROFILE = 'script-console-linux-units-v1'
|
||||
KINDS = ('domain-tests', 'linux-runtime-tests', 'helper-policy-tests', 'server-contract-tests')
|
||||
COUNTS = {'domain-tests': (22, 0), 'linux-runtime-tests': (16, 0),
|
||||
'helper-policy-tests': (6, 0), 'server-contract-tests': (40, 5)}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def native_case(p):
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import resource
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
kinds = ('domain-tests', 'linux-runtime-tests', 'helper-policy-tests', 'server-contract-tests')
|
||||
counts = {'domain-tests': (22, 0), 'linux-runtime-tests': (16, 0),
|
||||
'helper-policy-tests': (6, 0), 'server-contract-tests': (40, 5)}
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read')
|
||||
and p['profile'] == 'script-console-linux-units-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64'
|
||||
and set(p['artifacts']) == set(kinds), 'fixed Linux bootstrap qualification')
|
||||
root = Path('/var/lib/rmm-script-console-contracts')
|
||||
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(not stat.S_ISLNK(s.st_mode) and 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 intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists():
|
||||
partial = {}
|
||||
for kind in kinds:
|
||||
for suffix in ('-list.json', '-result.json'):
|
||||
path = case / (kind + suffix)
|
||||
if path.exists():
|
||||
safe(path, False); require(path.stat().st_size <= 3 * 1024 * 1024, 'bounded partial receipt')
|
||||
partial[kind + suffix] = json.loads(path.read_bytes())
|
||||
return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start',
|
||||
all_lists_verified=(case / 'all-lists-verified.json').exists(),
|
||||
tests_started=(case / 'tests-started.json').exists(), partial=partial)
|
||||
safe(case / 'result.json', False)
|
||||
require((case / 'result.json').stat().st_size <= 12 * 1024 * 1024, 'bounded final receipt')
|
||||
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/sbin:/usr/bin:/sbin:/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, (30, 30))
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (16 * 1024 * 1024, 16 * 1024 * 1024))
|
||||
resource.setrlimit(resource.RLIMIT_AS, (768 * 1024 * 1024, 768 * 1024 * 1024))
|
||||
|
||||
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 kinds:
|
||||
binary = case / kind; safe(binary, False)
|
||||
raw = binary.read_bytes()
|
||||
require(len(raw) == p['artifacts'][kind]['bytes'] and len(raw) <= 64 * 1024 * 1024
|
||||
and hashlib.sha256(raw).hexdigest() == p['artifacts'][kind]['sha256']
|
||||
and raw[:6] == b'\x7fELF\x02\x01' and raw[18:20] == b'\x3e\0', 'exact Linux x64 ELF')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'],
|
||||
cwd=case, env=env, capture_output=True, timeout=8, 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'))
|
||||
write(case / (kind + '-list.json'), dict(names=actual, exit_code=listed.returncode,
|
||||
sha256=p['artifacts'][kind]['sha256'], stdout_b64=base64.b64encode(listed.stdout).decode(),
|
||||
stderr_b64=base64.b64encode(listed.stderr).decode()))
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line)
|
||||
for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == sum(counts[kind]),
|
||||
'all exact lists BEFORE any unit execution')
|
||||
listings[kind] = actual
|
||||
write(case / 'all-lists-verified.json', dict(all_lists_before_any_tests=True, manifest_sha256=p['manifest_sha256']))
|
||||
write(case / 'tests-started.json', dict(execute_tests_once=True))
|
||||
reports = {}
|
||||
for kind in kinds:
|
||||
timed = False
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
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=45, 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])
|
||||
passed, ignored = counts[kind]
|
||||
require(code == 0 and not timed and re.search(
|
||||
rf'test result: ok\. {passed} passed; 0 failed; {ignored} ignored;', raw.decode()),
|
||||
'exact native pass/ignored count; no retry')
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'],
|
||||
runner_sha256=p['runner_sha256'], support_files=p['support_files'], reports=reports, all_lists_before_any_tests=True,
|
||||
network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False,
|
||||
capabilities_activated=False, approvals=False, passed=84, ignored_database_cases=5)
|
||||
write(case / 'result.json', value)
|
||||
return value
|
||||
|
||||
|
||||
def rpc(prefix, payload, folder):
|
||||
verify_support()
|
||||
code = inspect.getsource(require) + '\n' + inspect.getsource(native_case)
|
||||
code += '\ntry:\n print(__import__("json").dumps(native_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(__import__("json").dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return support.transport(prefix, 'python3 -', code.encode(), folder, timeout=230)
|
||||
|
||||
|
||||
def run(case_id=None):
|
||||
import os
|
||||
verify_support()
|
||||
os.umask(0o077); STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
support.private(STATE, True); support.private(PACK, True)
|
||||
manifest = support.load(PACK / 'manifest.json')
|
||||
require(support.sha(PACK / 'manifest.json') == MANIFEST_SHA
|
||||
and manifest['source_before_after_equal'] is True
|
||||
and manifest['type'] == 'rmm.script-console.local-source-qualification', 'frozen original qualification')
|
||||
if case_id is None:
|
||||
require(all(support.sha(ROOT / name) == digest for name, digest in manifest['source_files'].items()), 'new attempt uses exact frozen source')
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
names = {}; artifacts = {}
|
||||
for kind in KINDS:
|
||||
artifact = PACK / kind; support.private(artifact)
|
||||
require(support.sha(artifact) == manifest['artifacts'][kind]['sha256'], 'original ELF bytes')
|
||||
log = PACK / (kind + '-list.log'); support.private(log)
|
||||
require(support.sha(log) == manifest['checks'][kind + '-list']['log_sha256'], 'original actual list')
|
||||
names[kind] = sorted(line[:-6] for line in log.read_text().splitlines() if line.endswith(': test'))
|
||||
require(len(names[kind]) == sum(COUNTS[kind]), 'fixed original test count')
|
||||
artifacts[kind] = {key: manifest['artifacts'][kind][key] for key in ('sha256', 'bytes')}
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=MANIFEST_SHA,
|
||||
runner_sha256=support.sha(__file__), support_files=SUPPORT_FILES, names=names, artifacts=artifacts)
|
||||
support.save(folder / 'intent.json', payload)
|
||||
support.save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
prefix = support.access_settings(support.ACCESS_ROOT, 'linux')
|
||||
require(rpc(prefix, dict(payload, action='prepare'), folder) == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS:
|
||||
support.upload(prefix, dict(path=str(PACK / kind), **artifacts[kind]), REMOTE + '/' + case_id + '/' + kind, folder, kind)
|
||||
action = 'run'
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; support.private(folder, True)
|
||||
payload = support.load(folder / 'intent.json'); support.load(folder / 'started-local.json')
|
||||
require(payload['id'] == case_id and payload['manifest_sha256'] == MANIFEST_SHA
|
||||
and payload['runner_sha256'] == support.sha(__file__)
|
||||
and payload['support_files'] == SUPPORT_FILES, 'immutable original readback only')
|
||||
prefix = support.access_settings(support.ACCESS_ROOT, 'linux')
|
||||
action = 'read'
|
||||
value = rpc(prefix, dict(payload, action=action), folder)
|
||||
support.save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), value)
|
||||
if value.get('status'):
|
||||
require(action == 'read', 'only same-case readback can report incomplete state')
|
||||
print(json.dumps(dict(case_id=case_id, verified=False, status=value['status'], retry_allowed=False)))
|
||||
return
|
||||
require(value['id'] == case_id and value['manifest_sha256'] == MANIFEST_SHA
|
||||
and value['runner_sha256'] == payload['runner_sha256'] and value['passed'] == 84
|
||||
and value['ignored_database_cases'] == 5 and value['all_lists_before_any_tests'] is True
|
||||
and value['network_namespace'] is True and value['environment_cleared'] is True
|
||||
and value['support_files'] == SUPPORT_FILES
|
||||
and all(value.get(flag) is False for flag in ('product_state_writes','rmm_jobs','capabilities_activated','approvals'))
|
||||
and set(value['reports']) == set(KINDS), 'complete native receipt')
|
||||
for kind in KINDS:
|
||||
item = value['reports'][kind]; passed, ignored = COUNTS[kind]
|
||||
require(item['names'] == payload['names'][kind] and item['sha256'] == payload['artifacts'][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False
|
||||
and re.search(rf'test result: ok\. {passed} passed; 0 failed; {ignored} ignored;',
|
||||
base64.b64decode(item['stdout_b64'], validate=True).decode()), 'each original native result')
|
||||
proof = dict(verified=True, case_id=case_id, manifest_sha256=MANIFEST_SHA, native=value,
|
||||
native_services_or_rmm_job_acceptance=False)
|
||||
path = folder / ('passed-' + str(uuid.uuid4()) + '.json'); support.save(path, proof)
|
||||
print(json.dumps(dict(case_id=case_id, verified=True, proof=str(path), sha256=support.sha(path), passed=84,
|
||||
ignored_database_cases=5, rmm_jobs=False, retry_allowed=False)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('mode', choices=('execute-linux', 'read-linux'))
|
||||
parser.add_argument('--case')
|
||||
args = parser.parse_args()
|
||||
require((args.mode == 'read-linux') == (args.case is not None), 'read needs original case; execute always new case')
|
||||
run(args.case)
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline source qualification and Linux delivery pack. No SSH or deployment.
|
||||
|
||||
This tool never enrolls an agent, starts a daemon, edits a policy or approves a
|
||||
job. Linux/Windows VM execution and full-profile activation remain separate.
|
||||
"""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LINUX_IMAGE = 'sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6'
|
||||
WINDOWS_IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
|
||||
POSTGRES_IMAGE = 'sha256:567d5d704a3e5a4864393b623a0d50eb1b5a4ad134cdac7cf19555cb2d8ffe9e'
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def inputs():
|
||||
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
|
||||
'tests/backend_root_logs.rs', 'tests/script_console/codec-golden.json',
|
||||
'tests/apt_transaction/fixtures/planning-canonical.json',
|
||||
'tools/apt-transaction/apt_transaction.py', 'tools/apt-transaction/hook',
|
||||
'deploy/linux/rmm-apt-helper.service',
|
||||
'deploy/linux/rmm-full-maintenance-helper.service', 'deploy/script_console_build.py')]
|
||||
paths += [p for p in (ROOT / 'crates').rglob('*')
|
||||
if p.is_file() and p.suffix in ('.rs', '.toml', '.c', '.h', '.idl', '.sql')]
|
||||
paths += [p for p in (ROOT / 'tests').rglob('*.rs')]
|
||||
paths += [p for p in (ROOT / 'migrations').rglob('*.sql')]
|
||||
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file() and p.suffix == '.proto']
|
||||
for path in paths:
|
||||
if path.is_symlink():
|
||||
raise RuntimeError('Symlink compiler input refused: ' + str(path.relative_to(ROOT)))
|
||||
return {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
state = ROOT / 'devstate/script-console-qualification'
|
||||
state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
out = state / ('run-' + str(uuid.uuid4()))
|
||||
out.mkdir(mode=0o700)
|
||||
frozen = inputs()
|
||||
checks = {}
|
||||
|
||||
def command(label, args):
|
||||
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
|
||||
log = out / (label + '.log')
|
||||
log.write_bytes(result.stdout)
|
||||
checks[label] = {'exit_code': result.returncode, 'log_sha256': sha(log)}
|
||||
if result.returncode:
|
||||
raise RuntimeError(label + ' failed; inspect private log ' + str(log))
|
||||
return result.stdout
|
||||
|
||||
def cargo(label, image, *args):
|
||||
target = ROOT / ('devstate/script-console-windows-target' if image == WINDOWS_IMAGE else 'devstate/script-console-target')
|
||||
target.mkdir(mode=0o700, exist_ok=True)
|
||||
return command(label, ['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, *args])
|
||||
|
||||
common = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline']
|
||||
cargo('format', LINUX_IMAGE, 'fmt', '--manifest-path', '/src/Cargo.toml', '--all', '--check')
|
||||
cargo('linux-clippy', LINUX_IMAGE, 'clippy', *common, '--workspace', '--all-targets', '--', '-D', 'warnings')
|
||||
cargo('linux-tests', LINUX_IMAGE, 'test', *common, '--workspace', '--all-targets')
|
||||
# Existing ignored DB contracts use their own fresh PostgreSQL, internal
|
||||
# network namespace only. No published port, production URL or real device.
|
||||
pg_name='rmm-script-contract-'+uuid.uuid4().hex[:12]
|
||||
command('postgres-start',['docker','run','-d','--network','none','--name',pg_name,'-e','POSTGRES_HOST_AUTH_METHOD=trust',POSTGRES_IMAGE])
|
||||
try:
|
||||
for _ in range(100):
|
||||
ready=subprocess.run(['docker','exec',pg_name,'pg_isready','-h','127.0.0.1','-U','postgres'],capture_output=True)
|
||||
if ready.returncode == 0: break
|
||||
time.sleep(.2)
|
||||
else: raise RuntimeError('Isolated PostgreSQL did not become ready')
|
||||
sql='CREATE ROLE rmm_app LOGIN NOINHERIT NOSUPERUSER NOBYPASSRLS;\n'+''.join(p.read_text()+'\n' for p in sorted((ROOT/'migrations').glob('*.sql')))
|
||||
result=subprocess.run(['docker','exec','-i',pg_name,'psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres'],input=sql.encode(),capture_output=True)
|
||||
(out/'postgres-migrations.log').write_bytes(result.stdout+result.stderr)
|
||||
if result.returncode: raise RuntimeError('Isolated migrations failed')
|
||||
command('postgres-contracts',['docker','run','--rm','--network','container:'+pg_name,'--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(ROOT)+':/src:ro','-v',str(ROOT/'devstate/script-console-target')+':/target','-e','CARGO_TARGET_DIR=/target','-e','RMM_TEST_REPAIR_ADMIN_URL=postgres://postgres@127.0.0.1/postgres','-e','RMM_TEST_REPAIR_APP_URL=postgres://rmm_app@127.0.0.1/postgres','--entrypoint','cargo',LINUX_IMAGE,'test',*common,'-p','rmm-server','--bin','rmm-server','--','--include-ignored','--test-threads=1'])
|
||||
finally:
|
||||
command('postgres-remove',['docker','rm','-f',pg_name])
|
||||
for feature in ('default', 'system-helper'):
|
||||
cargo('windows-' + feature + '-clippy', WINDOWS_IMAGE, 'clippy', *common,
|
||||
'--target', 'x86_64-pc-windows-gnu', '-p', 'rmm-agent-windows', '--all-targets',
|
||||
*(['--features', 'system-helper'] if feature == 'system-helper' else []), '--', '-D', 'warnings')
|
||||
raw = cargo('linux-unit-link', LINUX_IMAGE, 'test', *common, '--workspace', '--all-targets',
|
||||
'--target', 'x86_64-unknown-linux-gnu', '--release', '--no-run', '--message-format=json')
|
||||
selected = {'rmm_domain': 'domain-tests', 'rmm_agent_linux': 'linux-runtime-tests',
|
||||
'rmm-privileged-helper': 'helper-policy-tests', 'rmm-server': 'server-contract-tests'}
|
||||
artifacts = {}
|
||||
for line in raw.splitlines():
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
target = value.get('target', {})
|
||||
name = target.get('name')
|
||||
if (value.get('reason') == 'compiler-artifact' and value.get('executable')
|
||||
and value.get('profile', {}).get('test') and name in selected
|
||||
and target.get('kind') in (['lib'], ['bin'])):
|
||||
label = selected[name]
|
||||
if label in artifacts:
|
||||
raise RuntimeError('Duplicate selected test artifact: ' + label)
|
||||
source = ROOT / 'devstate/script-console-target' / Path(value['executable']).relative_to('/target')
|
||||
artifact = out / label
|
||||
shutil.copyfile(source, artifact)
|
||||
artifacts[label] = {'sha256': sha(artifact), 'bytes': artifact.stat().st_size,
|
||||
'native_linux_executed': False, 'native_windows_executed': False}
|
||||
if set(artifacts) != set(selected.values()):
|
||||
raise RuntimeError('Incomplete Linux unit artifact set')
|
||||
for label in artifacts:
|
||||
command(label + '-list', ['docker', 'run', '--rm', '--network', 'none', '--read-only',
|
||||
'--tmpfs', '/tmp:rw,exec,size=128m', '-v', str(out / label) + ':/unit:ro',
|
||||
'--entrypoint', 'python3', LINUX_IMAGE, '-c',
|
||||
'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit","--list","--format","terse"],check=True,cwd="/tmp")'])
|
||||
cargo('linux-binary-link', LINUX_IMAGE, 'build', *common, '--release',
|
||||
'--target', 'x86_64-unknown-linux-gnu', '-p', 'rmm-agent', '-p', 'rmm-privileged-helper', '-p', 'rmm-server', '--bins')
|
||||
for name in ('rmm-agent', 'rmm-privileged-helper', 'rmm-server'):
|
||||
artifact = out / name
|
||||
shutil.copyfile(ROOT / 'devstate/script-console-target/x86_64-unknown-linux-gnu/release' / name, artifact)
|
||||
artifacts[name] = {'sha256': sha(artifact), 'bytes': artifact.stat().st_size,
|
||||
'installed': False, 'native_executed': False}
|
||||
if inputs() != frozen:
|
||||
raise RuntimeError('Compiler/deployment inputs changed during qualification; no deployable manifest')
|
||||
archive = out / 'reviewed-sources.tar.gz'
|
||||
with tarfile.open(archive, 'w:gz') as tar:
|
||||
for name in frozen:
|
||||
tar.add(ROOT / name, arcname=name, recursive=False)
|
||||
manifest = {'schema_version': 1, 'type': 'rmm.script-console.local-source-qualification',
|
||||
'created_at': dt.datetime.now(dt.timezone.utc).isoformat(), 'profile': 'full_maintenance_v1',
|
||||
'images': {'linux': LINUX_IMAGE, 'windows_cross': WINDOWS_IMAGE, 'isolated_postgres': POSTGRES_IMAGE}, 'source_files': frozen,
|
||||
'source_before_after_equal': True, 'checks': checks, 'artifacts': artifacts,
|
||||
'source_archive_sha256': sha(archive), 'native_linux_executed': False,
|
||||
'native_windows_executed': False, 'target_state_writes': False, 'rmm_jobs': False,
|
||||
'capabilities_activated': False, 'approvals': False}
|
||||
path = out / 'manifest.json'
|
||||
path.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
print(json.dumps({'manifest': str(path), 'sha256': sha(path), 'native_executed': False}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+42
-1
@@ -1,6 +1,6 @@
|
||||
# Linux-first-Entwicklung und reale VM-Abnahme
|
||||
|
||||
Stand: 2026-11-14 · Spezifikation 1.19. Das begrenzte Linux-MVP ist inzwischen
|
||||
Stand: 2026-11-14 · Spezifikation 1.20. Das begrenzte Linux-MVP ist inzwischen
|
||||
dokumentiert abgenommen; aktuelle Nachweise stehen in [handover.md](handover.md).
|
||||
Die getrennte Windows-SYSTEM-Grenze ist in Spezifikation0.1 und
|
||||
[windows-system-policy.md](windows-system-policy.md) präzisiert; Quellen-/Build-
|
||||
@@ -17,6 +17,47 @@ Deploymentnachweise: [server-deployment.md](server-deployment.md).
|
||||
Die folgenden PC-Server-/Reverse-Tunnel-Abläufe und Nachweise sind historisch.
|
||||
TLS/mTLS, Credentialschutz, Linux-first und WebUI-Plangenehmigung gelten weiter.
|
||||
|
||||
## Vorrang: genehmigte Batch-Skriptkonsole (Version1.20)
|
||||
|
||||
Der User priorisiert vollständige Shell-/PowerShell-Skripte über MCP/UI mit
|
||||
expliziten Root-/SYSTEM-Rechten. Kapitel0.1 bindet das neue optionale
|
||||
`privileged_script_profile="full_maintenance_v1"` vor Genehmigung in Payload,
|
||||
Policy und WebUI. Alte Pläne/Profile bleiben unverändert; SCM/APT/MSI dürfen
|
||||
keine Vollwartung durch eine stille Lockerung erhalten. Bisherige M7-Aussagen
|
||||
zu Terminal/Sitzungen verschieben diese Batchkonsole nicht. Agent-Selbstupdates
|
||||
werden separat behandelt; Paketfixture-Abnahmen ersetzen sie nicht.
|
||||
|
||||
Geplanter, noch nicht ausgeführter Ablauf: additive bytekompatible Verträge und
|
||||
Policygrenzen implementieren; lokale betroffene Kompatibilitäts-/Fehlerprüfungen;
|
||||
reviewbare explizite Helper-/Policymigration unter Erhalt aller Identitäten,
|
||||
Journaldateien und Verbräuche; qualifizierte Linux-Cloud-Artefakte; neuer fester
|
||||
WebUI-genehmigter harmloser Vollwartungsplan auf der Linux-Cloud-VM; erst danach
|
||||
getrennte native Windows-SYSTEM-Abnahme auf dem Windowsgast. Kein RMM-Agent oder
|
||||
Server auf dem Notebook. Vor Zieländerungen konkrete Startbedingungen/Umfang
|
||||
festhalten, keine Ledgerresets oder impliziten Reboots/Updates.
|
||||
|
||||
Abnahme muss gespeicherte vollständige Skriptbytes samt Profil/Identität/Limits
|
||||
vor tatsächlicher WebUI-Genehmigung zeigen, vor Genehmigung Job-/Outbox-/Grant-
|
||||
Abwesenheit belegen und danach ehrliche Zustände/finale begrenzte stdout-/stderr-
|
||||
Rohbytes mit Trunkierung erfassen. Keine laufende Ausgabe vortäuschen: bestehende
|
||||
Jobstrecke liefert vorerst Abschlussausgabe. LinuxUID0 und WindowsSID18 sowie
|
||||
Clock/Sync/Peer-/Originalsignatur-/Einmalverbrauchsgrenzen getrennt nachweisen.
|
||||
Abbruch/Fence/Timeout prüfen nur im abgestimmten harmlosen Scope; unklare Wirkung
|
||||
bleibt unknown, kein blindes Wiederholen. Root/SYSTEM kann auch eigene Schutz-
|
||||
mechanismen ändern; keine Sandbox-/No-Reboot- oder vollständige Kindprozess-
|
||||
Eindämmungszusage. Ein Skript-Reboot ersetzt keine typisierte Rebootabnahme.
|
||||
|
||||
Die Norm ist beschlossen; lokale Quellen-/Buildnachweise und deren Grenzen
|
||||
stehen in [deploy/linux/full-maintenance-README.md](../deploy/linux/full-maintenance-README.md).
|
||||
Ein unabhängiger Review fand im ersten eingefrorenen Pack die fehlende tatsächliche
|
||||
Linux-Helperbinarybindung; dieser Pack bleibt nur früherer Beleg. Der enge
|
||||
Full-only-Corefix wurde unabhängig geprüft und im neuen Pack29461892 mit158
|
||||
unveränderten Inputs,285 lokalen Tests und45 tatsächlichen isolierten DB-Verträgen
|
||||
neu qualifiziert. Der separate Native-Runner ist vorbereitet, noch nicht
|
||||
Zielaktivierung oder VM-Abnahme; diese bleiben offen. Die bestehende begrenzte
|
||||
Linux-MVP-Abnahme wird nicht nachträglich zur Vollwartungsabnahme umgedeutet.
|
||||
Details/technischer Entwurf: [script-console-contract-proposal.md](script-console-contract-proposal.md).
|
||||
|
||||
## Begrenzte Windowsfreigaben (2026-11-14)
|
||||
|
||||
Der User erlaubt `RemoteSigned` ausschließlich je zuvor WebUI-genehmigtem
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
# Verbindliche Projektentscheidungen
|
||||
|
||||
Stand: **2026-11-14**, Spezifikation **1.19** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung.
|
||||
Stand: **2026-11-14**, Spezifikation **1.20** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung.
|
||||
|
||||
## Skriptkonsole und vollständige Hostwartung (Version1.20)
|
||||
|
||||
Der User stellt die Batch-Skriptkonsole vor weitere Paketfixture-Erweiterungen:
|
||||
KI/MCP schreibt vollständige Shell-/PowerShell-Skripte und beantragt feste
|
||||
Aufträge; der Mensch genehmigt exakt gespeicherte Bytes, Ziele, Interpreter,
|
||||
Argumente, Rechte und Limits in der WebUI. Status und abschließende begrenzte
|
||||
Rohbyteausgabe verwenden die bestehende Jobstrecke. Keine neue PTY-/ConPTY-
|
||||
Sitzung und kein behauptetes laufendes Streaming. Regelmäßiges passives
|
||||
Inventar/Heartbeat ist getrennt; Live-Erhebung per Skript bleibt Job.
|
||||
|
||||
Das neue additive Feld `privileged_script_profile="full_maintenance_v1"`
|
||||
bindet die ausdrücklich gewünschte Root-/SYSTEM-Hostwartung vor Genehmigung.
|
||||
Fehlend bleibt es aus alten Bytes ausgelassen; null/unbekannt/agent_service mit
|
||||
Profil verweigert. Bestehende Linux-Root-Skripte ohne Profil behalten ihre
|
||||
bisherige begrenzte Runtime. Windows-SYSTEM-Skripte brauchen das neue Profil;
|
||||
SCM-/MSI-Policies erben keine Skripterlaubnis. Die historische Aussage1.18
|
||||
„SYSTEM-Skripte außerhalb des engen SCM-Vertrags“ bleibt für dessen Profile
|
||||
richtig; sie verbietet nicht den nun gesondert beauftragten Vollwartungspfad.
|
||||
|
||||
Zentrale/lokale Policy erlauben Vollwartung nur ausdrücklich versioniert über
|
||||
`allowed_script_profiles`: Linuxversion2, Windowsversion3; fehlend bedeutet deny,
|
||||
vorhandene null/unbekannte Profile verweigern. `scripts:execute` plus jeweiliges
|
||||
`root:execute`/`system:execute` gelten für Ersteller und Freigeber aktuell;
|
||||
zusätzlich exakte Geräte-/Helperpins, qualifizierte Capability
|
||||
`script.full_maintenance/1`, TrustedClock und unabhängiger signierter Sync.
|
||||
Linux bekommt ein eigenes explizites Helperprofil; bisherige General-/APT-
|
||||
Sandboxprofile bleiben erhalten. Windows verwendet SID18 und einen eigenständig
|
||||
geprüften SYSTEM-Pfad. Volle Originalsignaturen, dauerhafter Einmalverbrauch,
|
||||
Intent/Dispatch/RawMirror/Abandon und Journalidentitäten werden weiterverwendet.
|
||||
|
||||
Vollwartung ist volle Hostautorität, einschließlich möglicher Agent-/PKI-
|
||||
Änderungen und Neustarts. Keine Sandbox-/No-Reboot-/Rollbackzusage für beliebigen
|
||||
Root-/SYSTEM-Code; nachgeladener Inhalt ist nicht automatisch gebunden. Jede
|
||||
Wirkung braucht ihren festen WebUI-Plan. Kein ungeplanter destruktiver Test,
|
||||
keine Rebootabnahme aus einem Skript. Timeout/Abbruch/unklare Wirkung bleiben
|
||||
ehrlich `unknown`, kein automatischer Retry oder nachträgliches Heilen durch
|
||||
Exit0. Eigene Prozesse werden kontrolliert beendet, fremde nicht übernommen.
|
||||
Die konkreten Bounds und Kompatibilitätsregeln stehen in Spezifikation0.1.
|
||||
|
||||
Dies ändert den Produktauftrag, behauptet keine Implementierung oder native
|
||||
Abnahme. Linux-Cloud-VM zuerst; Windows-VM separat; Notebook nur Entwicklung.
|
||||
Die zusätzliche tatsächliche Linux-Helperbinarybindung des Fullprofils ist
|
||||
verpflichtend: geschützter Schema2-Pin, gehaltenes laufendes Rootimage,
|
||||
authentisierte Probe und passende zusätzliche Binärcapability; keine
|
||||
Agent-/proc-Lesebehauptung und keine Änderung der General-/APT-Legacybytes.
|
||||
Lokale frühere Qualifikation und noch offener separater Korrekturdurchlauf:
|
||||
[deploy/linux/full-maintenance-README.md](../deploy/linux/full-maintenance-README.md).
|
||||
Agent-Selbstupdates sind ein getrennter signierter Updatepfad; APT/MSI-
|
||||
Paketfixtures und Vollwartungsskripte sind keine fertigen Agent-Autoupdater.
|
||||
|
||||
## Enger Windows-M4-MSI-Schnitt (Version1.19)
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
# Skriptkonsole: Root-/SYSTEM-Vertrag1.20 und tatsächliche Nachweise
|
||||
|
||||
> **Aktualisierung1.20, 2026-11-14:** Der User und Rootreview haben den nun in
|
||||
> Spezifikation0.1, project-decisions und development dokumentierten Vollwartungs-
|
||||
> vertrag beschlossen. Der folgende ursprüngliche Entwurf ist als historische
|
||||
> Herleitung zu lesen: Insbesondere „kein neues Wirefeld“ und die Beibehaltung
|
||||
> des beschränkten Generalprofils als Wartungsruntime sind überstimmt. Aktuell
|
||||
> gilt das additive `privileged_script_profile="full_maintenance_v1"`, getrennte
|
||||
> explizite Policyversionen und eine eigene Linux-Helperroute. Kein stilles
|
||||
> Erweitern von General/APT/SCM/MSI. Quelle/Build/Unit/Native weiterhin getrennt.
|
||||
|
||||
|
||||
**Ursprünglicher Entwurfsstand**, Basis `287a784`: Damals noch nicht
|
||||
beschlossen oder implementiert. Der aktuelle beschlossene Vertrag und die
|
||||
späteren tatsächlichen Quellen-/Prüfnachweise stehen oben und am Dateiende.
|
||||
Dieser neue Fokus ersetzt die EXE-Priorität; der EXE-Normpatch bleibt ein
|
||||
unbeschlossener separater Archivstand. Vollständige Pflichtdokumente wurden
|
||||
gelesen; Spec1.19/PD/Dev sind bytegleich zum zuvor vollständig gelesenen Stand.
|
||||
Hier werden nur vorhandene Pfade auditiert und konkrete Änderungen vorgeschlagen.
|
||||
Kein Produkt-/Norm-/APIcode, Build, VMkontakt oder Ausführungsjob geändert.
|
||||
|
||||
## Bereits vorhanden und tatsächliche Lücken
|
||||
|
||||
`web/src/main.tsx`75–90 hat bereits vollständigen UTF-8-Editor, Linux/Windows-
|
||||
Plattformwahl, feste Interpreter, erwartete stdout-Nachbedingung und explizite
|
||||
Identitätsauswahl. Planansicht/Recheck/Submit/Approval bestehen. Operations- und
|
||||
Jobdetails152–165 pollen tatsächlich Zustand/Ergebnis und bieten Abbruch an.
|
||||
Ausgabe erscheint bisher nur im allgemeinen JSON, nicht als lesbare Konsole.
|
||||
SYSTEM ist für RunScript in UI, Domain, Backendpolicy und Helper bewusst gesperrt.
|
||||
|
||||
Linux-Rootskripte existieren: zentral `root_policy.rs` mit `allow_root_scripts`,
|
||||
`root:execute` und den allgemeinen Skriptrechten; lokal unabhängiges
|
||||
`allow_root_scripts`, NativeClock/RootSync und atomarer Originalgrantverbrauch.
|
||||
`privileged-helper::script` nutzt den vorhandenen Linux-Adapter. Dessen
|
||||
`process::run` hat Prozessgruppe, feste Umgebung, Timeout und beschränkte Pipes,
|
||||
aber **keine laufende Cancel-/Fenceabfrage**. Ein Timeout oder unbelegtes Ende
|
||||
wird Unknown; ein Kill beweist keine rückgängig gemachten Wirkungen.
|
||||
|
||||
Windows hat einen sicheren PowerShell-Datei-/JobObject-Pfad in `actions.rs` und
|
||||
`process.rs`, ist aber ausdrücklich LocalService/SID19. Ein Umbenennen der
|
||||
Identität wäre falsch. SYSTEM muss unter dem tatsächlich authentisierten
|
||||
SYSTEM-Helper/SID18 starten und dessen privaten Arbeitsbereich verwenden.
|
||||
Intent/Abandon/RawMirror sind vorhanden; WindowsClock bleibt ohne echten
|
||||
TrustedClock-Nachweis geschlossen. Linuxbelege ersetzen diesen nicht.
|
||||
|
||||
Der aktuelle Protobufvertrag hat nur `JobResult.stdout/stderr`; keinen
|
||||
JobOutputChunk und keinen implementierten JobProgress-Outputstream. Kleinster
|
||||
vollständiger Batch-Skriptkonsolenpfad: während Ausführung echte Statusanzeige,
|
||||
Laufzeit und Cancel-Anforderung; begrenzte stdout/stderr mit Rohbytes nach
|
||||
dauerhaftem Ergebnis. **Keine behauptete Liveausgabe oder interaktive PTY.**
|
||||
Falls Root/User Ausgabe bereits während der Ausführung verlangt, ist dafür ein
|
||||
separat zu prüfender begrenzter dauerhafter Chunkvertrag erforderlich; kein
|
||||
UI-Polling von flüchtigen Helperdateien oder vorgetäuschtes Streaming.
|
||||
|
||||
## Enger Funktions- und Autoritätsvertrag
|
||||
|
||||
Weiterhin genau `RunScript`, kein neues Actionformat, universeller Execute-
|
||||
Endpoint oder Terminalserver. Default bleibt `agent_service`; Root/SYSTEM nur
|
||||
ausdrücklich gewählt. Die kompletten eingegebenen UTF-8-Bytes, Interpreter,
|
||||
Argumente, Ausgabe-/Zeitlimit, Identität, Plattformvariante und gegebenenfalls
|
||||
vorhandenes PowerShell-RemoteSigned-Profil werden **vor** Hash/Planbindung
|
||||
festgeschrieben. Kein BOM-/Zeilenenden-/Prolognachrüsten nach Genehmigung.
|
||||
Nicht-ASCII-PowerShell braucht das bestehende explizite BOM im Editorinhalt.
|
||||
UI darf Argumente zunächst als feste leere Liste halten; keine freien
|
||||
Executablepfade, URLs oder `-Command`-/EncodedCommand-Launcherparameter.
|
||||
Linux verwendet `/bin/sh -- <privateDatei>` oder nachgewiesenes `/bin/bash`;
|
||||
Windows fest WindowsPowerShell5.1 mit `-NoLogo -NoProfile -NonInteractive`,
|
||||
optional genehmigtem prozessbezogenen RemoteSigned und `-File <privateDatei>`.
|
||||
Kein pwsh-Fallback oder ExecutionPolicy-Abschalten, GPO bleibt vorrangig.
|
||||
|
||||
Jeder Auftrag bleibt pending_approval ohne Jobs/Outbox/Offers/Grants bis zum
|
||||
tatsächlichen WebUI-Klick. Ersteller **und** Freigeber benötigen ihre aktuellen
|
||||
Operationsrechte und `scripts:execute`, zusätzlich `root:execute` bzw.
|
||||
`system:execute`. Keine neuen allgemeinen Rechtebezeichner, kein Autoapprove.
|
||||
Zentrale geräte-/principal-/generations-/helperhashgebundene Policy und lokale
|
||||
Helperpolicy müssen privilegierte Skripte zusätzlich ausdrücklich zulassen.
|
||||
Linux verwendet das bestehende Opt-in; Windows erhält ein versioniertes
|
||||
`allow_system_scripts`-Opt-in, alte SCM/MSI-Settings verweigern weiter Skripte.
|
||||
Interpreter und Maximalbudget sind feste überprüfbare Grenzen, keine
|
||||
Befehlsblockliste. Erforderlich bleiben bisherige Plattform-/Interpretercaps,
|
||||
Helperpins und signedSync; SYSTEM braucht zusätzlich die enge
|
||||
`system:run_script`-Capability. Nichts davon aus Build oder Bootstrap publizieren.
|
||||
|
||||
Kleinste erste Grenzen: Skript1–32768Bytes, insgesamt höchstens65536Bytes
|
||||
stdout+stderr, Laufzeit1–300s für Linux-Root wie der vorhandene zentrale Deckel;
|
||||
SYSTEM zunächst1–120s wie die vorhandene Helper-Lane. UI validiert diese
|
||||
tatsächlichen Grenzen vor Planung. Größere Budgets sind keine stillen Defaults.
|
||||
Keine Wire-/JobPayload-/Grantcodecänderung nötig; Linux- und bisherige
|
||||
agent_service-/PowerShell-RemoteSigned-Goldens bleiben erhalten.
|
||||
|
||||
## Tatsächliche Privilegien, Sandbox und Reboot
|
||||
|
||||
**Ein genehmigtes allgemeines Root-/SYSTEM-Skript ist bewusste Volladministration
|
||||
im tatsächlich gestarteten Dienstkontext, keine sichere Standardaktion.**
|
||||
Es kann Dateien/PKI/Journale, Konten, Dienste, Paketmanager, Egress und gegebenenfalls
|
||||
den OS-Neustart beeinflussen oder andere Programme nachladen. Der gebundene
|
||||
Skripttext pinnt nicht automatisch alle später von ihm gelesenen Programme und
|
||||
Netzbytes. Keine Befehlsblockliste kann das zu einem harmlosen Profil machen.
|
||||
Ein Angreifer mit genehmigtem Rootcode ist außerhalb der Integritätsgarantie
|
||||
dieses lokalen Helpers; Benutzer mit diesem Recht müssen als Hostadministratoren
|
||||
vertrauenswürdig sein. Die Freigabe ist niemals eine KI-Dauerberechtigung.
|
||||
|
||||
Der aktuelle Linux-Generalhelper ist tatsächlich UID0, hat aber unter anderem
|
||||
PrivateNetwork, ProtectSystem, begrenzte Capabilities und Seccomp. Diese Grenzen
|
||||
bleiben im ersten Integrationsslice **unverändert**; manche Skripte werden damit
|
||||
ehrlich fehlschlagen. Sie sind kein zugesicherter Sandboxschutz gegen allgemeinen
|
||||
Rootcode, insbesondere nicht gegen Delegation an vorhandene privilegierte
|
||||
Betriebssystemdienste. UI muss UID0/SID18 und den konkreten qualifizierten
|
||||
Runtime-/Policykontext zeigen, nicht „uneingeschränkte Hostrechte“ erfinden.
|
||||
Falls uneingeschränkter Hostkontext benötigt wird, braucht er einen gesonderten
|
||||
explizit geprüften und gepinnten Bootstrapprofilwechsel; keine stille Entgrenzung
|
||||
der vorhandenen Helper-/APT-/MSI-Dienste im Skriptslice.
|
||||
|
||||
Eine Skriptgenehmigung erlaubt die sichtbaren Skriptbytes und deren mögliche
|
||||
administrative Wirkung, **keinen zusätzlichen RMM-Reboot-/Paketjob**. Skript-
|
||||
Exit0 beweist nur Prozess-/gebundene stdout-Nachbedingung, keine Paketabnahme.
|
||||
Ein vom Skript ausgelöster Neustart ist kein erfolgreicher typisierter Rebootjob:
|
||||
ohne dessen eigenen unabhängigen Vorher-/Nachher-/Fristbeleg bleibt der
|
||||
Skriptversuch bei fehlendem Ergebnis Unknown. Keine implizite OS-Rebootabnahme,
|
||||
kein nochmaliges Ausführen nach Reconnect und keine aus einem Warntext abgeleitete
|
||||
allgemeine Erlaubnis, tatsächliche Testreboots/Updates durchzuführen.
|
||||
|
||||
## Dauerhaftigkeit, Abbruch und lesbare Ausgabe
|
||||
|
||||
Dieselbe OriginalRequest-/Plan-/Grantprüfung, ein einziger atomarer Start,
|
||||
Outcome zuerst dauerhaft, dann Jobjournal/Ergebnis und normaler SignedSync.
|
||||
Windows verwendet genau den vorhandenen Intent→MayHaveDispatched→Helper-/
|
||||
RawFullTupleMirror-Pfad. Abandon ausschließlich bei belegtem Nichtdispatch,
|
||||
ohne Script-/Temporärdateiwirkung; Originalgrant nie leeren, Unknown/Missing-
|
||||
Guards nie lockern. Keine zweite Zustandsmaschine oder Ausführungswiederholung.
|
||||
|
||||
Linuxprozess erhält einen tatsächlichen kooperativen Cancel-/Fencecallback
|
||||
innerhalb der bestehenden Poll-/Pipe-Schleife. Windows nutzt den vorhandenen
|
||||
JobObject-Prozessbaum mit tatsächlichem SYSTEM-Token und entsprechender
|
||||
Fence-/Cancelprüfung. Nur der eigene beobachtete Prozessbaum darf begrenzt
|
||||
beendet werden; kein globales Kill. Abbruch/Timeout nach möglicher Wirkung
|
||||
bleibt Unknown. Kernelbestätigtes Prozessende ist kein NoEffect-/Rollbackbeweis.
|
||||
Ein durch Root/SYSTEM abgespalteter Dienst/Task kann außerhalb des beobachteten
|
||||
Baums weiterwirken; keine vollständige Prozesskonfinierung behaupten. Wenn
|
||||
Beendigung nicht bestätigt ist, behält der Helper eigene Child-/Handlebindung
|
||||
und die Ressourcensperre; kein neuer Start aus bloßem Pipe-/Channelclose.
|
||||
|
||||
UI zeigt getrennte stdout/stderr, Exitcode, Trunkierung, tatsächliche Identität,
|
||||
Zustand/Unknown und Cancelstatus. Rohbytes bleiben unverändert gespeichert;
|
||||
Textdarstellung bekommt explizite Decoder-/Encodingangabe und optional Byteansicht,
|
||||
keine stillen Ersatzzeichen als Originaloutput ausgeben. Nur Reacttext, kein
|
||||
HTML/ANSI-Scriptinterpretieren oder zustandsändernde Aktion aus Logtext.
|
||||
Anzeigenaliase und später mutierte APIobjekte müssen gegen gespeicherte
|
||||
Planpayloadbytes geprüft werden, auch für Linuxroot und WindowsSYSTEM.
|
||||
|
||||
## Reihenfolge und kleinste Dateigrenzen nach Rootreview
|
||||
|
||||
1. Root beschließt den Skriptvertrag1.20; EXE1.20 wird nicht übernommen.
|
||||
2. UI-Konsole/Rootpfad und Cancel-/Outcomeownership lokal qualifizieren;
|
||||
danach tatsächlicher Cloud-Linux-RunScript mit WebUI-Genehmigung, stdout/stderr,
|
||||
Rootidentität, einmaligem Grant und verlorenem Reply/Abbruch korrekt nachweisen.
|
||||
3. SYSTEMpfad sourceimplementieren, portable Guards Linux-first→Windows;
|
||||
erst nach echter Clock-/Peer-/Helper-/PERSISTqualifikation Windows-Skriptjobs
|
||||
per WebUI. Keine Windowsfähigkeit aus dem Linuxnachweis ableiten.
|
||||
|
||||
| Scope | Engste Änderungen nach Freigabe |
|
||||
| --- | --- |
|
||||
| Norm | Root: Spec1.20/PD/Dev für Skripte statt EXE; explizite Administrator-/Rebootgrenzen |
|
||||
| Web | bestehende main/api/safety+betroffene Tests: vorhandenen Editor behalten, SYSTEM-Option für RunScript, verifiedScriptProjection, lesbare Ausgabe/Cancelstatus |
|
||||
| Linux | agent-linux actions/process; privileged-helper script/main/control und Agenthelper-Routing nur soweit Cancel/gebundene Ownership nötig; keine stille Unitlockerung |
|
||||
| Windows | actions/process um explizite getrennte LocalService-/SYSTEM-Einstiege; helper_system/helper_runtime/runtime um RunScript unter bestehenden Intent-/Mirrorgrenzen; private gehaltene SYSTEM-Skriptdatei |
|
||||
| Domain/Backend | jobs.available_for/valid_helper_denial_shape; windows_policy und vorhandene DTO-/Gateprüfungen, bisheriger Rootpfad erhalten; neue lokale bool-Settings nur versioniert und None-omit |
|
||||
| Core/Protocol/SQL | keine neue Zustandsmaschine oder Job-/Grantfelder geplant; bestehende Codecs/Unlocks unverändert, Chunktransport ausdrücklich nicht Bestandteil des ersten Batchpfads |
|
||||
|
||||
Alle Angaben oberhalb sind Sourceaudit und Entwurf. Tatsächliche privilegierte
|
||||
Skript-/Abbruch-/Runtimeabnahmen bleiben offen, bis Root sie getrennt ausführt.
|
||||
|
||||
## Implementierungsstand des genehmigten1.20-Schnitts
|
||||
|
||||
Lokal implementiert: additives strikt nichtnull Profil am Ende der RunScript-
|
||||
Action, Identitäts-/Capability-/Laufzeit-/Outputgrenzen und unveränderte Legacy-
|
||||
Bytes; drei echte Rust-Codecplanfamilien in `tests/script_console/codec-golden.json`.
|
||||
Zentrale Rootversion2 und SYSTEMversion3 erfordern zusätzliche explizite
|
||||
`allowed_script_profiles`; beide Akteure benötigen aktuelle Skript- und jeweilige
|
||||
Privilegrechte. Eigene Linuxroute `RMM_FULL_MAINTENANCE_HELPER_SOCKET` mit
|
||||
`RMM_FULL_MAINTENANCE_POLICY_FILE`, lokalem FullMaintenanceprofil und unverändertem
|
||||
Sharedledger; bestehende General-/APT-Dienste werden nicht geändert.
|
||||
|
||||
`deploy/linux/rmm-full-maintenance-helper.service` ist ein reviewbarer, noch
|
||||
nicht installierter vollständiger Hostkontext ohne die General-Sandbox. Vor
|
||||
Zieländerung sind tatsächliche zusammengesetzte Unit, Gruppen-/Socket-/Pinpfade,
|
||||
Rootbesitz, Journale und Inodes zu prüfen. Der eigene Socket und Pin müssen
|
||||
explizit auf das FullMaintenanceprofil zeigen; kein Fallback auf General/APT.
|
||||
Eine passende Bootstrapkonfiguration enthält `profile=full_maintenance_v1`,
|
||||
`allow_root_scripts=true`, `allowed_script_profiles=["full_maintenance_v1"]`,
|
||||
leere allowed_services, allow_reboot=false und keinen apt_provider. Das letzte
|
||||
Flag begrenzt nur die typisierte Helperaction, nicht den genehmigten Rootcode.
|
||||
|
||||
Laufender Linuxabbruch benutzt ausschließlich EOF/Halbschließen des vorhandenen
|
||||
originalrequestgebundenen, beidseitig peergeprüften Unixstreams. Der Agent
|
||||
beobachtet konkreten Attempt-Cancel, aktuelle Kanalgeneration und lokale Clock;
|
||||
der Helper beobachtet Peer/EOF/Clock. Ein abgelaufenes Startticket beendet keinen
|
||||
bereits gültig begonnenen Prozess. Eigene Prozessgruppe wird beendet und unter
|
||||
beibehaltener lokaler Effektlock bis zum belegten Ende lebender Mitglieder
|
||||
beobachtet. Zombieeinträge werden anhand ihres tatsächlichen /proc-Status von
|
||||
lebender Wirkung unterschieden, bei unklarer Beobachtung bleibt die Lock erhalten.
|
||||
|
||||
Windows besitzt einen gesonderten SYSTEM-Skriptpfad nach atomarem Verbrauch,
|
||||
mit privater gehaltenem Skriptdateihandle, exakt erhaltenen Bytes, festem
|
||||
PowerShell5.1-argv und JobObject. Clock/Peer/Intent/STOP bleiben beobachtet,
|
||||
Originalgrant wird unmittelbar vor Prozessstart frisch geprüft. Nach Start
|
||||
bleibt seine Startfrist eine Startfrist. Unklare Prozessbereinigung behält
|
||||
JobObject/Prozesshandles und Helperlane bis zum belegten Ende. SID18 und Profil-
|
||||
/Skripthash werden im Ergebnis gebunden; LocalService-Admission bleibt separat.
|
||||
Keine neue Windowscapability ist durch diese Quellen öffentlich aktiviert.
|
||||
|
||||
Tatsächliche Zwischenprüfung:22 Domain-Tests lokal im unveränderten Offline-
|
||||
Builder9a76ad37… bestanden, einschließlich alter Bytegoldens und neuer Profile.
|
||||
Weitere Prüfungen und native Cloud-Linux-/Windows-Abnahmen sind noch offen;
|
||||
kein neues RMM-Zielprofil installiert, kein Job gestartet oder genehmigt.
|
||||
|
||||
## Eingefrorene lokale Qualifikation1.20
|
||||
|
||||
Der abschließende lokale Lauf ist vollständig:157 Compiler-/Include-/Fixture-/
|
||||
Deploymentinputs unverändert vor/nach; Manifest
|
||||
`60a50262f9f8d85c11eb58e1a9e0f6e03be6cd5db7a59bc1745fb7d9dc8a6f65`.
|
||||
Linuxfmt/Workspace-Alltargets-Clippy mit -Dwarnings bestanden;284 lokale Tests
|
||||
bestanden und zunächst5DB-Fälle ausgelassen, anschließend sämtliche45Servertests
|
||||
inklusive dieser5 in frischem internem PostgreSQL bestanden (0ignored). WindowsGNU
|
||||
Default/Systemhelper-Alltargets-Clippy bestanden; keine native Windowsprüfung.
|
||||
Release-Linux-Unitlisten und Agent-/Helper-/Serverbinaries sind gebunden gebaut,
|
||||
noch nicht auf Zielen ausgeführt oder installiert. Vorherige unvollständige
|
||||
Packvorbereitungen sind separat protokolliert, keine bestandenen Qualifikationen.
|
||||
|
||||
Der separate Create-once-Linuxrunner ist vorbereitet, noch nicht ausgeführt;
|
||||
kein Compilerinput wurde dafür verändert. Konkrete lokale Belege, geplante
|
||||
Befehle, Erwartung83PASS/5expliziteDBignored auf Cloud-Linux und die noch nötige
|
||||
Erhaltungs-/Bootstrap-/WebUI-Abnahme stehen in
|
||||
[deploy/linux/full-maintenance-README.md](../deploy/linux/full-maintenance-README.md).
|
||||
|
||||
|
||||
## Separater Reviewblocker nach der ersten Qualifikation
|
||||
|
||||
Ein unabhängiger Review fand nach Packde34 die fehlende tatsächliche laufende
|
||||
Linux-Fullhelperbinarybindung. Dieser Pack bleibt unverändert früherer Beleg
|
||||
und berechtigt keine Fullaktivierung. Ein enger separater Corefix bindet
|
||||
`helper_binary_sha256` ausschließlich im neuen Fullschema/Pin/Policy/Probe und
|
||||
zentralen Scope; Root hält/prüft sein echtes laufendes Image, Agent993 benötigt
|
||||
keinen fremden Root-/proc-Zugriff. General/APT lassen die neuen None-Felder
|
||||
vollständig aus. Core-Review erfolgt vor neuem Build; neue tatsächliche
|
||||
Quellen-/Unit-/VM-Belege werden separat ergänzt, nicht vom alten Pack abgeleitet.
|
||||
Der Native-Runner ist vorbereitet und lokal geparst, noch nicht ausgeführt.
|
||||
|
||||
|
||||
## Neue tatsächliche lokale Qualifikation nach Binärpinfix
|
||||
|
||||
Der neue Pack29461892 ist ein eigener Beleg; de34 und der ursprüngliche Reviewdiff
|
||||
bleiben erhalten. Manifest
|
||||
`ddd1a78d1cd289b02b1f98572f9652171ec00be84e01ce099fd722d689bcaacd`,
|
||||
158 Inputs unverändert vor/nach. Format und Linux-/beide Windows-GNU-Clippyprofile
|
||||
mit-Dwarnings bestanden;285 lokale Tests bestanden, anschließend alle45Servertests
|
||||
mit tatsächlichem isoliertem PostgreSQL einschließlich vorheriger5DBignored
|
||||
bestanden (0ignored). Der neue Rootimage-Test prüft in jedem Eigentümerpfad
|
||||
Sicherheitsassertions, kein stilles Skip. Native Linuxlisten22/16/6/45 gebaut,
|
||||
auf der Cloud-VM noch nicht ausgeführt; neue Erwartung84PASS/5expliziteDBignored.
|
||||
Der Native-Runner ist separat ausdrücklich auf diesen neuen Pack gebunden und
|
||||
lokal geparst; seine Supportquellen/Scopetatsachen sind in Intent und Readback
|
||||
streng geprüft. Bisher keine SSH-, VM-, Enrollment-, Dienst-, Policy-, Job- oder
|
||||
Capabilityänderung durch diesen Strang. Aktueller Primärstand und noch geplante
|
||||
Bootstrap-/WebUI-Abnahmen: `deploy/linux/full-maintenance-README.md`.
|
||||
|
||||
## Tatsächlich nativ auf Cloud-Linux geprüft
|
||||
|
||||
Der korrigierte158-Input-Pack29461892/ddd1a78d wurde durch Root nach beiden
|
||||
Source-Reviews auf der tatsächlichen Cloud-Linux-Test-VM ausgeführt. Fall
|
||||
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`: Domain22, Linuxruntime16,
|
||||
Helperpolicy6, Serververträge40PASS plus5explizite DBignored; insgesamt84PASS.
|
||||
Alle vollständigen Listen wurden zuerst geprüft. Die fünf DBfälle sind nur
|
||||
im separaten isolierten45er-PostgreSQL-Lauf nachgewiesen. NativeproofSHA256
|
||||
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
|
||||
Keine Zielruntime bereitgestellt oder Job-/Capability-/Policyfreigabe. Die
|
||||
tatsächliche WebUI-genehmigte volle Wartung bleibt ein eigener offener Schritt.
|
||||
@@ -33,10 +33,12 @@ fn fixture() -> (RootScope, JobPayload, Vec<String>) {
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
principals: vec!["selected".into()],
|
||||
helper_binary_sha256: None,
|
||||
helper_policy_sha256: "ab".repeat(32),
|
||||
acceptance_evidence_id: "reviewed-helper-record".into(),
|
||||
allowed_services: vec!["mutation-only.service".into()],
|
||||
allow_root_scripts: false,
|
||||
allowed_script_profiles: None,
|
||||
allow_reboot: false,
|
||||
apt: None,
|
||||
root_logs: Some(RootLogPolicy {
|
||||
|
||||
@@ -61,8 +61,8 @@ test('simulated human prepares root request through UI only, without approving',
|
||||
await page.getByLabel('Begründung', { exact: true }).fill(text(request.reason));
|
||||
await page.getByRole('button', { name: 'Plan erstellen · noch keine Ausführung' }).click();
|
||||
const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) });
|
||||
await expect(detail.locator('pre')).toBeVisible();
|
||||
const plan = object(JSON.parse(await detail.locator('pre').innerText()));
|
||||
await expect(detail.locator('pre[aria-label^="Alle festen Zielpreviews"]')).toBeVisible();
|
||||
const plan = object(JSON.parse(await detail.locator('pre[aria-label^="Alle festen Zielpreviews"]').innerText()));
|
||||
expect(createHash('sha256').update(bytes(plan.plan_payload_bytes)).digest('hex')).toBe(plan.plan_hash);
|
||||
await detail.getByRole('button', { name: 'Antrag absenden · pending_approval' }).click();
|
||||
const op = page.locator('section').filter({ has: page.getByRole('heading', { name: /^Antrag \/ Ausführung / }) });
|
||||
@@ -102,8 +102,8 @@ test('one opted-in immutable dev/test action: inspect all fixed bytes → UI cli
|
||||
await expect(op.locator('pre').first()).toContainText('"execution_state": null');
|
||||
await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen' }).click();
|
||||
const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) });
|
||||
await expect(detail.locator('pre')).toBeVisible();
|
||||
const plan = object(JSON.parse(await detail.locator('pre').innerText()));
|
||||
await expect(detail.locator('pre[aria-label^="Alle festen Zielpreviews"]')).toBeVisible();
|
||||
const plan = object(JSON.parse(await detail.locator('pre[aria-label^="Alle festen Zielpreviews"]').innerText()));
|
||||
expect(plan.plan_hash).toBe(expected.plan_hash);
|
||||
expect(bytes(plan.plan_payload_bytes)).toEqual(bytes(expected.plan_payload_bytes));
|
||||
expect(createHash('sha256').update(bytes(plan.plan_payload_bytes)).digest('hex')).toBe(expected.plan_hash);
|
||||
|
||||
@@ -15,10 +15,10 @@ test('preserved real VM: pending fixed Hello World → UI click → confirmed re
|
||||
await expect(op.locator('pre').first()).toContainText('"execution_state": null');
|
||||
await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen' }).click();
|
||||
const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) });
|
||||
await expect(detail.locator('pre')).toBeVisible();
|
||||
await expect(detail.locator('pre[aria-label^="Alle festen Zielpreviews"]')).toBeVisible();
|
||||
// Inspect the complete rendered immutable preview, not a separately fetched
|
||||
// or caller-supplied payload. Refuse all root/package/reboot/extra-target jobs.
|
||||
const plan = JSON.parse(await detail.locator('pre').innerText());
|
||||
const plan = JSON.parse(await detail.locator('pre[aria-label^="Alle festen Zielpreviews"]').innerText());
|
||||
expect(plan.resolved_targets).toHaveLength(1);
|
||||
expect(plan.resolved_targets[0].asset_id).toBe(asset);
|
||||
expect(plan.jobs).toHaveLength(1);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+63
-6
@@ -1,6 +1,6 @@
|
||||
# Linux-MVP WebUI
|
||||
|
||||
React/TypeScript, no runtime demo data, no desktop/terminal/hypervisor integration.
|
||||
React/TypeScript, no runtime demo data, no desktop/PTY/hypervisor integration.
|
||||
Build assets: **`web/dist/`**; serve `index.html` and `/assets/*` from the TLS backend
|
||||
on the same origin. Do not proxy authentication to a different origin. All API URLs
|
||||
are relative; cookies use `credentials: same-origin`, mutations use `X-CSRF-Token`.
|
||||
@@ -10,8 +10,64 @@ No token or password persistence, raw HTML rendering, automatic approval or retr
|
||||
|
||||
From `web/`: `npm ci`, `npm run typecheck`, `npm test`, `npm run build`.
|
||||
`npm run dev` binds loopback, but is not the authenticated TLS acceptance setup.
|
||||
The authoritative runtime is the backend serving `web/dist` at
|
||||
`https://rmm-dev.internal:18443`. No certificate-verification bypass is supported.
|
||||
The current server is `discovery.ease-technologies.de`; management access uses the
|
||||
configured SSH tunnel and verified TLS. Earlier local `rmm-dev.internal:18443`
|
||||
examples below are historical. The notebook is development only, without an RMM
|
||||
server or enrolled agent. No certificate-verification bypass is supported.
|
||||
|
||||
## Script console (specification 1.20, source implementation)
|
||||
|
||||
`run_script` remains a durable plan/request, not a PTY or interactive terminal.
|
||||
The planner accepts complete fixed POSIX/Bash or Windows PowerShell5.1 scripts.
|
||||
The optional action-wide `parameters.privileged_script_profile` is exactly
|
||||
`full_maintenance_v1`; missing preserves the existing bounded mode, while present
|
||||
null/unknown values fail. Full maintenance requires root on Linux or SYSTEM on
|
||||
Windows, plus `scripts:execute` and the separate root/system scope. SYSTEM scripts
|
||||
require the explicit profile. The UI selection grants no permission: central/local
|
||||
opt-in, target capabilities, independent helper checks and actual WebUI approval
|
||||
remain necessary. Full authority includes filesystem, network and services, and
|
||||
can alter the agent/PKI or cause a reboot. It has no sandbox/no-reboot promise.
|
||||
The profile budgets are Linux 1–300s, Windows 1–120s, at most 32768 script bytes
|
||||
and 65536 output bytes. RemoteSigned, when explicitly bound, remains limited to
|
||||
the approved Windows job process.
|
||||
|
||||
Before submit/approval, `src/script-console.ts` projects every script from the
|
||||
SHA256-verified stored plan bytes. It checks full payload structure, fixed
|
||||
target/job/attempt IDs, script SHA256 and the job SHA256 reconstructed in Rust
|
||||
declaration order. Every supplied payload/target alias must agree. It snapshots
|
||||
the checked views, rejects later mutation and rechecks immediately before each
|
||||
submit/approval action. The displayed script, arguments, identity, profiles,
|
||||
budgets, deadlines and hashes come from that projection, never the draft editor.
|
||||
Control characters, CR, BOM and bidi controls are made visible in the text view;
|
||||
the full original JSON and stored bytes remain available. Existing pending-only
|
||||
submission and interactivity/CSRF checks remain in force.
|
||||
|
||||
`src/console-output.tsx` displays the actual stored job status and final stdout/
|
||||
stderr. Status polling is every four seconds; output arrives with the durable
|
||||
result. There is no incremental output stream. Null result, empty output,
|
||||
unknown exit code, unknown outcome, requested cancellation and truncation are
|
||||
distinct. UTF-8 is a display attempt, not a claimed source encoding; invalid
|
||||
UTF-8 is marked and original bytes can be downloaded as inert `.bin` files.
|
||||
Terminal escapes and bidi controls are visible, never interpreted. Agent output
|
||||
is React text and cannot create HTML, approval controls or follow-up jobs.
|
||||
|
||||
MCP already dispatches plan/submit/read-results to the same server application
|
||||
functions. Shared PlanRequest/Action schemas expose the profile; MCP has no
|
||||
approval tool and its bearer context cannot become an interactive approval
|
||||
session. No independent MCP execution or approval path was added.
|
||||
|
||||
Local typechecking and renderer tests are source evidence only. Native Linux/
|
||||
Windows runs, deployment and actual UI/MCP acceptance remain separate gates.
|
||||
Actually executed on 2026-11-14 for this source slice: `npm ci --ignore-scripts
|
||||
--no-audit --no-fund`, `npm run typecheck`, `npm test` (49 passed across seven
|
||||
files), `npm run build` (TypeScript and Vite passed). Five script-console tests
|
||||
read `../tests/script_console/codec-golden.json` directly: the same three actual
|
||||
Rust codec families cover legacy Linux agent, Linux root/full and Windows
|
||||
SYSTEM/full with RemoteSigned. Checks cover full displayed script/target/attempt/
|
||||
profile/budgets/hashes, all aliases, mutation during/after verification and
|
||||
independent scopes. Two output tests cover hostile HTML/terminal/bidi bytes,
|
||||
unknown/cancellation/truncation, invalid encodings and absent/invalid results.
|
||||
No browser, server, VM job, approval or deployment was executed in these checks.
|
||||
|
||||
## JSON adapter contract
|
||||
|
||||
@@ -70,9 +126,10 @@ All business endpoints are under `/api/v1/tenants/{tenant}`:
|
||||
asset_id can also come from the exact payload. Every target requires a nonempty
|
||||
exact payload and payload hash; preview coverage must equal the fixed target set,
|
||||
duplicate asset IDs and contradictory payload asset IDs are rejected.
|
||||
`job_id`/`attempt_id` are **not prerequisites** for planning, submission or approval:
|
||||
if present they are optional fixed plan references, not proof of executable jobs
|
||||
or persisted attempts. Actual jobs/attempts are created only after approval.
|
||||
Script plans require the reserved `job_id`/`attempt_id` from the exact stored
|
||||
payload, as well as matching script/job hashes. These are fixed definitions,
|
||||
not proof of executable jobs or persisted attempts. Actual execution rows are
|
||||
created only after approval.
|
||||
Exact payload metadata and script/package hashes must be included. UI does not
|
||||
recompute the plan hash from JSON. Missing fixed targets/previews/payload/hash or
|
||||
excluded targets block submission and approval. All fields are shown, not just
|
||||
|
||||
+20
-2
@@ -60,6 +60,18 @@ 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;
|
||||
export const fullMaintenanceScriptProfile = 'full_maintenance_v1' as const;
|
||||
export function privilegedScriptProfile(value: RecordValue, identity: unknown): 'bounded' | typeof fullMaintenanceScriptProfile {
|
||||
if (!Object.hasOwn(value, 'privileged_script_profile')) return 'bounded';
|
||||
if (value.privileged_script_profile !== fullMaintenanceScriptProfile || !['root', 'system'].includes(String(identity))) throw new Error('Vollwartungsprofil ausschließlich full_maintenance_v1 mit root/system; kein null oder geerbtes Privileg');
|
||||
return fullMaintenanceScriptProfile;
|
||||
}
|
||||
export function validateScriptIdentityProfile(value: RecordValue, identity: unknown, interpreter: unknown): void {
|
||||
const profile = privilegedScriptProfile(value, identity);
|
||||
if (interpreter === 'powershell') {
|
||||
if (identity !== 'agent_service' && !(identity === 'system' && profile === fullMaintenanceScriptProfile)) throw new Error('PowerShell nur agent_service oder ausdrücklich SYSTEM/full_maintenance_v1');
|
||||
} else if (!['posix_sh', 'bash'].includes(String(interpreter)) || !['agent_service', 'root'].includes(String(identity))) throw new Error('Linux-Skript benötigt agent_service/root und festen Shellinterpreter');
|
||||
}
|
||||
/** 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';
|
||||
@@ -157,6 +169,7 @@ export function expectedStdout(value: string, format: string): string | null {
|
||||
return output;
|
||||
}
|
||||
export function validateInput(input: PlanInput): void {
|
||||
if (Object.hasOwn(input.parameters, 'privileged_script_profile') && input.action !== 'run_script') throw new Error('Vollwartungsprofil ausschließlich für run_script');
|
||||
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');
|
||||
@@ -164,21 +177,26 @@ export function validateInput(input: PlanInput): void {
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || end <= Date.now()) throw new Error('Ungültige oder abgelaufene Frist');
|
||||
for (const n of [input.rollout.max_parallel, input.rollout.halt_after_failures, input.parameters.timeout_seconds, input.parameters.max_output_bytes]) if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 1) throw new Error('Limits müssen positive Ganzzahlen sein');
|
||||
if (input.action === 'run_script') {
|
||||
const profile = privilegedScriptProfile(input.parameters, input.parameters.execution_identity);
|
||||
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 : '';
|
||||
if (Object.hasOwn(variant, 'privileged_script_profile')) throw new Error('Privilegiertes Skriptprofil muss aktionsweit in parameters stehen');
|
||||
windowsScriptProfile(variant);
|
||||
validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter);
|
||||
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';
|
||||
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
|
||||
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
|
||||
}) || new Set(variants.map(v => record(v).os_family)).size !== variants.length) throw new Error('Je Plattform genau eine passende UTF-8 Variante (max.32KiB); PowerShell5.1: ASCII oder explizites UTF-8-BOM vor Hashbildung');
|
||||
if (variants.some(v => record(v).os_family === 'windows') && input.parameters.execution_identity !== 'agent_service') throw new Error('Windows PowerShell benötigt agent_service; kein SYSTEM-/Root-Fallback');
|
||||
if (profile === fullMaintenanceScriptProfile && (Number(input.parameters.timeout_seconds) > (variants.some(v => record(v).os_family === 'windows') ? 120 : 300) || Number(input.parameters.max_output_bytes) > 65536)) throw new Error('Vollwartung: Linux höchstens300s / Windows höchstens120s und65536Ausgabebytes');
|
||||
}
|
||||
if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
|
||||
if (input.parameters.execution_identity === 'system') {
|
||||
if (input.action === 'ensure_package') validateWindowsMsiInput(input);
|
||||
if (input.action === 'run_script') {
|
||||
if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1');
|
||||
} else if (input.action === 'ensure_package') validateWindowsMsiInput(input);
|
||||
else {
|
||||
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste oder feste MSI-Rezepte; keine SYSTEM-Shell');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { ConsoleOutput, outputBytes, outputText } from './console-output';
|
||||
|
||||
it('renders hostile output as inert text, reports real status and preserves exact raw bytes', () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
|
||||
try {
|
||||
const hostile = '<script>fetch("/approve")</script>\r\n\x1b[2J\u202eapprove', raw = Array.from(new TextEncoder().encode(hostile));
|
||||
const job = { state: 'unknown', attempt_id: 'fixed-attempt', revision: 4, cancel_requested: true, result: { stdout: raw, stderr: [], exit_code: null, error_code: 'TIMEOUT', output_truncated: true, reboot_required: false } };
|
||||
const before = JSON.stringify(job), html = renderToStaticMarkup(<ConsoleOutput job={job}/>);
|
||||
for (const expected of ['unknown', 'fixed-attempt', 'TIMEOUT', 'unknown / nicht gemeldet', 'nur ein Ausschnitt', 'keinen Live-Ausgabestream', 'Abbruch angefordert', 'neuen genehmigten Plan', '<script>', '\\u000d', '\\u001b', '\\u202e', JSON.stringify(raw)]) expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(script|img|iframe|form|input)\b/i);
|
||||
expect(html).not.toContain('onclick='); expect(fetch).not.toHaveBeenCalled(); expect(JSON.stringify(job)).toBe(before);
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('distinguishes no result, empty bytes, invalid encoding, invalid bytes and missing truncation evidence', () => {
|
||||
const pending = renderToStaticMarkup(<ConsoleOutput job={{ state: 'running', result: null }}/>);
|
||||
expect(pending).toContain('Noch kein gespeichertes Ergebnis'); expect(pending).not.toContain('(leere Ausgabe)');
|
||||
const partial = renderToStaticMarkup(<ConsoleOutput job={{ state: 'failed', result: { stdout: [255, 0, 13, 10], stderr: [] } }}/>);
|
||||
expect(partial).toContain('kein gültiges UTF-8'); expect(partial).toContain('Vollständigkeit ist nicht bestätigt'); expect(partial).toContain('(leere Ausgabe)');
|
||||
const bad = renderToStaticMarkup(<ConsoleOutput job={{ state: 'failed', result: { stdout: [256], stderr: 'not bytes', output_truncated: false } }}/>);
|
||||
expect(bad.match(/Keine verlässliche Textansicht/g)).toHaveLength(2);
|
||||
for (const raw of [undefined, 'hello', [1.5], [-1], [256]]) expect(() => outputBytes(raw)).toThrow();
|
||||
const bytes = outputBytes([239, 187, 191, 65, 13, 10]);
|
||||
expect(outputText(bytes).text).toBe('\\ufeffA\\u000d\n'); expect(Array.from(bytes)).toEqual([239, 187, 191, 65, 13, 10]);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { record, RecordValue, stringField } from './api';
|
||||
|
||||
/** The wire format carries bytes, not an encoding declaration. Never guess a
|
||||
* Windows code page or interpret output as HTML, terminal escapes or actions. */
|
||||
export function outputBytes(value: unknown): Uint8Array<ArrayBuffer> {
|
||||
if (!Array.isArray(value) || value.length > 262144 || value.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) throw new Error('Ungültige oder zu große Ausgabebytes');
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
export function outputText(raw: Uint8Array<ArrayBuffer>): { text: string; encoding: string } {
|
||||
let decoded: string, encoding: string;
|
||||
try { decoded = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw); encoding = 'UTF-8 lesbar; Quellencoding nicht separat belegt'; }
|
||||
catch { decoded = new TextDecoder('utf-8', { ignoreBOM: true }).decode(raw); encoding = 'Encoding unbekannt / kein gültiges UTF-8: Ersatzzeichen nur in der Textansicht'; }
|
||||
// Make terminal/control and bidi characters visible. In particular CR cannot
|
||||
// visually overwrite an earlier line; CRLF remains recognizable as such.
|
||||
return { text: decoded.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g,
|
||||
char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`), encoding };
|
||||
}
|
||||
function download(raw: Uint8Array<ArrayBuffer>, name: 'stdout' | 'stderr') {
|
||||
const url = URL.createObjectURL(new Blob([raw], { type: 'application/octet-stream' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url; link.download = `${name}.bin`; link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
function OutputChannel({ value, name }: { value: unknown; name: 'stdout' | 'stderr' }) {
|
||||
try {
|
||||
const raw = outputBytes(value), view = outputText(raw);
|
||||
return <div><h4>{name} · {raw.length} gespeicherte Bytes</h4><p className="muted">{view.encoding}. Steuerzeichen werden sichtbar als \\uXXXX dargestellt; Rohbytes bleiben erhalten.</p>
|
||||
<pre className="console-output" aria-label={`${name} Textansicht`}>{raw.length ? view.text : '(leere Ausgabe)'}</pre>
|
||||
<button type="button" onClick={() => download(raw, name)}>{name} als unveränderte Rohbytes herunterladen</button>
|
||||
<details><summary>{name} Originalbytes (dezimal)</summary><pre>{JSON.stringify(Array.from(raw))}</pre></details>
|
||||
</div>;
|
||||
} catch (error) { return <p role="alert" className="error">{name}: {error instanceof Error ? error.message : 'Ausgabe nicht lesbar'}. Keine verlässliche Textansicht.</p>; }
|
||||
}
|
||||
export function ConsoleOutput({ job }: { job: RecordValue }) {
|
||||
const state = stringField(job, 'state');
|
||||
return <section aria-label="Gespeichertes Konsolenergebnis"><h3>Konsolenergebnis</h3>
|
||||
<p role="status">Zustand: <strong>{state}</strong> · Versuch: {stringField(job, 'attempt_id')} · Revision: {typeof job.revision === 'number' ? job.revision : 'unknown'}</p>
|
||||
<p>Die Ansicht fragt den gespeicherten Zustand alle 4 Sekunden ab. stdout/stderr erscheinen nach Eingang des Ergebnisses; es gibt keinen Live-Ausgabestream.</p>
|
||||
{state === 'unknown' && <p className="warning">Wirkung oder Ergebnis unklar. Keine automatische Wiederholung; ein neuer Versuch benötigt Abgleich und einen neuen genehmigten Plan.</p>}
|
||||
{job.cancel_requested === true && <p className="warning">Abbruch angefordert; dies bestätigt weder Prozessende noch Rollback.</p>}
|
||||
{job.pending_reason != null && <p>Wartegrund: {String(job.pending_reason)}</p>}
|
||||
{job.result == null ? <p>Noch kein gespeichertes Ergebnis. Fehlende Ausgabe ist kein Erfolgsnachweis.</p> : <Result value={job.result}/>}
|
||||
</section>;
|
||||
}
|
||||
function Result({ value }: { value: unknown }) {
|
||||
try {
|
||||
const result = record(value, 'Jobergebnis');
|
||||
return <><p>Exitcode: {typeof result.exit_code === 'number' && Number.isInteger(result.exit_code) ? result.exit_code : 'unknown / nicht gemeldet'} · Fehlercode: {typeof result.error_code === 'string' && result.error_code ? result.error_code : 'nicht gemeldet'}</p>
|
||||
<p className={result.output_truncated === false ? 'muted' : 'warning'}>Ausgabe begrenzt: {typeof result.output_truncated === 'boolean' ? String(result.output_truncated) : 'unknown'}. {result.output_truncated === true ? 'Die gespeicherten Bytes sind nur ein Ausschnitt.' : result.output_truncated !== false ? 'Vollständigkeit ist nicht bestätigt.' : 'Keine Trunkierung gemeldet.'}</p>
|
||||
<p>Neustartbedarf: {typeof result.reboot_required === 'boolean' ? String(result.reboot_required) : 'unknown'}. Ein Exitcode 0 bestätigt Prozessabschluss; fachliche Nachbedingungen stehen im vollständigen Ergebnis.</p>
|
||||
<p>Ausgabe ist nicht vertrauenswürdiger Text vom Zielgerät. Sie erteilt keine Genehmigung und wird nicht als Anweisung ausgeführt.</p>
|
||||
<OutputChannel name="stdout" value={result.stdout}/><OutputChannel name="stderr" value={result.stderr}/></>;
|
||||
} catch { return <p className="error" role="alert">Ergebnisformat unbekannt; vollständige Originaldaten stehen darunter.</p>; }
|
||||
}
|
||||
+32
-12
@@ -1,13 +1,31 @@
|
||||
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, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety';
|
||||
import { Login } from './login';
|
||||
import { ConsoleOutput, outputText } from './console-output';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre>{pretty(value)}</pre></details>; }
|
||||
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre aria-label={label}>{pretty(value)}</pre></details>; }
|
||||
export function ScriptPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = scriptPlanJobs(plan); if (!jobs.length) return null;
|
||||
return <article aria-label="Feste Skriptkonsole vor Genehmigung"><h3>Vollständige feste Skriptaufträge ({jobs.length})</h3><p>Diese Inhalte stammen aus den hashgeprüften gespeicherten Planbytes. Jeder Zielauftrag, Versuch und Skripthash ist fest gebunden.</p>
|
||||
{jobs.map(job => <article key={job.jobId}><h4>Asset {job.assetId}</h4><p>Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId}</p>
|
||||
<p>Interpreter: {job.interpreter} · Identität: <strong>{job.identity}</strong> · Privilegiertes Profil: <strong>{job.privilegedProfile === fullMaintenanceScriptProfile ? fullMaintenanceScriptProfile : 'bestehendes begrenztes Profil'}</strong> · Windowsprozess: {job.interpreter !== 'powershell' ? 'nicht zutreffend' : job.windowsProfile === 'powershell_51_remote_signed' ? 'Windows PowerShell5.1 RemoteSigned, nur Jobprozess' : 'geerbte Windowsrichtlinie / kein Windows-Prozessoverride'}</p>
|
||||
<p>Frühester Start: {job.notBefore} · Startfrist: {job.startBefore} · Laufzeit: {job.runtimeSeconds}s · Ausgabe: höchstens {job.outputBytes} Bytes</p>
|
||||
<p>Skript: {job.scriptBytes} UTF-8-Bytes · SHA256: <code>{job.scriptHash}</code><br/>Jobpayload-SHA256: <code>{job.jobHash}</code></p>
|
||||
{job.privilegedProfile === fullMaintenanceScriptProfile ? <p className="warning">{fullMaintenanceWarning}</p> : job.identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
<p>Vollständiger Skripttext; Steuerzeichen, BOM und CR werden sichtbar als \uXXXX dargestellt. LF bleibt Zeilenumbruch. Kein Kürzen oder Normalisieren der gespeicherten Bytes.</p>
|
||||
<pre aria-label={`Vollständiges Skript für ${job.assetId}`}>{outputText(new TextEncoder().encode(job.script)).text}</pre>
|
||||
<p>Feste Argumente (JSON): <code>{JSON.stringify(job.arguments)}</code></p><p>stdout-Nachbedingung (JSON): <code>{JSON.stringify(job.expectedStdout)}</code>{job.expectedStdout === null && ' · keine zusätzliche fachliche stdout-Prüfung gebunden'}</p>
|
||||
</article>)}
|
||||
</article>;
|
||||
} catch { return <aside role="alert" className="error">Skriptplan ist nicht vollständig aus unveränderten gespeicherten Bytes verifiziert. Keine Genehmigung möglich.</aside>; }
|
||||
}
|
||||
export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
let jobs: RecordValue[];
|
||||
try { jobs = systemPlanJobs(plan).filter(p => record(p.action).action === 'set_service_state'); }
|
||||
@@ -33,7 +51,7 @@ 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>;
|
||||
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 · {job.identity ?? '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 }) {
|
||||
@@ -77,7 +95,7 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
const [identity, setIdentity] = useState('agent_service');
|
||||
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 common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')), ...(action === 'run_script' && f.get('privileged_script_profile') === fullMaintenanceScriptProfile ? { privileged_script_profile: fullMaintenanceScriptProfile } : {}) };
|
||||
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 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; }
|
||||
@@ -87,9 +105,10 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
{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>}
|
||||
<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={!['set_service_state', 'ensure_package'].includes(action) || !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>}
|
||||
<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={!['set_service_state', 'ensure_package', 'run_script'].includes(action) || !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>
|
||||
{action === 'run_script' && <><label>Privilegiertes Skriptprofil<select name="privileged_script_profile" aria-label="Privilegiertes Skriptprofil" key={identity} defaultValue=""><option value="">Bestehendes begrenztes Profil · keine volle Hostwartung</option><option value={fullMaintenanceScriptProfile} disabled={!['root', 'system'].includes(identity) || !allowed(auth, 'scripts:execute')}>full_maintenance_v1 · volle Hostautorität als root/SYSTEM</option></select></label><p className="warning">{fullMaintenanceWarning}</p><p>Die Auswahl erteilt keine Rechte und aktiviert keinen Client. Zentrale und lokale Policy, tatsächliche Zielcapabilities und die spätere Genehmigung werden unabhängig geprüft. SYSTEM erfordert dieses Profil; es gibt keinen automatischen Fallback.</p></>}
|
||||
{identity === 'root' && action !== 'run_script' && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && action !== 'run_script' && <p className="warning">{systemWarning}</p>}
|
||||
{identity === 'system' && action === 'ensure_package' && <p>MSI: provider=msi, package=rmm-windows-msi-fixture, architecture=x64, installation_context=machine, recipe_version=1 und vollständiges windows_msi_manifest aus dem getrennten MSI-Katalog. Genau zwei eigene Rezepte1.0/1.0→1.1;10–120s,1024–65536Bytes. APT-Manifest fehlt/null. Rezept-/Artefakthash und feste Nachbedingungen werden geprüft. Kein zusätzlicher Artefaktvektor.</p>}
|
||||
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
|
||||
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={identity === 'system' && action === 'ensure_package'} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
|
||||
@@ -120,13 +139,14 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
|
||||
}
|
||||
|
||||
function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id: string; auth: Session; onOperation: (id: string) => void }) {
|
||||
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 plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); await verifyScriptPlan(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), ...windowsMsiApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
|
||||
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); await verifyScriptPlan(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
|
||||
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>
|
||||
<ScriptPlanNotice plan={plan.data}/>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<WindowsMsiPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
@@ -160,7 +180,7 @@ function OperationDetail({ tenantId, id, auth, openPlan }: { tenantId: string; i
|
||||
function JobDetail({ tenantId, id, auth }: { tenantId: string; id: string; auth: Session }) {
|
||||
const job = useResource(async signal => record(await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true);
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
|
||||
return <article><h3>Job {id}</h3><ErrorBox error={job.error}/><ErrorBox error={error}/><p>verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <JsonView value={job.data} label="Versuch, Zustand, pending_reason, Output/stdout/stderr, Trunkierung, Nachprüfungen und Ergebnis"/>}
|
||||
return <article><h3>Job {id}</h3><ErrorBox error={job.error}/><ErrorBox error={error}/><p>verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <><ConsoleOutput job={job.data}/><JsonView value={job.data} label="Vollständige Originaldaten: Versuch, Zustand, Ausgabe, Trunkierung, Nachprüfungen und Ergebnis"/></>}
|
||||
<form onSubmit={async e => { e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}><label>Abbruchgrund<input name="reason" required/></label><button disabled={busy}>Abbruch anfordern · nicht zurückrollen</button></form></article>;
|
||||
}
|
||||
function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
|
||||
+18
-6
@@ -1,8 +1,9 @@
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid } from './api';
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } 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.';
|
||||
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst (running/stopped) oder eigenes festes MSI-Rezept. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
|
||||
export const fullMaintenanceWarning = 'VOLLE HOSTWARTUNG · full_maintenance_v1: Das genehmigte Skript läuft als root/SYSTEM mit vollständiger Hostautorität, einschließlich Netzwerk, Dateisystem und Diensten. Es kann auch Agent, PKI und Schutzmechanismen ändern oder einen Neustart auslösen. Keine Sandbox- oder No-Reboot-Zusage. scripts:execute plus root:execute/system:execute, lokaler und zentraler Opt-in, passende Capability, unabhängiger Helper und konkrete WebUI-Genehmigung bleiben erforderlich.';
|
||||
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
|
||||
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
|
||||
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
|
||||
@@ -72,10 +73,13 @@ export function validateAptManifest(value: unknown, acceptance: boolean): Record
|
||||
}
|
||||
export async function verifyAptManifest(value: unknown, acceptance: boolean) { const m = validateAptManifest(value, acceptance); if (await sha256(bytes(m.transaction_bytes)) !== m.transaction_sha256) throw new Error('APT Transaktionshash stimmt nicht überein'); }
|
||||
export async function validateSensitiveInput(input: PlanInput, auth: Session) {
|
||||
if (input.action === 'run_script' && privilegedScriptProfile(input.parameters, input.parameters.execution_identity) === fullMaintenanceScriptProfile && !allowed(auth, 'scripts:execute')) throw new Error('scripts:execute für Vollwartung unbekannt oder nicht erteilt');
|
||||
if (input.parameters.execution_identity === 'root' && !allowed(auth, 'root:execute')) throw new Error('root:execute unbekannt oder nicht erteilt; keine Rechteerhöhung');
|
||||
if (input.parameters.execution_identity === 'system') {
|
||||
if (!allowed(auth, 'system:execute')) throw new Error('system:execute unbekannt oder nicht erteilt; root:execute enthält dieses Recht nicht');
|
||||
if (input.action !== 'set_service_state' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte');
|
||||
if (input.action === 'run_script') {
|
||||
if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM ausschließlich für typisierte Aktionen oder explizit full_maintenance_v1');
|
||||
} else if (input.action !== 'set_service_state' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte');
|
||||
if (input.action === 'set_service_state') validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest') || (input.action === 'ensure_package' && input.parameters.execution_identity === 'system')) {
|
||||
@@ -104,7 +108,7 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
powerShellPlanJobs(plan);
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.systemJobs);
|
||||
}
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed'; readonly identity?: 'system' }
|
||||
// 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 msiJobs: readonly WindowsMsiPlanJob[]; readonly systemJobs: RecordValue[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
@@ -146,13 +150,14 @@ function hasPowerShellProfile(payload: RecordValue): boolean {
|
||||
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 (action.action !== 'run_script' || action.interpreter !== 'powershell') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service oder explizit SYSTEM');
|
||||
validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter);
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : []), ...(Object.hasOwn(action, 'privileged_script_profile') ? ['privileged_script_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) };
|
||||
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action), ...(payload.execution_identity === 'system' ? { identity: 'system' as const } : {}) };
|
||||
});
|
||||
}
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
@@ -352,6 +357,13 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
for (const payload of systemJobs) {
|
||||
const action = record(payload.action);
|
||||
if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above.
|
||||
if (action.action === 'run_script') {
|
||||
validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter);
|
||||
if (privilegedScriptProfile(action, payload.execution_identity) !== fullMaintenanceScriptProfile || action.interpreter !== 'powershell'
|
||||
|| !Number.isInteger(payload.max_runtime_seconds) || Number(payload.max_runtime_seconds) < 1 || Number(payload.max_runtime_seconds) > 120
|
||||
|| !Number.isInteger(payload.max_output_bytes) || Number(payload.max_output_bytes) < 1 || Number(payload.max_output_bytes) > 65536) throw new Error('SYSTEM-Skript benötigt explizites Vollwartungsprofil und feste Budgets');
|
||||
continue;
|
||||
}
|
||||
exact(action, ['action', 'unit', 'state']);
|
||||
if (action.action !== 'set_service_state') throw new Error('SYSTEM-Plan enthält keine typisierte Dienstaktion');
|
||||
validateSystemService(action.unit, action.state, payload.max_runtime_seconds, payload.max_output_bytes);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { fullMaintenanceScriptProfile, PlanInput, record, RecordValue, Session, validateInput } from './api';
|
||||
import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
// The same fixture is produced and checked by rmm-domain's actual Rust codec.
|
||||
const golden = JSON.parse(readFileSync(new URL('../../tests/script_console/codec-golden.json', import.meta.url), 'utf8')) as RecordValue[];
|
||||
function plan(name: string): RecordValue {
|
||||
const fixture = golden.find(value => value.name === name); if (!fixture) throw new Error('Rust golden case missing');
|
||||
const parsed = record(JSON.parse(new TextDecoder().decode(new Uint8Array(fixture.plan_payload_bytes as number[]))));
|
||||
const jobs = (parsed.jobs as RecordValue[]).map(job => ({ ...structuredClone(job), ...Object.fromEntries(['asset_id', 'agent_id', 'job_id', 'attempt_id'].map(key => [key, record(job.payload)[key]])) }));
|
||||
return { plan_id: parsed.plan_id, plan_hash: fixture.plan_hash, plan_payload_bytes: structuredClone(fixture.plan_payload_bytes), payload: parsed, plan_payload: structuredClone(parsed), jobs, resolved_targets: jobs.map(job => ({ asset_id: job.asset_id, agent_id: job.agent_id })), excluded_targets: [], expires_at: record(jobs[0]!.payload).start_before };
|
||||
}
|
||||
function first(value: RecordValue): RecordValue { return record((record(value.plan_payload).jobs as RecordValue[])[0]!.payload); }
|
||||
async function changedBytes(name: string, change: (payload: RecordValue, job: RecordValue) => void): Promise<RecordValue> {
|
||||
const p = plan(name), parsed = structuredClone(record(p.plan_payload)), job = (parsed.jobs as RecordValue[])[0]!;
|
||||
change(record(job.payload), job);
|
||||
const raw = new TextEncoder().encode(JSON.stringify(parsed));
|
||||
// No aliases: still reject invalid exact bytes or their internal hashes.
|
||||
return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) };
|
||||
}
|
||||
|
||||
it('projects legacy/Linux root/Windows SYSTEM from the exact shared Rust golden bytes', async () => {
|
||||
for (const fixture of golden) {
|
||||
const p = plan(String(fixture.name)); expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0);
|
||||
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
|
||||
const view = scriptPlanJobs(p); expect(view).toHaveLength(1);
|
||||
const job = view[0]!, original = first(p), action = record(original.action);
|
||||
expect(job).toMatchObject({ assetId: original.asset_id, agentId: original.agent_id, jobId: original.job_id, attemptId: original.attempt_id, script: action.script_utf8, identity: original.execution_identity, scriptHash: fixture.script_sha256, jobHash: fixture.job_payload_hash });
|
||||
expect(job.privilegedProfile).toBe(fixture.name === 'legacy_linux_agent' ? 'bounded' : fullMaintenanceScriptProfile);
|
||||
expect(scriptApprovalBlockers(p)).toEqual([]);
|
||||
job.script = 'mutated return copy'; expect(scriptPlanJobs(p)[0]!.script).toBe(action.script_utf8);
|
||||
expect(await sha256(new Uint8Array(fixture.job_payload_bytes as number[]))).toBe(fixture.job_payload_hash);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects view, byte and fixed identity/budget/profile tampering before and after display', async () => {
|
||||
for (const alias of ['payload', 'plan_payload', 'jobs', 'resolved_targets']) {
|
||||
const p = plan('linux_root_full'); await verifyScriptPlan(p); p[alias] = [];
|
||||
expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0); await expect(verifyScriptPlan(p)).rejects.toThrow('verändert');
|
||||
}
|
||||
const p = plan('windows_system_full'); (p.plan_payload_bytes as number[])[0] = 0;
|
||||
await expect(verifyScriptPlan(p)).rejects.toThrow('Planhash');
|
||||
for (const [field, value] of [['execution_identity', 'agent_service'], ['max_runtime_seconds', 121], ['max_output_bytes', 65537]] as const) {
|
||||
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { payload[field] = value; }))).rejects.toThrow();
|
||||
}
|
||||
for (const profile of [null, 'unknown', {}]) await expect(verifyScriptPlan(await changedBytes('linux_root_full', payload => { record(payload.action).privileged_script_profile = profile; }))).rejects.toThrow();
|
||||
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { delete record(payload.action).privileged_script_profile; }))).rejects.toThrow('PowerShell');
|
||||
for (const key of ['job_payload_hash', 'script_sha256']) await expect(verifyScriptPlan(await changedBytes('linux_root_full', (_payload, job) => { job[key] = 'a'.repeat(64); }))).rejects.toThrow('hash');
|
||||
});
|
||||
|
||||
it('binds every supplied alias and refuses asynchronous mutation during hashing', async () => {
|
||||
const p = plan('linux_root_full');
|
||||
const copy = structuredClone(p); copy.jobs = [];
|
||||
await expect(verifyScriptPlan(copy)).rejects.toThrow('Zielansicht');
|
||||
const q = plan('linux_root_full'), check = verifyScriptPlan(q);
|
||||
q.plan_payload_bytes = [123, 125]; await expect(check).rejects.toThrow('verändert');
|
||||
const hashSwap = plan('legacy_linux_agent'); await verifyScriptPlan(hashSwap); hashSwap.plan_hash = 'f'.repeat(64);
|
||||
expect(() => scriptPlanJobs(hashSwap)).toThrow('unveränderten');
|
||||
});
|
||||
|
||||
it('shows full fixed script/profile/identities before approval and has no approval or network side effects', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { ScriptPlanNotice } = await import('./main');
|
||||
const p = plan('windows_system_full'); expect(renderToStaticMarkup(<ScriptPlanNotice plan={p}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
|
||||
const html = renderToStaticMarkup(<ScriptPlanNotice plan={p}/>), view = scriptPlanJobs(p)[0]!;
|
||||
for (const value of ['full_maintenance_v1', 'system', 'powershell', 'RemoteSigned', 'SYSTEM stdout', 'SYSTEM stderr', '\\u000d', view.assetId, view.jobId, view.attemptId, view.scriptHash, view.jobHash, '30s', '4096', 'Keine Sandbox- oder No-Reboot-Zusage', 'Agent, PKI']) expect(html).toContain(value);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('requires separate script/root/SYSTEM scopes and an explicit correctly placed profile at planning', async () => {
|
||||
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', privileged_script_profile: fullMaintenanceScriptProfile, variants: [{ os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: 'Write-Output 1\r\n', windows_execution_profile: 'powershell_51_remote_signed' }], arguments: [], expected_stdout: null, timeout_seconds: 120, max_output_bytes: 65536 }, 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: 'unit only, no native execution' };
|
||||
const auth: Session = { principal: { id: 'simulated', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['scripts:execute', 'system:execute'] };
|
||||
validateInput(input); await validateSensitiveInput(input, auth);
|
||||
for (const permissions of [[], ['system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow();
|
||||
for (const profile of [null, 'other', {}]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: profile } })).toThrow();
|
||||
expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: undefined } })).toThrow();
|
||||
for (const parameters of [{ ...input.parameters, timeout_seconds: 121 }, { ...input.parameters, max_output_bytes: 65537 }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, execution_identity: 'root' }]) expect(() => validateInput({ ...input, parameters })).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api';
|
||||
import { bytes, hashPattern, parseStrictJson, sha256 } from './safety';
|
||||
|
||||
export interface ScriptPlanJob {
|
||||
assetId: string; agentId: string; jobId: string; attemptId: string;
|
||||
interpreter: string; identity: string; windowsProfile: string; privilegedProfile: string;
|
||||
script: string; scriptHash: string; jobHash: string; scriptBytes: number;
|
||||
arguments: string[]; expectedStdout: string | null;
|
||||
notBefore: string; startBefore: string; runtimeSeconds: number; outputBytes: number;
|
||||
}
|
||||
interface Verified { snapshot: string; jobs: ScriptPlanJob[] }
|
||||
const verified = new WeakMap<RecordValue, Verified>();
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||
if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
function snapshot(plan: RecordValue): string {
|
||||
return canonical(Object.fromEntries(['plan_hash', 'plan_payload_bytes', 'plan_payload', 'payload', 'jobs', 'payloads', 'resolved_targets', 'plan_id', 'expires_at'].filter(key => key in plan).map(key => [key, plan[key]])));
|
||||
}
|
||||
function exact(value: RecordValue, fields: string[]) {
|
||||
if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.hasOwn(value, key))) throw new Error('Skriptplan: vollständige bekannte Schemafelder erforderlich');
|
||||
}
|
||||
function uuid(value: unknown): string {
|
||||
const id = text(value, 'Feste Skript-ID');
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) || id === '00000000-0000-0000-0000-000000000000') throw new Error('Skriptplan: feste UUID erforderlich');
|
||||
return id;
|
||||
}
|
||||
function integer(value: unknown, min: number, max: number): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) throw new Error('Skriptplan: ungültiges festes Limit / Generation');
|
||||
return value;
|
||||
}
|
||||
function digest(value: unknown): string { const hash = text(value, 'SHA256'); if (!hashPattern.test(hash)) throw new Error('Skriptplan: exakter SHA256 fehlt'); return hash; }
|
||||
function isScript(value: unknown): boolean { return value !== null && typeof value === 'object' && record(value).action === 'run_script'; }
|
||||
function validateViews(plan: RecordValue, parsed: RecordValue, jobs: RecordValue[]): void {
|
||||
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(plan[alias]) !== canonical(parsed)) throw new Error('Skriptplanansicht widerspricht gespeicherten Bytes');
|
||||
if (plan.plan_id !== undefined && plan.plan_id !== parsed.plan_id) throw new Error('Skript-Plan-ID widerspricht gespeicherten Bytes');
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
if (plan[alias] === undefined) continue;
|
||||
const list = plan[alias]; if (!Array.isArray(list) || list.length !== jobs.length) throw new Error('Skript-Zielansicht unvollständig oder erweitert');
|
||||
const seen = new Set<string>();
|
||||
for (const item of list) {
|
||||
const view = typeof item === 'string' ? { asset_id: item } : record(item), payload = view.payload === undefined ? null : record(view.payload);
|
||||
const asset = uuid(view.asset_id ?? payload?.asset_id), fixed = jobs.find(job => record(job.payload).asset_id === asset);
|
||||
if (!fixed || seen.has(asset)) throw new Error('Skript-Zielansicht enthält fremde oder doppelte Ziele'); seen.add(asset);
|
||||
const p = record(fixed.payload);
|
||||
if (payload) {
|
||||
if (Object.keys(view).some(key => !['payload', 'job_payload_hash', 'script_sha256', 'asset_id', 'agent_id', 'job_id', 'attempt_id'].includes(key))
|
||||
|| canonical(payload) !== canonical(p) || view.job_payload_hash !== fixed.job_payload_hash
|
||||
|| (view.script_sha256 !== undefined && view.script_sha256 !== fixed.script_sha256)
|
||||
|| ['agent_id', 'job_id', 'attempt_id'].some(key => view[key] !== undefined && view[key] !== p[key])) throw new Error('Skript-Zielpreview widerspricht gespeicherten Bytes');
|
||||
} else if (alias !== 'resolved_targets' || (typeof item !== 'string' && (Object.keys(view).some(key => !['asset_id', 'agent_id'].includes(key)) || view.agent_id !== p.agent_id))) throw new Error('Vollständiger Skript-Zielpayload fehlt');
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Verify stored bytes, not a draft textarea or separately formatted JSON view.
|
||||
* Reconstruct the Rust JobPayload/Action declaration order for its job hash.
|
||||
* This is an approval display check, never a grant of execution rights. */
|
||||
export async function verifyScriptPlan(plan: RecordValue): Promise<void> {
|
||||
const before = snapshot(plan), old = verified.get(plan);
|
||||
if (old && old.snapshot !== before) throw new Error('Skriptplan wurde nach Anzeige verändert');
|
||||
const raw = bytes(plan.plan_payload_bytes);
|
||||
if (await sha256(raw) !== digest(plan.plan_hash)) throw new Error('Skript-Planhash widerspricht gespeicherten Bytes');
|
||||
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(raw)));
|
||||
if (!Array.isArray(parsed.jobs)) throw new Error('Vollständige feste Jobdefinitionen fehlen');
|
||||
const jobs = parsed.jobs.map(value => record(value));
|
||||
validateViews(plan, parsed, jobs);
|
||||
if (!jobs.some(job => isScript(record(job.payload).action))) {
|
||||
if (snapshot(plan) !== before) throw new Error('Plan wurde während der Prüfung verändert');
|
||||
verified.set(plan, { snapshot: before, jobs: [] }); return;
|
||||
}
|
||||
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', ...(Object.hasOwn(parsed, 'recipe_references') ? ['recipe_references'] : []), ...(Object.hasOwn(parsed, 'artifact_references') ? ['artifact_references'] : [])]);
|
||||
if (parsed.schema_version !== 1 || !jobs.length || jobs.length > 100) throw new Error('Skriptplan: unbekanntes Schema oder Zielbudget');
|
||||
uuid(parsed.plan_id); uuid(parsed.tenant_id); text(parsed.principal, 'Antragsteller'); text(parsed.reason, 'Begründung');
|
||||
integer(parsed.max_parallel, 1, 10); integer(parsed.halt_after_failures, 1, Number.MAX_SAFE_INTEGER);
|
||||
const result: ScriptPlanJob[] = [], assets = new Set<string>(), attempts = new Set<string>();
|
||||
for (const job of jobs) {
|
||||
const p = record(job.payload); if (!isScript(p.action)) continue;
|
||||
exact(job, ['payload', 'job_payload_hash', 'script_sha256']);
|
||||
exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']);
|
||||
const assetId = uuid(p.asset_id), agentId = uuid(p.agent_id), jobId = uuid(p.job_id), attemptId = uuid(p.attempt_id);
|
||||
if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || assets.has(assetId) || attempts.has(`${jobId}/${attemptId}`)) throw new Error('Skriptplan: widersprüchliche feste Ziele / Versuche');
|
||||
assets.add(assetId); attempts.add(`${jobId}/${attemptId}`);
|
||||
integer(p.enrollment_generation, 1, Number.MAX_SAFE_INTEGER); integer(p.assignment_version, 1, Number.MAX_SAFE_INTEGER);
|
||||
const action = record(p.action), hasWindowsProfile = Object.hasOwn(action, 'windows_execution_profile'), hasPrivilegedProfile = Object.hasOwn(action, 'privileged_script_profile');
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(hasWindowsProfile ? ['windows_execution_profile'] : []), ...(hasPrivilegedProfile ? ['privileged_script_profile'] : [])]);
|
||||
const interpreter = text(action.interpreter, 'Interpreter'), identity = text(p.execution_identity, 'Ausführungsidentität'), script = text(action.script_utf8, 'Skriptbytes'), scriptBytes = new TextEncoder().encode(script);
|
||||
validateScriptIdentityProfile(action, identity, interpreter);
|
||||
const privilegedProfile = privilegedScriptProfile(action, identity);
|
||||
if (scriptBytes.length > 32768 || script.includes('\0') || (interpreter === 'powershell' && !/^[\x00-\x7f]*$/.test(script) && !script.startsWith('\ufeff'))) throw new Error('Skriptplan: Interpreter, Identität oder exakte Skriptbytes ungültig');
|
||||
const windowsProfile = windowsScriptProfile(action);
|
||||
if (!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('Skriptplan: feste Argumente / stdout-Nachbedingung fehlen');
|
||||
const notBefore = text(p.not_before, 'Frühester Start'), startBefore = text(p.start_before, 'Startfrist');
|
||||
if (!Number.isFinite(Date.parse(notBefore)) || !Number.isFinite(Date.parse(startBefore)) || Date.parse(notBefore) >= Date.parse(startBefore) || (plan.expires_at !== undefined && plan.expires_at !== startBefore)) throw new Error('Skriptplan: widersprüchliche feste Fristen');
|
||||
const full = privilegedProfile === fullMaintenanceScriptProfile;
|
||||
const runtimeSeconds = integer(p.max_runtime_seconds, 1, full ? interpreter === 'powershell' ? 120 : 300 : 3600), outputBytes = integer(p.max_output_bytes, 1, full ? 65536 : 262144);
|
||||
const orderedAction = { action: 'run_script', interpreter, script_utf8: script, arguments: action.arguments, expected_stdout: action.expected_stdout, ...(hasWindowsProfile ? { windows_execution_profile: action.windows_execution_profile } : {}), ...(hasPrivilegedProfile ? { privileged_script_profile: action.privileged_script_profile } : {}) };
|
||||
const ordered = { schema_version: p.schema_version, tenant_id: p.tenant_id, asset_id: assetId, agent_id: agentId, enrollment_generation: p.enrollment_generation, assignment_version: p.assignment_version, job_id: jobId, attempt_id: attemptId, action: orderedAction, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: runtimeSeconds, max_output_bytes: outputBytes };
|
||||
const scriptHash = digest(job.script_sha256), jobHash = digest(job.job_payload_hash);
|
||||
if (await sha256(scriptBytes) !== scriptHash || await sha256(new TextEncoder().encode(JSON.stringify(ordered))) !== jobHash) throw new Error('Skript-/Jobhash widerspricht exakten Rust-Payloadbytes');
|
||||
result.push({ assetId, agentId, jobId, attemptId, interpreter, identity, windowsProfile, privilegedProfile, script, scriptHash, jobHash, scriptBytes: scriptBytes.length, arguments: [...action.arguments] as string[], expectedStdout: action.expected_stdout as string | null, notBefore, startBefore, runtimeSeconds, outputBytes });
|
||||
}
|
||||
if (snapshot(plan) !== before) throw new Error('Skriptplan wurde während der Hashprüfung verändert');
|
||||
verified.set(plan, { snapshot: before, jobs: result });
|
||||
}
|
||||
export function scriptPlanJobs(plan: RecordValue): ScriptPlanJob[] {
|
||||
const checked = verified.get(plan);
|
||||
if (!checked || checked.snapshot !== snapshot(plan)) throw new Error('Skriptplan nicht aus unveränderten gespeicherten Bytes verifiziert');
|
||||
return structuredClone(checked.jobs);
|
||||
}
|
||||
export function scriptApprovalBlockers(plan: RecordValue): string[] {
|
||||
try { scriptPlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'Skriptplan nicht verifiziert']; }
|
||||
}
|
||||
Reference in New Issue
Block a user