Add fresh device trust, installer recovery and scoped patch runtime

This commit is contained in:
2026-11-17 16:08:53 +01:00
parent 60f8f21f54
commit 81fcd9c8f8
24 changed files with 543 additions and 45 deletions
+18 -4
View File
@@ -1430,6 +1430,13 @@ impl Server {
} }
} }
/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor. /// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor.
pub fn execution_timeout(action: &rmm_domain::jobs::Action, seconds: u32) -> Result<Duration> {
ensure!(
(1..=action.windows_system_runtime_limit(120, Some(rmm_domain::jobs::WINDOWS_UPDATE_MAX_SECONDS))).contains(&seconds),
"SYSTEM_EXECUTION_TIMEOUT_BOUND"
);
Ok(Duration::from_secs(u64::from(seconds) + 5))
}
pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> { pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
exchange_fixed(pin, call, timeout, false) exchange_fixed(pin, call, timeout, false)
} }
@@ -1443,10 +1450,17 @@ fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) ->
); );
pin.validate()?; pin.validate()?;
require_self(&pin.agent).context(Stage::ClientSelfRole)?; require_self(&pin.agent).context(Stage::ClientSelfRole)?;
ensure!( if timeout > Duration::from_secs(125) {
(Duration::from_secs(1)..=Duration::from_secs(125)).contains(&timeout), let Operation::Execute { request, .. } = &call.operation else {
"HELPER_CALL_TIMEOUT_BOUND" anyhow::bail!("HELPER_CALL_TIMEOUT_BOUND");
); };
let job = pin.binding.job(&request.job_bytes)?;
ensure!(job.execution_identity == "system" && job.action.is_windows_update_template()
&& execution_timeout(&job.action, job.max_runtime_seconds)? == timeout,
"HELPER_CALL_TIMEOUT_BOUND");
} else {
ensure!(timeout >= Duration::from_secs(1), "HELPER_CALL_TIMEOUT_BOUND");
}
let deadline = Instant::now() + timeout; let deadline = Instant::now() + timeout;
let pipe = owned(unsafe { let pipe = owned(unsafe {
CreateFileW( CreateFileW(
+10 -13
View File
@@ -563,7 +563,7 @@ impl Client {
let timeout = if matches!(job.action, Action::UpdateAgent { .. }) { let timeout = if matches!(job.action, Action::UpdateAgent { .. }) {
Duration::from_secs(60) Duration::from_secs(60)
} else { } else {
execution_timeout(job.max_runtime_seconds)? ipc::execution_timeout(&job.action, job.max_runtime_seconds)?
}; };
let permit = self let permit = self
.lane .lane
@@ -898,13 +898,6 @@ fn system_shape(job: &JobPayload) -> bool {
&& (1..=65536).contains(&job.max_output_bytes) && (1..=65536).contains(&job.max_output_bytes)
&& matches!(&job.action,Action::SetServiceState{unit,state} if unit.starts_with("RmmDiscoveryFixture")&&unit.len()>"RmmDiscoveryFixture".len()&&unit.len()<=80&&unit.bytes().all(|b|b.is_ascii_alphanumeric()||b"_-".contains(&b))&&matches!(state.as_str(),"running"|"stopped")) && matches!(&job.action,Action::SetServiceState{unit,state} if unit.starts_with("RmmDiscoveryFixture")&&unit.len()>"RmmDiscoveryFixture".len()&&unit.len()<=80&&unit.bytes().all(|b|b.is_ascii_alphanumeric()||b"_-".contains(&b))&&matches!(state.as_str(),"running"|"stopped"))
} }
fn execution_timeout(seconds: u32) -> Result<Duration> {
ensure!(
(1..=120).contains(&seconds),
"SYSTEM_EXECUTION_TIMEOUT_BOUND"
);
Ok(Duration::from_secs(u64::from(seconds) + 5))
}
pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()> { pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()> {
if let Action::UpdateAgent { update } = &job.action { if let Action::UpdateAgent { update } = &job.action {
ensure!( ensure!(
@@ -1023,11 +1016,15 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
} }
return Ok(()); return Ok(());
} }
let windows_update = job.action.is_windows_update_template();
let reboot_report = if windows_update && !outcome.output_truncated && matches!(outcome.state.as_str(), "succeeded" | "failed") {
rmm_domain::jobs::windows_update_reboot_report(&outcome.stdout)
} else { None };
ensure!( ensure!(
matches!( matches!(
outcome.state.as_str(), outcome.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired" | "unknown" "succeeded" | "failed" | "cancelled" | "expired" | "unknown"
) && (job.action.windows_msi().is_some() || !outcome.reboot_required) ) && (job.action.windows_msi().is_some() || outcome.reboot_required == reboot_report.unwrap_or(false))
&& outcome && outcome
.stdout .stdout
.len() .len()
@@ -1092,7 +1089,7 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
system_shape(job) system_shape(job)
&& outcome.exit_code == Some(0) && outcome.exit_code == Some(0)
&& !outcome.output_truncated && !outcome.output_truncated
&& !outcome.reboot_required && (!windows_update || (reboot_report.is_some() && e["windows_update_reboot_required"] == serde_json::json!(reboot_report)))
&& e["postconditions_passed"] == true && e["postconditions_passed"] == true
&& e["privileged_script_profile"] == "full_maintenance_v1" && e["privileged_script_profile"] == "full_maintenance_v1"
&& e["execution_sid"] == "S-1-5-18" && e["execution_sid"] == "S-1-5-18"
@@ -1417,9 +1414,9 @@ mod tests {
state: "stopped".into(), state: "stopped".into(),
}; };
assert!(!system_shape(&job)); assert!(!system_shape(&job));
assert_eq!(execution_timeout(120).unwrap(), Duration::from_secs(125)); assert_eq!(ipc::execution_timeout(&job.action, 120).unwrap(), Duration::from_secs(125));
assert!(execution_timeout(0).is_err()); assert!(ipc::execution_timeout(&job.action, 0).is_err());
assert!(execution_timeout(121).is_err()); assert!(ipc::execution_timeout(&job.action, 121).is_err());
let mut outcome = Outcome::unknown("LOST_REPLY"); let mut outcome = Outcome::unknown("LOST_REPLY");
assert!(checked_outcome(&job, &outcome).is_ok()); assert!(checked_outcome(&job, &outcome).is_ok());
outcome.reboot_required = true; outcome.reboot_required = true;
+19 -2
View File
@@ -83,6 +83,8 @@ pub struct Settings {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles" deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)] )]
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>, pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub windows_update_max_runtime_seconds: Option<u32>,
} }
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>( fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
d: D, d: D,
@@ -113,7 +115,7 @@ impl Settings {
&& job && job
.action .action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& job.max_runtime_seconds <= self.max_runtime_seconds && job.max_runtime_seconds <= job.action.windows_system_runtime_limit(self.max_runtime_seconds, self.windows_update_max_runtime_seconds)
&& self.allowed_script_profiles.as_deref() && self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]) == Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
} }
@@ -144,6 +146,7 @@ impl Settings {
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1] |v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
) )
&& (self.schema_version == 4 || !self.allow_reboot) && (self.schema_version == 4 || !self.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds, self.allowed_script_profiles.as_deref())
&& (1..=120).contains(&self.max_runtime_seconds) && (1..=120).contains(&self.max_runtime_seconds)
&& self.allowed_services.len() <= 16, && self.allowed_services.len() <= 16,
"SYSTEM_POLICY_PROFILE" "SYSTEM_POLICY_PROFILE"
@@ -1167,8 +1170,8 @@ impl SystemHelper {
&& ((job.max_runtime_seconds <= self.settings.max_runtime_seconds && ((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)) && (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)
|| self.settings.permits_reboot(&job))) || self.settings.permits_reboot(&job)))
|| self.settings.permits_script(&job)
|| crate::update_admission::permits_denial( || crate::update_admission::permits_denial(
&self.settings.binding, &self.settings.binding,
&job &job
@@ -1974,6 +1977,7 @@ mod tests {
allow_reboot: false, allow_reboot: false,
allowed_msi_recipe_sha256: None, allowed_msi_recipe_sha256: None,
allowed_script_profiles: None, allowed_script_profiles: None,
windows_update_max_runtime_seconds: None,
}; };
let legacy = serde_json::to_value(&settings).unwrap(); let legacy = serde_json::to_value(&settings).unwrap();
assert!(legacy.get("allowed_msi_recipe_sha256").is_none()); assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
@@ -2013,6 +2017,19 @@ mod tests {
assert!(!settings.permits_script(&script)); assert!(!settings.permits_script(&script));
settings.schema_version = 3; settings.schema_version = 3;
assert!(settings.permits_script(&script)); assert!(settings.permits_script(&script));
let generic_script = script.action.clone();
script.max_runtime_seconds = 3600;
settings.windows_update_max_runtime_seconds = Some(3600);
assert!(!settings.permits_script(&script));
if let Action::RunScript { script_utf8, windows_execution_profile, .. } = &mut script.action {
*script_utf8 = rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into();
*windows_execution_profile = Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
}
assert!(settings.permits_script(&script));
settings.windows_update_max_runtime_seconds = None;
assert!(!settings.permits_script(&script));
script.action = generic_script;
script.max_runtime_seconds = 30;
script.execution_identity = "root".into(); script.execution_identity = "root".into();
assert!(!settings.permits_script(&script)); assert!(!settings.permits_script(&script));
let mut null = legacy; let mut null = legacy;
@@ -89,6 +89,9 @@ pub fn qualified(
&& crate::actions::powershell().is_ok(), && crate::actions::powershell().is_ok(),
"system script qualification policy" "system script qualification policy"
); );
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned());
}
caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string)); caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string));
} }
"set_service_state" => { "set_service_state" => {
@@ -60,6 +60,8 @@ struct Settings {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles" deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)] )]
allowed_script_profiles: Option<Vec<PrivilegedScriptProfile>>, allowed_script_profiles: Option<Vec<PrivilegedScriptProfile>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
windows_update_max_runtime_seconds: Option<u32>,
} }
fn strict_hashes<'de, D: serde::Deserializer<'de>>( fn strict_hashes<'de, D: serde::Deserializer<'de>>(
d: D, d: D,
@@ -213,6 +215,7 @@ pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
ensure!( ensure!(
matches!(settings.schema_version, 1..=4) matches!(settings.schema_version, 1..=4)
&& (settings.schema_version == 4 || !settings.allow_reboot) && (settings.schema_version == 4 || !settings.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(settings.windows_update_max_runtime_seconds, settings.allowed_script_profiles.as_deref())
&& (1..=120).contains(&settings.max_runtime_seconds) && (1..=120).contains(&settings.max_runtime_seconds)
&& settings.allowed_services.len() <= 16 && settings.allowed_services.len() <= 16
&& (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none()) && (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none())
+68 -1
View File
@@ -54,6 +54,36 @@ pub enum PrivilegedScriptProfile {
#[serde(rename = "full_maintenance_v1")] #[serde(rename = "full_maintenance_v1")]
FullMaintenanceV1, FullMaintenanceV1,
} }
/// Bytes of the Windows Update Agent PowerShell template seeded by migration 0023.
pub const WINDOWS_UPDATE_SCRIPT_UTF8: &str = include_str!("windows_update.ps1");
pub const WINDOWS_UPDATE_SCRIPT_SHA256: &str =
"0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf";
pub const WINDOWS_UPDATE_MAX_SECONDS: u32 = 3600;
pub const WINDOWS_UPDATE_LONG_CAPABILITY: &str = "script.windows_update.long/1";
pub fn valid_windows_update_limit(
limit: Option<u32>,
profiles: Option<&[PrivilegedScriptProfile]>,
) -> bool {
limit.is_none_or(|seconds| {
(121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds)
&& profiles == Some(&[PrivilegedScriptProfile::FullMaintenanceV1][..])
})
}
/// Only the built-in template's final ASCII JSON object describes the host's
/// restart state. Earlier lines can include per-update results and native titles.
pub fn windows_update_reboot_report(stdout: &[u8]) -> Option<bool> {
let summary = stdout
.rsplit(|byte| *byte == b'\n')
.map(<[u8]>::trim_ascii)
.find(|line| !line.is_empty())?;
let json: serde_json::Value = serde_json::from_slice(summary).ok()?;
let obj = json.as_object()?;
let reboot = obj.get("reboot_required")?.as_bool()?;
(obj.len() == 2
&& (obj.get("found").is_some_and(|v| v.is_u64())
|| (reboot && obj.get("status").and_then(|v| v.as_str()) == Some("restart_pending"))))
.then_some(reboot)
}
pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1"; pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1";
pub fn deserialize_privileged_script_profile<'de, D>( pub fn deserialize_privileged_script_profile<'de, D>(
d: D, d: D,
@@ -387,6 +417,20 @@ impl Action {
} }
) )
} }
pub fn is_windows_update_template(&self) -> bool {
matches!(self, Self::RunScript {
interpreter, script_utf8, arguments, expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
} if interpreter == "powershell" && arguments.is_empty() && script_utf8 == WINDOWS_UPDATE_SCRIPT_UTF8)
}
pub fn windows_system_runtime_limit(&self, normal: u32, windows_update: Option<u32>) -> u32 {
if self.is_windows_update_template() {
windows_update.unwrap_or(normal)
} else {
normal
}
}
pub fn valid_execution_identity(&self, identity: &str) -> bool { pub fn valid_execution_identity(&self, identity: &str) -> bool {
if let Self::UpdateAgent { update } = self { if let Self::UpdateAgent { update } = self {
return update.execution_identity() == Some(identity); return update.execution_identity() == Some(identity);
@@ -410,7 +454,7 @@ impl Action {
|| (output_bytes <= 65536 || (output_bytes <= 65536
&& runtime_seconds && runtime_seconds
<= if self.script_platform() == Some("windows") { <= if self.script_platform() == Some("windows") {
120 self.windows_system_runtime_limit(120, Some(WINDOWS_UPDATE_MAX_SECONDS))
} else { } else {
300 300
})) }))
@@ -779,6 +823,29 @@ impl JobState {
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn windows_update_final_report_and_policy_are_exact() {
assert_eq!(
windows_update_reboot_report(
b"ignored \xff\r\n{\"found\":1,\"reboot_required\":true}\r\n"
),
Some(true)
);
assert_eq!(
windows_update_reboot_report(br#"{"reboot_required":false,"found":0}"#),
Some(false)
);
assert_eq!(
windows_update_reboot_report(br#"{"reboot_required":true,"status":"restart_pending"}"#),
Some(true)
);
assert_eq!(
windows_update_reboot_report(br#"{"id":"an update","reboot_required":true}"#),
None
);
assert_eq!(windows_update_reboot_report(b"partial"), None);
assert!(!valid_windows_update_limit(Some(3600), None));
}
#[test]
fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() { fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() {
let caps: Vec<String> = [ let caps: Vec<String> = [
"windows.base/1", "windows.base/1",
+47
View File
@@ -0,0 +1,47 @@
# Install available software updates from the configured Windows Update source.
# See https://learn.microsoft.com/windows/win32/wua_sdk/windows-update-agent-object-model
$ErrorActionPreference = 'Stop'
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'Rust Discovery'
$searcher = $session.CreateUpdateSearcher()
$search = $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'")
if ($search.ResultCode -ne 2) { throw "Update search returned $($search.ResultCode)" }
$failed = $false
$systemInfo = New-Object -ComObject Microsoft.Update.SystemInfo
if ($systemInfo.RebootRequired) {
Write-Output '{"reboot_required":true,"status":"restart_pending"}'
exit 1
}
foreach ($update in $search.Updates) {
$result = [ordered]@{ id = $update.Identity.UpdateID; title = $update.Title; status = 'pending' }
try {
if ($update.InstallationBehavior.CanRequestUserInput -or !$update.EulaAccepted) {
$result.status = 'operator_input_required'
$failed = $true
} else {
$batch = New-Object -ComObject Microsoft.Update.UpdateColl
[void]$batch.Add($update)
if (!$update.IsDownloaded) {
$downloader = $session.CreateUpdateDownloader()
$downloader.Updates = $batch
$download = $downloader.Download().GetUpdateResult(0)
if ($download.ResultCode -ne 2) { throw "Download HRESULT $($download.HResult)" }
}
$installer = $session.CreateUpdateInstaller()
$installer.AllowSourcePrompts = $false
$installer.Updates = $batch
$install = $installer.Install().GetUpdateResult(0)
$result.status = [int]$install.ResultCode
$result.hresult = $install.HResult
$result.reboot_required = [bool]$install.RebootRequired
if ($install.ResultCode -ne 2) { $failed = $true }
}
} catch {
$result.status = 'failed'
$result.error = $_.Exception.Message
$failed = $true
}
Write-Output ($result | ConvertTo-Json -Compress)
}
Write-Output (@{ found = $search.Updates.Count; reboot_required = [bool]$systemInfo.RebootRequired } | ConvertTo-Json -Compress)
if ($failed) { exit 1 }
+1
View File
@@ -308,6 +308,7 @@ RMM_BOOTSTRAP_PYTHON
.route("/agent/v1/bootstrap/updater", get(bootstrap::updater)) .route("/agent/v1/bootstrap/updater", get(bootstrap::updater))
.route("/agent/v1/releases/current", get(current)) .route("/agent/v1/releases/current", get(current))
.route("/agent/v1/releases/installed", get(installed)) .route("/agent/v1/releases/installed", get(installed))
.route("/agent/v1/releases/device-trust", get(bootstrap::device_trust))
.route( .route(
"/agent/v1/releases/{release}/artifacts/{artifact}", "/agent/v1/releases/{release}/artifacts/{artifact}",
get(release_artifact), get(release_artifact),
+27 -6
View File
@@ -176,14 +176,16 @@ def installed():
def healthy(version, baseline, duration=90): def healthy(version, baseline, duration=90):
until = time.monotonic() + duration until = time.monotonic() + duration
started = time.time()
while time.monotonic() < until: while time.monotonic() < until:
try: try:
record = installed() record = installed()
contact = record.get('last_contact_at') contact = record.get('last_contact_at')
if contact: if contact:
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp() recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
if (time.time() - 65 < recent <= time.time() + 10 and record['agent_version'] == version if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline): and record['connection_generation'] > baseline
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
return True return True
except (subprocess.SubprocessError, ValueError, OSError): except (subprocess.SubprocessError, ValueError, OSError):
pass pass
@@ -249,6 +251,18 @@ def enable():
service('enable', '--now', SERVICE, TIMER) service('enable', '--now', SERVICE, TIMER)
def enrollment_token(path):
token = Path(path).read_text().strip() if path else getpass.getpass('Einmalcode: ').strip()
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
return token
def save_token(base, token, gid):
path = base / 'first.token'
save(path, token.encode(), 0o440)
os.chown(path, 0, gid)
def install(base, token_file): def install(base, token_file):
require(platform.machine() == 'x86_64', 'Linux x86-64 required') require(platform.machine() == 'x86_64', 'Linux x86-64 required')
base = origin(base) base = origin(base)
@@ -256,12 +270,20 @@ def install(base, token_file):
config = read(ROOT / 'config.json') config = read(ROOT / 'config.json')
require(config['bootstrap'] == base and (ROOT / 'current/manifest.json').is_file(), require(config['bootstrap'] == base and (ROOT / 'current/manifest.json').is_file(),
'existing installation differs') 'existing installation differs')
if not (STATE / 'identity.json').is_file():
token = enrollment_token(token_file)
with tempfile.TemporaryDirectory() as work:
metadata = Path(work) / 'bootstrap.json'
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, metadata)
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
enable() enable()
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
(ROOT / 'first.token').unlink(missing_ok=True)
return return
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()), require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
'existing device installation requires migration') 'existing device installation requires migration')
token = Path(token_file).read_text().strip() if token_file else getpass.getpass('Einmalcode: ').strip() token = enrollment_token(token_file)
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
try: try:
account = pwd.getpwnam('rmm-discovery') account = pwd.getpwnam('rmm-discovery')
except KeyError: except KeyError:
@@ -290,8 +312,7 @@ def install(base, token_file):
link(staging, manifest['release_id']) link(staging, manifest['release_id'])
save(staging / 'lifecycle.py', Path(__file__).read_bytes()) save(staging / 'lifecycle.py', Path(__file__).read_bytes())
save(staging / 'release.lock', b'') save(staging / 'release.lock', b'')
save(staging / 'first.token', token.encode(), 0o440) save_token(staging, token, account.pw_gid)
os.chown(staging / 'first.token', 0, account.pw_gid)
staging.chmod(0o755) staging.chmod(0o755)
releases.chmod(0o755) releases.chmod(0o755)
os.rename(staging, ROOT) os.rename(staging, ROOT)
+33 -1
View File
@@ -106,6 +106,37 @@ async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
.await?; .await?;
t.ok_or_else(denied) t.ok_or_else(denied)
} }
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct TimeTrust {
key_generation: u64,
server_instance: Uuid,
public_keys_hex: std::collections::BTreeMap<String, String>,
}
fn device_trust_data(s: &crate::State) -> Result<Value, Error> {
let job_public = hex::encode(s.job_signer.public_key()?);
let path = std::env::var_os("RMM_AGENT_BOOTSTRAP_WINDOWS_FILE")
.and_then(|slot| FsPath::new(&slot).parent().map(|p| p.join("windows-time-trust.json")));
let trust = match path {
Some(path) if path.try_exists().map_err(|_| fail("BOOTSTRAP_TIME_TRUST_INVALID"))? => {
let trust: TimeTrust = serde_json::from_slice(&protected_file(&path, 8192)?)?;
if trust.key_generation == 0 || trust.server_instance.is_nil()
|| !(1..=8).contains(&trust.public_keys_hex.len())
|| !trust.public_keys_hex.iter().all(|(id,key)| !id.is_empty() && id.len() <= 64
&& id.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
&& rmm_domain::agent_update::digest(key) && key != &job_public) {
return Err(fail("BOOTSTRAP_TIME_TRUST_INVALID"));
}
Some(trust)
}
_ => None
};
Ok(json!({"job_signing_public_key_hex":job_public,"windows_time_trust":trust}))
}
pub(super) async fn device_trust(State(s): State<crate::State>, Extension(peer): Extension<crate::Peer>, headers: HeaderMap) -> Result<Response, Error> {
device(&s, peer, &headers).await?;
Ok(private_json(device_trust_data(&s)?))
}
pub(super) async fn current( pub(super) async fn current(
State(s): State<crate::State>, State(s): State<crate::State>,
headers: HeaderMap, headers: HeaderMap,
@@ -126,8 +157,9 @@ pub(super) async fn current(
.ca .ca
.to_pem() .to_pem()
.map_err(|_| invalid())?; .map_err(|_| invalid())?;
let trust = device_trust_data(&s)?;
Ok(private_json( Ok(private_json(
json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest, json!({"job_signing_public_key_hex":trust["job_signing_public_key_hex"],"windows_time_trust":trust["windows_time_trust"],"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
"gateway_origin":c.gateway_origin,"ca_pem":String::from_utf8(ca).map_err(|_| invalid())?, "gateway_origin":c.gateway_origin,"ca_pem":String::from_utf8(ca).map_err(|_| invalid())?,
"keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}}), "keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}}),
)) ))
+2
View File
@@ -723,6 +723,7 @@ pub(crate) async fn plan_resolved(
artifact_references, artifact_references,
script_revision, script_revision,
}; };
crate::script_library::validate_plan_bindings(&payload)?;
crate::windows_msi_catalog::validate_plan_bindings(&payload)?; crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
crate::agent_updates::validate_plan_bindings(&payload)?; crate::agent_updates::validate_plan_bindings(&payload)?;
let bytes = encode(&payload)?; let bytes = encode(&payload)?;
@@ -759,6 +760,7 @@ async fn load_plan(
Ok((serde_json::from_slice(&bytes)?, h, bytes)) Ok((serde_json::from_slice(&bytes)?, h, bytes))
} }
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> { async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
crate::script_library::validate_plan_bindings(plan)?;
crate::windows_msi_catalog::validate_plan_bindings(plan)?; crate::windows_msi_catalog::validate_plan_bindings(plan)?;
crate::agent_updates::validate_plan_bindings(plan)?; crate::agent_updates::validate_plan_bindings(plan)?;
policy(tx).await?; policy(tx).await?;
+42 -1
View File
@@ -186,6 +186,27 @@ pub async fn plan(
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
} }
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
let Some(reference) = &plan.script_revision else {
if plan.jobs.iter().any(|job| {
job.payload.max_runtime_seconds > 120 && job.payload.action.is_windows_update_template()
}) {
return Err(Error(
StatusCode::CONFLICT,
"WINDOWS_UPDATE_REVISION_REQUIRED",
));
}
return Ok(());
};
if reference.revision_id.is_nil() || reference.version < 1 || reference.name.is_empty() || plan.jobs.is_empty()
|| plan.jobs.iter().any(|job| !matches!(&job.payload.action,
Action::RunScript { script_utf8, .. } if hash(script_utf8.as_bytes()) == reference.script_sha256
&& job.script_sha256.as_ref() == Some(&reference.script_sha256))) {
return Err(Error(StatusCode::CONFLICT, "SCRIPT_REVISION_BINDING_MISMATCH"));
}
Ok(())
}
pub fn routes(r: Router<crate::State>) -> Router<crate::State> { pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
r.route( r.route(
"/api/v1/tenants/{tenant}/script-revisions", "/api/v1/tenants/{tenant}/script-revisions",
@@ -247,7 +268,13 @@ pub(crate) mod tests {
template["script_utf8"].as_str().unwrap().into(), template["script_utf8"].as_str().unwrap().into(),
) )
.unwrap(); .unwrap();
assert!(native.full_maintenance()); assert!(native.is_windows_update_template());
assert_eq!(
template["script_sha256"],
rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256
);
assert!(native.valid_job_limits(3600, 65536));
assert!(!native.valid_job_limits(3601, 65536));
let v1 = Publish { let v1 = Publish {
name: "Agentversion".into(), name: "Agentversion".into(),
@@ -335,6 +362,20 @@ pub(crate) mod tests {
.unwrap(); .unwrap();
tx.commit().await.unwrap(); tx.commit().await.unwrap();
let bound: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&bytes).unwrap(); let bound: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&bytes).unwrap();
let mut extended = bound.clone();
extended.jobs[0].payload.action = native;
extended.jobs[0].payload.max_runtime_seconds = 3600;
extended.jobs[0].script_sha256 =
Some(rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256.into());
assert_eq!(
validate_plan_bindings(&extended).unwrap_err().1,
"SCRIPT_REVISION_BINDING_MISMATCH"
);
extended.script_revision = None;
assert_eq!(
validate_plan_bindings(&extended).unwrap_err().1,
"WINDOWS_UPDATE_REVISION_REQUIRED"
);
let reference = bound.script_revision.unwrap(); let reference = bound.script_revision.unwrap();
assert_eq!(reference.revision_id, id); assert_eq!(reference.revision_id, id);
assert_eq!(reference.version, 1); assert_eq!(reference.version, 1);
+39 -1
View File
@@ -45,6 +45,8 @@ struct SystemScope {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles" deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)] )]
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>, allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
#[serde(default)]
windows_update_max_runtime_seconds: Option<u32>,
#[serde(default, deserialize_with = "strict_optional_reboot")] #[serde(default, deserialize_with = "strict_optional_reboot")]
allow_reboot: Option<bool>, allow_reboot: Option<bool>,
} }
@@ -122,6 +124,10 @@ impl SystemScope {
.allowed_script_profiles .allowed_script_profiles
.as_deref() .as_deref()
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]) .is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
&& rmm_domain::jobs::valid_windows_update_limit(
self.windows_update_max_runtime_seconds,
self.allowed_script_profiles.as_deref(),
)
&& (1..=120).contains(&self.max_runtime_seconds) && (1..=120).contains(&self.max_runtime_seconds)
} }
fn permits( fn permits(
@@ -154,7 +160,13 @@ impl SystemScope {
"helper.binary.sha256:{}", "helper.binary.sha256:{}",
self.helper_binary_sha256 self.helper_binary_sha256
)) ))
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds) && (1..=job.action.windows_system_runtime_limit(
self.max_runtime_seconds,
self.windows_update_max_runtime_seconds,
))
.contains(&job.max_runtime_seconds)
&& (job.max_runtime_seconds <= 120
|| has(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY))
&& (1..=65536).contains(&job.max_output_bytes) && (1..=65536).contains(&job.max_output_bytes)
&& match &job.action { && match &job.action {
Action::Reboot { .. } => { Action::Reboot { .. } => {
@@ -556,6 +568,32 @@ mod tests {
policy.schema_version = 3; policy.schema_version = 3;
assert!(policy.permits("selected", &job, &caps, Utc::now())); assert!(policy.permits("selected", &job, &caps, Utc::now()));
assert!(!policy.permits("foreign", &job, &caps, Utc::now())); assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
let general = job.action.clone();
job.action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
),
privileged_script_profile: Some(
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
),
};
caps.push("script.powershell.process_remote_signed/1".into());
job.max_runtime_seconds = 3600;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
assert!(policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(1800);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
job.action = general;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
job.max_runtime_seconds = 30;
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY); caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
assert!(!policy.permits("selected", &job, &caps, Utc::now())); assert!(!policy.permits("selected", &job, &caps, Utc::now()));
} }
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Renew the development server's public installer certificate before expiry."""
from pathlib import Path
import os
import subprocess
import tempfile
def main():
state = Path('/opt/rmm-bootstrap-download')
cert = state / 'chain.pem'
host = 'discovery.ease-technologies.de'
def run(*args, **kwargs):
return subprocess.run(args, check=True, timeout=180, **kwargs)
if subprocess.run(['openssl', 'x509', '-in', cert, '-noout', '-checkend', str(30*86400)],
stdout=subprocess.DEVNULL).returncode == 0:
print('Public installer certificate valid beyond renewal window')
return
rules = run('ufw','show','added', capture_output=True, text=True).stdout.splitlines()
rule = ['allow','80/tcp']
already_open = any(line.split()[:3] == ['ufw',*rule] for line in rules)
run('systemctl','start','rmm-bootstrap-acme.service')
try:
if not already_open:
run('ufw',*rule)
try:
with tempfile.NamedTemporaryFile(dir=state, delete=False) as output:
candidate = Path(output.name)
try:
run('/usr/bin/python3','-I',state/'acme_tiny.py','--account-key',state/'account.key',
'--csr',state/'domain.csr','--acme-dir','/srv/rmm-bootstrap-acme',stdout=output)
output.flush()
run('openssl','verify','-verify_hostname',host,'-CAfile','/etc/ssl/certs/ca-certificates.crt',
'-untrusted',candidate,candidate)
cert_key = run('openssl','x509','-in',candidate,'-noout','-pubkey',capture_output=True).stdout
local_key = run('openssl','pkey','-in',state/'domain.key','-pubout',capture_output=True).stdout
if cert_key != local_key:
raise ValueError('Certificate does not match bootstrap key')
os.fsync(output.fileno())
os.replace(candidate,cert)
finally:
candidate.unlink(missing_ok=True)
finally:
if not already_open:
run('ufw','delete',*rule)
finally:
run('systemctl','stop','rmm-bootstrap-acme.service')
run('systemctl','restart','rmm-install-ingress.service')
if __name__ == '__main__':
main()
@@ -0,0 +1,8 @@
[Unit]
Description=Renew public Rust Discovery installer TLS certificate
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 -I /usr/local/libexec/rmm-renew-bootstrap-tls.py
UMask=0077
TimeoutStartSec=5min
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Check public installer TLS certificate daily
[Timer]
OnCalendar=daily
RandomizedDelaySec=2h
Persistent=true
[Install]
WantedBy=timers.target
+69
View File
@@ -0,0 +1,69 @@
"""Retry coverage for the HTTPS Linux bootstrap without installing on the test host."""
from contextlib import ExitStack
from importlib.util import module_from_spec, spec_from_file_location
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
src = Path(__file__).resolve().parents[1] / 'crates/server/src/bootstrap/lifecycle.py'
spec = spec_from_file_location('rmm_bootstrap_lifecycle', src)
lifecycle = module_from_spec(spec)
spec.loader.exec_module(lifecycle)
class EnrollmentRetry(unittest.TestCase):
def setUp(self):
self.stack = ExitStack()
self.addCleanup(self.stack.close)
folder = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
self.base = 'https://bootstrap.example'
self.tenant = '11111111-1111-4111-8111-111111111111'
root = folder / 'application'
(root / 'current').mkdir(parents=True)
(root / 'config.json').write_text(json.dumps({'bootstrap': self.base, 'tenant': self.tenant}))
(root / 'current/manifest.json').write_text('{"version":"1.0"}')
self.state = folder / 'device'
self.state.mkdir()
for field, value in [('ROOT',root),('STATE',self.state)]:
self.stack.enter_context(patch.object(lifecycle,field,value))
self.enable = self.stack.enter_context(patch.object(lifecycle,'enable'))
self.healthy = self.stack.enter_context(patch.object(lifecycle,'healthy',return_value=True))
self.save = self.stack.enter_context(patch.object(lifecycle,'save_token'))
self.stack.enter_context(patch.object(lifecycle.pwd,'getpwnam'))
self.token = folder / 'retry.token'
self.token.write_text('0' * 64)
def bootstrap_tenant(self, tenant):
def answer(source, route, target):
self.assertEqual(source, (self.base,'0' * 64))
target.write_text(json.dumps({'tenant_id': tenant}))
return self.stack.enter_context(patch.object(lifecycle,'remote',side_effect=answer))
def test_completed_enrollment_keeps_identity_and_needs_no_token(self):
identity = self.state / 'identity.json'
identity.write_text('{"agent_id":"original"}')
remote = self.bootstrap_tenant(self.tenant)
lifecycle.install(self.base,None)
self.assertEqual(identity.read_text(), '{"agent_id":"original"}')
remote.assert_not_called()
self.save.assert_not_called()
self.enable.assert_called_once()
def test_expired_initial_token_can_be_replaced_in_same_tenant(self):
self.bootstrap_tenant(self.tenant)
lifecycle.install(self.base,self.token)
self.save.assert_called_once()
self.healthy.assert_called_once_with('1.0',0)
def test_token_for_another_tenant_cannot_replace_initial_token(self):
self.bootstrap_tenant('22222222-2222-4222-8222-222222222222')
with self.assertRaisesRegex(ValueError,'different enrollment tenant'):
lifecycle.install(self.base,self.token)
self.save.assert_not_called()
self.enable.assert_not_called()
if __name__ == '__main__':
unittest.main()
+19 -5
View File
@@ -2,7 +2,6 @@
"""Prepare an Ed25519 agent release on the signing host and publish through the catalog API.""" """Prepare an Ed25519 agent release on the signing host and publish through the catalog API."""
import argparse import argparse
import base64 import base64
import datetime
import getpass import getpass
import hashlib import hashlib
import http.client import http.client
@@ -11,7 +10,6 @@ import json
import os import os
from pathlib import Path from pathlib import Path
import re import re
import shutil
import ssl import ssl
import subprocess import subprocess
import tempfile import tempfile
@@ -132,11 +130,19 @@ def prepare(args):
save_once(config / (label + '-keyring.json'), encoded(ring), args.service_uid) save_once(config / (label + '-keyring.json'), encoded(ring), args.service_uid)
boot = {'gateway_origin': args.gateway.rstrip('/'), 'updater_sha256': blobs[2]['sha256'], 'updater_bytes': blobs[2]['bytes']} boot = {'gateway_origin': args.gateway.rstrip('/'), 'updater_sha256': blobs[2]['sha256'], 'updater_bytes': blobs[2]['bytes']}
boot_path = config / (label + '-bootstrap.json') boot_path = config / (label + '-bootstrap.json')
# The stable bootstrap worker is provisioned separately from replaceable code. # Keep the original verified worker available for publication into additional
# tenants, even if a newer build also generated a different worker.
stable = args.state / 'bootstrap-workers' / label
provision_folder(stable.parent)
if not boot_path.exists(): if not boot_path.exists():
save_once(boot_path, encoded(boot), args.service_uid) save_once(boot_path, encoded(boot), args.service_uid)
existing = json.loads(boot_path.read_bytes()) existing = json.loads(boot_path.read_bytes())
check(existing['gateway_origin'] == boot['gateway_origin'], 'existing gateway origin differs') check(existing['gateway_origin'] == boot['gateway_origin'], 'existing gateway origin differs')
if not stable.exists() and boot == existing:
save_once(stable, (args.artifacts / FILES[platform][2]).read_bytes())
if stable.exists():
check(fingerprint(stable) == (existing['updater_sha256'], existing['updater_bytes']),
'stored bootstrap worker differs from protected configuration')
prepared = args.state / 'prepared' / label / str(args.sequence) prepared = args.state / 'prepared' / label / str(args.sequence)
provision_folder(prepared.parent) provision_folder(prepared.parent)
if prepared.exists(): if prepared.exists():
@@ -212,9 +218,16 @@ def publish(args):
tenant = str(uuid.UUID(args.tenant)) tenant = str(uuid.UUID(args.tenant))
check(session['tenant_id'] == tenant and 'catalog:write' in session['permissions'], 'tenant catalog write permission required') check(session['tenant_id'] == tenant and 'catalog:write' in session['permissions'], 'tenant catalog write permission required')
path = '/api/v1/tenants/' + tenant path = '/api/v1/tenants/' + tenant
for name, blob in zip(FILES[platform], blobs): paths = [args.artifacts / name for name in FILES[platform]]
if args.bootstrap_worker:
paths[2] = args.bootstrap_worker
sha, size = fingerprint(paths[2])
name = FILES[platform][2]
blobs[2] = {'artifact_id': str(uuid.uuid5(uuid.NAMESPACE_OID, platform + '/' + name + '/' + sha)),
'sha256': sha, 'bytes': size}
for file, blob in zip(paths, blobs):
query = urlencode(dict(artifact_id=blob['artifact_id'], sha256=blob['sha256'], size_bytes=blob['bytes'])) query = urlencode(dict(artifact_id=blob['artifact_id'], sha256=blob['sha256'], size_bytes=blob['bytes']))
with (args.artifacts / name).open('rb') as data: with file.open('rb') as data:
result = client.request('POST', path + '/agent-update-artifacts?' + query, data, result = client.request('POST', path + '/agent-update-artifacts?' + query, data,
{'Content-Type': 'application/octet-stream', 'Content-Length': str(blob['bytes'])}) {'Content-Type': 'application/octet-stream', 'Content-Length': str(blob['bytes'])})
check(result['sha256'] == blob['sha256'] and result['size_bytes'] == blob['bytes'], 'artifact receipt differs') check(result['sha256'] == blob['sha256'] and result['size_bytes'] == blob['bytes'], 'artifact receipt differs')
@@ -243,6 +256,7 @@ def main():
cmd.add_argument('--service-uid', type=int, default=os.getuid()) cmd.add_argument('--service-uid', type=int, default=os.getuid())
else: else:
cmd.add_argument('--origin', required=True) cmd.add_argument('--origin', required=True)
cmd.add_argument('--bootstrap-worker', type=Path, help='Pinned initial stable updater when publishing subsequent code pairs')
cmd.add_argument('--ca', type=Path) cmd.add_argument('--ca', type=Path)
cmd.add_argument('--tenant', required=True) cmd.add_argument('--tenant', required=True)
cmd.add_argument('--envelope', type=Path, required=True) cmd.add_argument('--envelope', type=Path, required=True)
+28 -1
View File
@@ -50,6 +50,33 @@ def on_server(options):
inputs = ['--artifacts', str(build), '--build-receipt', str(build / options['receipt'])] inputs = ['--artifacts', str(build), '--build-receipt', str(build / options['receipt'])]
subprocess.run(['python3', '-I', str(tool), 'prepare', *inputs, '--state', str(state), '--gateway', options['gateway'], subprocess.run(['python3', '-I', str(tool), 'prepare', *inputs, '--state', str(state), '--gateway', options['gateway'],
'--service-uid','10001','--sequence',str(options['sequence']),'--version',options['version']],check=True) '--service-uid','10001','--sequence',str(options['sequence']),'--version',options['version']],check=True)
if options['label'].startswith('windows'):
import re
import uuid
public = Path('/etc/rmm-time-source/time-public-key.json')
if public.exists():
contents = json.loads(public.read_bytes())
if (set(contents) != {'schema_version','algorithm','server_instance','key_id','key_generation','public_key_hex'}
or contents['algorithm'] != 'Ed25519' or contents['schema_version'] != 1 or uuid.UUID(contents['server_instance']).int == 0
or not re.fullmatch('[A-Za-z0-9_-]{1,64}', contents['key_id']) or not re.fullmatch('[0-9a-f]{64}', contents['public_key_hex'])
or type(contents['key_generation']) is not int or contents['key_generation'] <= 0):
raise ValueError('time broker public key information invalid')
expected = {'server_instance':contents['server_instance'],'key_generation':contents['key_generation'],
'public_keys_hex':{contents['key_id']:contents['public_key_hex']}}
path = state/'config/windows-time-trust.json'
if not path.exists():
with tempfile.NamedTemporaryFile(mode='w', dir=path.parent,delete=False) as tmp:
json.dump(expected,tmp,separators=(',',':'))
os.fchmod(tmp.fileno(),0o600)
os.fchown(tmp.fileno(),10001,10001)
tmp.flush()
os.fsync(tmp.fileno())
try:
os.link(tmp.name,path)
finally:
os.unlink(tmp.name)
if json.loads(path.read_bytes()) != expected:
raise ValueError('time trust changed; verify rotation before new publication')
if options['prepare_only']: if options['prepare_only']:
return return
# Use the ordinary development catalog permission and CSRF-protected API. # Use the ordinary development catalog permission and CSRF-protected API.
@@ -67,7 +94,7 @@ def on_server(options):
subprocess.run(['python3','-I',str(tool),'publish',*inputs,'--tenant',options['tenant'], subprocess.run(['python3','-I',str(tool),'publish',*inputs,'--tenant',options['tenant'],
'--envelope',str(state/'prepared'/options['label']/str(options['sequence'])/'envelope.json'), '--envelope',str(state/'prepared'/options['label']/str(options['sequence'])/'envelope.json'),
'--origin','https://localhost:18443','--ca','/opt/rust-discovery/devstate/api-pki/ca.pem', '--origin','https://localhost:18443','--ca','/opt/rust-discovery/devstate/api-pki/ca.pem',
'--dev-login-file',auth.name],check=True) '--dev-login-file',auth.name,'--bootstrap-worker',str(state/'bootstrap-workers'/options['label'])],check=True)
def main(): def main():
import inspect import inspect
+12 -5
View File
@@ -95,10 +95,11 @@ def activate(payload):
run('docker','build','--network=none','--pull=false','-t',tag,str(context)) run('docker','build','--network=none','--pull=false','-t',tag,str(context))
overlay=role_dir/'image.compose.yaml' overlay=role_dir/'image.compose.yaml'
write_atomic(overlay,('services:\n'+''.join(f' {r}:\n image: {tag}\n pull_policy: never\n' for r in ('migrate','api','gateway'))).encode()) write_atomic(overlay,('services:\n'+''.join(f' {r}:\n image: {tag}\n pull_policy: never\n' for r in ('migrate','api','gateway'))).encode())
for path in payload['overlays']: for path, content in payload['overlays'].items():
file = (root / 'deploy') / path file = (root / 'deploy') / path
if not re.fullmatch(r'[\w.-]+\.compose\.yaml',path) or not file.is_file(): if not re.fullmatch(r'server\.[\w.-]+\.compose\.yaml', path) or file.is_symlink():
raise ValueError('Dev compose overlay must exist in the deployment directory') raise ValueError('Invalid development overlay name')
write_atomic(file, base64.b64decode(content, validate=True))
if file not in base_files: if file not in base_files:
compose.extend(['-f',str(file)]) compose.extend(['-f',str(file)])
compose.extend(['-f',str(overlay)]) compose.extend(['-f',str(overlay)])
@@ -150,7 +151,7 @@ def main():
import shlex import shlex
parser=argparse.ArgumentParser(description=__doc__) parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ref',required=True) parser.add_argument('--ref',required=True)
parser.add_argument('--overlay',action='append',default=[],help='Additional existing compose file in remote deploy/') parser.add_argument('--overlay',action='append',default=[],help='Deploy and use this compose overlay from the selected Git revision')
args=parser.parse_args() args=parser.parse_args()
revision=subprocess.check_output(['git','rev-parse','--verify','--end-of-options',args.ref+'^{commit}'],text=True).strip() revision=subprocess.check_output(['git','rev-parse','--verify','--end-of-options',args.ref+'^{commit}'],text=True).strip()
web=web_files(revision) web=web_files(revision)
@@ -158,7 +159,13 @@ def main():
names=subprocess.check_output(['git','ls-tree','--name-only','-r',revision,'migrations'],text=True).splitlines() names=subprocess.check_output(['git','ls-tree','--name-only','-r',revision,'migrations'],text=True).splitlines()
migrations={str(int(Path(n).name.split('_',1)[0])):hashlib.sha384(subprocess.check_output(['git','show',revision+':'+n])).hexdigest() migrations={str(int(Path(n).name.split('_',1)[0])):hashlib.sha384(subprocess.check_output(['git','show',revision+':'+n])).hexdigest()
for n in names if n.endswith('.sql')} for n in names if n.endswith('.sql')}
payload=json.dumps(dict(revision=revision,web=web,overlays=args.overlay,migrations=migrations)) overlays = {}
for name in args.overlay:
if not re.fullmatch(r'server\.[\w.-]+\.compose\.yaml', name):
parser.error('Expected a server overlay filename from deploy/')
raw = subprocess.check_output(['git', 'show', revision + ':deploy/' + name])
overlays[name] = base64.b64encode(raw).decode()
payload=json.dumps(dict(revision=revision,web=web,overlays=overlays,migrations=migrations))
cmd=source+'\nactivate(json.loads('+repr(payload)+'))\n' cmd=source+'\nactivate(json.loads('+repr(payload)+'))\n'
subprocess.run(ssh_prefix('server')+[shlex.join(['python3','-I','-'])],input=cmd,text=True,check=True) subprocess.run(ssh_prefix('server')+[shlex.join(['python3','-I','-'])],input=cmd,text=True,check=True)
+3 -1
View File
@@ -45,9 +45,11 @@ export function ConsoleOutput({ job }: { job: RecordValue }) {
function Result({ value }: { value: unknown }) { function Result({ value }: { value: unknown }) {
try { try {
const result = record(value, 'Jobergebnis'); const result = record(value, 'Jobergebnis');
const evidence = result.evidence && typeof result.evidence === 'object' ? record(result.evidence) : {};
const reboot = Object.hasOwn(evidence, 'windows_update_reboot_required') ? evidence.windows_update_reboot_required : result.reboot_required;
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> 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 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>Neustartbedarf: {typeof reboot === 'boolean' ? String(reboot) : '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> <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}/></>; <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>; } } catch { return <p className="error" role="alert">Ergebnisformat unbekannt; vollständige Originaldaten stehen darunter.</p>; }
+20
View File
@@ -51,6 +51,26 @@ it('shows the immutable library revision and rejects a different catalog script
await expect(verifyScriptPlan(await stored('f'.repeat(64)))).rejects.toThrow('Bibliotheksversion'); await expect(verifyScriptPlan(await stored('f'.repeat(64)))).rejects.toThrow('Bibliotheksversion');
}); });
it('accepts one hour only for the exact Windows Update revision', async () => {
const source = readFileSync(new URL('../../crates/domain/src/windows_update.ps1', import.meta.url), 'utf8');
async function windowPlan(script: string, fixed: boolean, seconds: number) {
const original = plan('windows_system_full');
const parsed = record(JSON.parse(new TextDecoder().decode(new Uint8Array(original.plan_payload_bytes as number[]))));
const job = (parsed.jobs as RecordValue[])[0]!, payload = record(job.payload), action = record(payload.action);
action.script_utf8 = script; action.arguments = []; action.expected_stdout = null; payload.max_runtime_seconds = seconds;
job.script_sha256 = await sha256(new TextEncoder().encode(script));
job.job_payload_hash = await sha256(new TextEncoder().encode(JSON.stringify(payload)));
if (fixed) parsed.script_revision = { revision_id: parsed.plan_id, name: 'Windows-Updates installieren', version: 1, script_sha256: job.script_sha256 };
const raw = new TextEncoder().encode(JSON.stringify(parsed));
return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) };
}
const valid = await windowPlan(source, true, 3600);
await verifyScriptPlan(valid); expect(scriptPlanJobs(valid)[0]?.runtimeSeconds).toBe(3600);
for (const bad of [await windowPlan(source+'\n',true,3600), await windowPlan(source,false,3600), await windowPlan(source,true,3601)]) {
await expect(verifyScriptPlan(bad)).rejects.toThrow();
}
});
it('rejects view, byte and fixed identity/budget/profile tampering before and after display', async () => { 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']) { for (const alias of ['payload', 'plan_payload', 'jobs', 'resolved_targets']) {
const p = plan('linux_root_full'); await verifyScriptPlan(p); p[alias] = []; const p = plan('linux_root_full'); await verifyScriptPlan(p); p[alias] = [];
+4 -1
View File
@@ -1,6 +1,7 @@
import { canonicalJson, record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api'; import { canonicalJson, record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api';
import { bytes, hashPattern, parseStrictJson, sha256 } from './safety'; import { bytes, hashPattern, parseStrictJson, sha256 } from './safety';
export const windowsUpdateScriptHash = '0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf';
export interface ScriptPlanJob { export interface ScriptPlanJob {
revision?: { id: string; name: string; version: number }; revision?: { id: string; name: string; version: number };
assetId: string; agentId: string; jobId: string; attemptId: string; assetId: string; agentId: string; jobId: string; attemptId: string;
@@ -99,7 +100,9 @@ export async function verifyScriptPlan(plan: RecordValue): Promise<void> {
const notBefore = text(p.not_before, 'Frühester Start'), startBefore = text(p.start_before, 'Startfrist'); 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'); 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 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 windowsUpdate = revisionHash === windowsUpdateScriptHash && interpreter === 'powershell' && identity === 'system'
&& full && windowsProfile === 'powershell_51_remote_signed' && !action.arguments.length && action.expected_stdout === null;
const runtimeSeconds = integer(p.max_runtime_seconds, 1, windowsUpdate ? 3600 : 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 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 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); const scriptHash = digest(job.script_sha256), jobHash = digest(job.job_payload_hash);
+5 -2
View File
@@ -1,6 +1,7 @@
import React, { FormEvent, useEffect, useState } from 'react'; import React, { FormEvent, useEffect, useState } from 'react';
import { objectId, page, record, request, Session, tenantPath, text } from './api'; import { objectId, page, record, request, Session, tenantPath, text } from './api';
import { allowed } from './safety'; import { allowed } from './safety';
import { windowsUpdateScriptHash } from './script-console';
interface Draft { interface Draft {
name: string; name: string;
@@ -79,7 +80,8 @@ export function ScriptLibrary({ tenantId, auth, selected, showPlan }: { tenantId
}); });
} }
if (!canRead) return null; if (!canRead) return null;
const limit = stored?.execution_identity === 'system' ? 120 : stored?.execution_identity === 'root' ? 300 : 3600; const windowsUpdate = stored?.execution_identity === 'system' && stored.interpreter === 'powershell' && stored.script_sha256 === windowsUpdateScriptHash;
const limit = windowsUpdate ? 3600 : stored?.execution_identity === 'system' ? 120 : stored?.execution_identity === 'root' ? 300 : 3600;
return <section aria-label="Skriptbibliothek"><h2>Skriptbibliothek</h2> return <section aria-label="Skriptbibliothek"><h2>Skriptbibliothek</h2>
{error && <p role="alert" className="error">{error}</p>}{notice && <p role="status">{notice}</p>} {error && <p role="alert" className="error">{error}</p>}{notice && <p role="status">{notice}</p>}
{items.length > 0 && <label>Gespeicherte Skriptversion<select value={chosen} disabled={busy || !!draft} onChange={e => setChosen(e.target.value)}> {items.length > 0 && <label>Gespeicherte Skriptversion<select value={chosen} disabled={busy || !!draft} onChange={e => setChosen(e.target.value)}>
@@ -101,9 +103,10 @@ export function ScriptLibrary({ tenantId, auth, selected, showPlan }: { tenantId
</fieldset></form>} </fieldset></form>}
{canPlan && stored && !draft && <form key={stored.revision_id} onSubmit={plan}><fieldset disabled={busy}><legend>Auftrag für {stored.name} · v{stored.version} vorbereiten</legend> {canPlan && stored && !draft && <form key={stored.revision_id} onSubmit={plan}><fieldset disabled={busy}><legend>Auftrag für {stored.name} · v{stored.version} vorbereiten</legend>
<p>{selected.length} ausgewählte Geräte · Ein Gerät gleichzeitig · Stopp beim ersten Fehler · 65536 Byte Ausgabe je Gerät</p> <p>{selected.length} ausgewählte Geräte · Ein Gerät gleichzeitig · Stopp beim ersten Fehler · 65536 Byte Ausgabe je Gerät</p>
{windowsUpdate && <p>Diese Version installiert verfügbare Softwareupdates ohne eigenen Neustart. Sie meldet Neustartbedarf. Laufzeiten über 120 Sekunden erfordern die passende Windows-Update-Freigabe in Server- und Helperpolicy.</p>}
<label>Begründung<input name="reason" required maxLength={1024}/></label> <label>Begründung<input name="reason" required maxLength={1024}/></label>
<label>Startfrist in Minuten<input name="minutes" type="number" min={1} max={1440} defaultValue={60} required/></label> <label>Startfrist in Minuten<input name="minutes" type="number" min={1} max={1440} defaultValue={60} required/></label>
<label>Laufzeit je Gerät in Sekunden<input name="runtime" type="number" min={1} max={limit} defaultValue={Math.min(limit,120)} required/></label> <label>Laufzeit je Gerät in Sekunden<input name="runtime" type="number" min={1} max={limit} defaultValue={windowsUpdate ? 3600 : Math.min(limit,120)} required/></label>
<button disabled={!selected.length}>Plan vorbereiten</button> <button disabled={!selected.length}>Plan vorbereiten</button>
</fieldset></form>} </fieldset></form>}
</section>; </section>;