Integrate the currently deployed server functionality with the reviewed WebUI

This commit is contained in:
2026-11-18 09:05:06 +01:00
17 changed files with 261 additions and 83 deletions
@@ -8,6 +8,10 @@ fn main() -> anyhow::Result<()> {
println!("enrolled-windows-update/1");
return Ok(());
}
if std::env::args().skip(1).eq(["--managed-script-helper-version"]) {
println!("managed-script-helper/1");
return Ok(());
}
rmm_agent_windows::helper_system::dispatch()
}
#[cfg(not(windows))]
@@ -11,6 +11,10 @@ fn main() -> anyhow::Result<()> {
println!("release-job-lock/1");
Ok(())
}
Some(flag) if flag == "--managed-script-helper-version" && args.next().is_none() => {
println!("managed-script-helper/1");
Ok(())
}
Some(flag) if flag == "--verify-bootstrap" => {
let release = rmm_updater::verify_bootstrap_files(
rmm_agent_windows::release_platform::VERIFY,
+11 -3
View File
@@ -107,10 +107,13 @@ impl Settings {
})
}
pub(crate) fn windows_update_only(&self) -> bool {
self.schema_version >= 3 && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
(3..=4).contains(&self.schema_version) && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
&& self.allowed_script_profiles.is_none() && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30
}
pub(crate) fn managed_scripts(&self) -> bool {
self.schema_version == 5
}
fn permits_script(&self, job: &JobPayload) -> bool {
self.schema_version >= 3
&& job.execution_identity == "system"
@@ -133,7 +136,12 @@ impl Settings {
}
pub fn validate(&self) -> Result<()> {
ensure!(
matches!(self.schema_version, 1..=4)
matches!(self.schema_version, 1..=5)
&& (!self.managed_scripts()
|| (self.enable_effects && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot
&& self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])))
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
&& self
@@ -891,7 +899,7 @@ impl SystemHelper {
let pin = settings.pin()?;
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
let clock = if settings.windows_update_only() {
let clock = if settings.windows_update_only() || settings.managed_scripts() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
let boot = WindowsBoot::capture()?;
+11 -6
View File
@@ -319,10 +319,16 @@ fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
// Only typed release UUIDs enter the fixed SCM command. The actual service path,
// LocalService account and absence of an independently provisioned helper are checked again on the target.
fn select(from: Uuid, to: Uuid) -> Result<()> {
fn select(from: &Installed, to: &Installed) -> Result<()> {
let manifest = local_manifest(to)?;
let [agent, helper] = manifest.artifacts.as_slice() else {
anyhow::bail!("incomplete installed release pair");
};
let script = include_str!("release_service_switch.ps1")
.replace("FROM_UUID", &from.to_string())
.replace("TO_UUID", &to.to_string());
.replace("FROM_UUID", &from.release_id.to_string())
.replace("TO_UUID", &to.release_id.to_string())
.replace("SELECTED_AGENT_SHA256", &agent.sha256)
.replace("SELECTED_HELPER_SHA256", &helper.sha256);
let windows = std::env::var_os("SystemRoot").context("Windows directory")?;
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let result = Command::new(ps)
@@ -338,8 +344,7 @@ fn select(from: Uuid, to: Uuid) -> Result<()> {
Ok(())
}
async fn rollback(t: &Transition) -> Result<()> {
local_manifest(&t.old)?;
select(t.new.release_id, t.old.release_id)?;
select(&t.new, &t.old)?;
write_record("rejected-release.json", &t.new)?;
fs::remove_file(record_path(INTENT))?;
Ok(())
@@ -494,7 +499,7 @@ async fn cycle() -> Result<()> {
let t = Transition { old: active, new };
write_record(INTENT, &t)?;
let start = chrono::Utc::now();
let selected = select(t.old.release_id, t.new.release_id);
let selected = select(&t.old, &t.new);
if selected.is_ok() {
for _ in 0..18 {
if let Ok(h) = device.health().await
@@ -4,6 +4,31 @@ function Get-Image([string]$Id) {
$image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe')
return '"' + $image + '" --service --config "' + $configPath + '"'
}
function Get-HelperImage([string]$Id) {
Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-helper-windows.exe')
}
function Wait-Stopped([string]$Name) {
$control = Get-Service $Name
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
}
}
function Select-Image($Service, [string]$Image) {
if ($Service.PathName -cne $Image) {
$result = Invoke-CimMethod -InputObject $Service -MethodName Change -Arguments @{PathName=$Image}
if ($result.ReturnValue -ne 0) { throw 'SCM path change failed.' }
}
}
function Replace-Pin([string]$Path, [string]$Value) {
$temp = "$Path.next-$([Guid]::NewGuid())"
try {
[IO.File]::WriteAllText($temp, $Value, [Text.UTF8Encoding]::new($false))
[IO.File]::Replace($temp, $Path, $null)
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
$configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json'
$from = Get-Image 'FROM_UUID'
$to = Get-Image 'TO_UUID'
@@ -13,16 +38,36 @@ if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) {
if (-not $config.PSObject.Properties['localservice_time_policy'] -or
$config.localservice_time_policy -cne (Join-Path (Split-Path $configPath) 'job-time.json')) { throw 'Job-enabled pair requires a coordinated helper handoff.' }
}
$managed = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$helper = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cnotin @($from,$to) -or (Get-Service 'RmmDiscoverySystemHelper' -ErrorAction SilentlyContinue)) { throw 'Unexpected service configuration.' }
if ($service.PathName -cne $to) {
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
}
$res = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{PathName=$to}
if ($res.ReturnValue -ne 0) { throw 'SCM path change failed.' }
$service.PathName -cnotin @($from,$to) -or ([bool]$helper -ne [bool]$managed)) { throw 'Unexpected service configuration.' }
if ($managed) {
$helperExe = Get-HelperImage 'TO_UUID'
$helperTo = '"' + $helperExe + '" --service'
$helperFrom = '"' + (Get-HelperImage 'FROM_UUID') + '" --service'
if ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cnotin @($helperFrom,$helperTo)) { throw 'Unexpected managed helper service.' }
$policyRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$settingsPath = Join-Path $policyRoot 'helper.json'
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
if ($settings.schema_version -ne 5) { throw 'Managed helper settings required.' }
$rendered = ([ordered]@{binding=$settings.binding; release_id='TO_UUID'
agent_sha256='SELECTED_AGENT_SHA256'; helper_sha256='SELECTED_HELPER_SHA256'
max_runtime_seconds=$settings.windows_update_max_runtime_seconds; managed_scripts=$true} | ConvertTo-Json -Depth 6 -Compress) |
& $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Signed successor helper could not render its pins.' }
$pins = $rendered | ConvertFrom-Json
Wait-Stopped 'RmmDiscoveryWindows'
Wait-Stopped 'RmmDiscoverySystemHelper'
Replace-Pin $settingsPath $pins.helper_settings
Replace-Pin (Join-Path $policyRoot 'agent-pin.json') $pins.agent_pin
Select-Image $helper $helperTo
Select-Image $service $to
Start-Service 'RmmDiscoverySystemHelper'
(Get-Service 'RmmDiscoverySystemHelper').WaitForStatus('Running', [TimeSpan]::FromSeconds(45))
} elseif ($service.PathName -cne $to) {
Wait-Stopped 'RmmDiscoveryWindows'
Select-Image $service $to
}
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Running') {
+9 -3
View File
@@ -40,6 +40,8 @@ struct Config {
localservice_time_policy: Option<PathBuf>,
#[serde(default)]
windows_update_helper: bool,
#[serde(default)]
managed_script_helper: bool,
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
#[serde(default)]
enable_jobs: bool,
@@ -99,7 +101,8 @@ impl Config {
fn read(path: &Path) -> Result<Self> {
let raw = protected_read(path, 32768)?;
let config: Self = serde_json::from_slice(&raw)?;
if config.windows_update_helper {
ensure!(!(config.windows_update_helper && config.managed_script_helper), "AMBIGUOUS_ENROLLED_HELPER");
if config.windows_update_helper || config.managed_script_helper {
ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED");
}
if let Some(policy) = &config.localservice_time_policy {
@@ -817,7 +820,8 @@ impl Agent {
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let helper = if self.config.localservice_time_policy.is_some() && !self.config.windows_update_helper {
let helper = if self.config.localservice_time_policy.is_some()
&& !self.config.windows_update_helper && !self.config.managed_script_helper {
None
} else { rmm_agent_windows::helper_runtime::Client::discover(
&self.identity.agent_id,
@@ -1406,7 +1410,9 @@ impl Agent {
}
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service"
&& !(self.config.windows_update_helper && job.execution_identity == "system" && job.action.windows_update_or_identity_probe()) {
&& !(job.execution_identity == "system"
&& (self.config.windows_update_helper && job.action.windows_update_or_identity_probe()
|| self.config.managed_script_helper && job.action.full_maintenance())) {
return false;
}
if self.config.windows_echo_probe_only
@@ -42,12 +42,21 @@ pub fn qualified(
pin.validate()?;
let (settings, _handles) = helper_system::read_settings()?;
ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin");
if settings.windows_update_only() {
// The caller has verified an independent helper-role clock and the live
// peer. Only the two built-in scripts pass both local and server gates.
return Ok(vec!["helper.system.v1".into(), format!("helper.binary.sha256:{}",pin.helper.binary_sha256),
format!("helper.policy.sha256:{}",pin.policy_sha256), "system:run_script".into(),
rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()]);
if settings.windows_update_only() || settings.managed_scripts() {
// The caller has verified the live enrolled peer and its independent clock.
let mut caps = vec![
"helper.system.v1".into(),
format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
format!("helper.policy.sha256:{}", pin.policy_sha256),
"system:run_script".into(),
];
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
}
if settings.managed_scripts() {
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
}
return Ok(caps);
}
let ordinary = load_ordinary(pin);
let (q, result_bytes) = match ordinary {
@@ -20,6 +20,8 @@ struct Input {
agent_sha256: String,
helper_sha256: String,
max_runtime_seconds: u32,
#[serde(default)]
managed_scripts: bool,
}
pub fn render() -> Result<()> {
@@ -48,7 +50,7 @@ pub fn render() -> Result<()> {
})
};
let settings = Settings {
schema_version: 3,
schema_version: if data.managed_scripts { 5 } else { 3 },
binding: data.binding,
agent: role(
crate::SERVICE_NAME,
@@ -63,11 +65,13 @@ pub fn render() -> Result<()> {
data.helper_sha256,
)?,
allowed_services: vec![],
max_runtime_seconds: 30,
max_runtime_seconds: if data.managed_scripts { 120 } else { 30 },
enable_effects: true,
allow_reboot: false,
allowed_msi_recipe_sha256: None,
allowed_script_profiles: None,
allowed_script_profiles: data.managed_scripts.then(|| {
vec![rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
}),
windows_update_max_runtime_seconds: Some(data.max_runtime_seconds),
};
settings.validate()?;
+4 -2
View File
@@ -78,9 +78,11 @@ impl Config {
})
}
fn validate_profile(&self) -> Result<()> {
let state = self.state.as_path();
ensure!(
self.state.as_path()
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE),
state == std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE)
|| (self.profile == HelperProfile::FullMaintenanceV1
&& state == std::path::Path::new("/var/lib/rmm-discovery-helper")),
"SHARED_HELPER_LEDGER_REQUIRED"
);
if self.profile == HelperProfile::FullMaintenanceV1 {
+1
View File
@@ -27,6 +27,7 @@ mod oidc;
mod pagination;
mod permissions;
mod root_policy;
mod managed_scripts;
mod scheduler;
mod script_library;
mod synchronization;
+61
View File
@@ -0,0 +1,61 @@
//! Permanent authorization ceilings for installed, pinned script helpers.
//! Plan submission, interactive approval and signed start grants are unchanged.
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
use axum::http::StatusCode;
use rmm_domain::jobs::{Action, JobPayload};
use serde::Deserialize;
use std::{fs, os::unix::fs::MetadataExt, path::Path};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u8,
linux: Vec<RootScope>,
windows: Vec<SystemScope>,
}
fn invalid() -> Error {
Error(StatusCode::CONFLICT, "MANAGED_SCRIPT_POLICY_INVALID")
}
impl Policy {
fn permits(&self, principal: &str, job: &JobPayload, caps: &[String]) -> bool {
if !matches!(job.action, Action::RunScript { .. })
|| !job.action.full_maintenance()
|| !job.action.validate()
|| !job.action.available_for(&job.execution_identity, caps)
|| !job.action.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
{
return false;
}
match job.execution_identity.as_str() {
"root" => self.linux.iter().any(|scope| scope.permits(principal, job, caps, None)),
"system" => self.windows.iter().any(|scope| scope.permits(principal, job, caps, false, true, false)),
_ => false,
}
}
}
pub(crate) fn permits(principal: &str, job: &JobPayload, caps: &[String]) -> Result<bool, Error> {
if !job.action.full_maintenance() {
return Ok(false);
}
let Some(path) = std::env::var_os("RMM_MANAGED_SCRIPT_POLICY_FILE") else {
return Ok(false);
};
let key = std::env::var_os("RMM_JOB_KEY_FILE").ok_or_else(invalid)?;
let signer = fs::symlink_metadata(key).map_err(|_| invalid())?;
if !signer.is_file() {
return Err(invalid());
}
let bytes = crate::windows_policy::protected_bytes(Path::new(&path), signer.uid())
.map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
if policy.schema_version != 1
|| policy.linux.len() + policy.windows.len() > 64
|| !policy.windows.iter().all(SystemScope::valid)
{
return Err(invalid());
}
Ok(policy.permits(principal, job, caps))
}
+1 -1
View File
@@ -126,7 +126,7 @@ fn tools() -> Vec<Tool> {
),
tool::<PlanScript>(
"scripts.plan",
"Plan the selected immutable script revision against fixed assets. Submit the returned plan for WebUI approval via operations.submit.",
"Plan the selected immutable script revision against fixed assets. Set input.execution_identity to select agent_service, root on Linux or system on Windows. Omitting it uses the revision default. Submit the plan for WebUI approval via operations.submit.",
),
tool::<Devices>(
"updates.list_releases",
+7 -4
View File
@@ -20,7 +20,7 @@ pub struct RootPolicy {
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RootScope {
pub(crate) struct RootScope {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
@@ -158,7 +158,7 @@ impl RootScope {
&& self.enrollment_generation == job.enrollment_generation
&& self.assignment_version == job.assignment_version
}
fn permits(
pub(crate) fn permits(
&self,
principal: &str,
job: &JobPayload,
@@ -338,6 +338,11 @@ pub async fn authorize(
for permission in required_permissions(job, false) {
crate::permissions::require(tx, principal, permission).await?;
}
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").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 caps: Vec<String> = serde_json::from_value(caps)?;
if crate::managed_scripts::permits(principal, job, &caps)? {
return Ok(());
}
let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
@@ -356,8 +361,6 @@ pub async fn authorize(
crate::permissions::require(tx, principal, "logs:read_sensitive").await?;
}
}
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").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 caps: Vec<String> = serde_json::from_value(caps)?;
if !policy
.scopes
.iter()
+6 -1
View File
@@ -38,6 +38,7 @@ pub struct Selection {
pub reason: String,
pub max_runtime_seconds: u32,
pub max_output_bytes: u32,
pub execution_identity: Option<String>,
}
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
@@ -169,7 +170,9 @@ pub async fn plan(
version: row.get("version"),
script_sha256: hash(body.as_bytes()),
};
let identity: String = row.get("execution_identity");
let identity = input
.execution_identity
.unwrap_or_else(|| row.get("execution_identity"));
let action = script(row.get("interpreter"), &identity, body)?;
let plan = PlanInput {
targets: input.targets,
@@ -299,6 +302,7 @@ pub(crate) mod tests {
reason: "standard diagnostic library contract".into(),
max_runtime_seconds: 120,
max_output_bytes: 65536,
execution_identity: None,
};
let planned = plan(s, p, tenant, id, selection).await;
if identity == "system" {
@@ -394,6 +398,7 @@ pub(crate) mod tests {
reason: "isolated library contract".into(),
max_runtime_seconds: 60,
max_output_bytes: 4096,
execution_identity: None,
};
assert_eq!(
plan(s, p, tenant, id, selection(windows))
+8 -5
View File
@@ -25,7 +25,7 @@ struct SystemPolicy {
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SystemScope {
pub(crate) struct SystemScope {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
@@ -76,7 +76,7 @@ fn fixture_service(name: &str) -> bool {
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
}
impl SystemScope {
fn valid(&self) -> bool {
pub(crate) fn valid(&self) -> bool {
!self.tenant_id.is_nil()
&& !self.asset_id.is_nil()
&& !self.agent_id.is_nil()
@@ -127,7 +127,7 @@ impl SystemScope {
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
&& (1..=120).contains(&self.max_runtime_seconds)
}
fn permits(
pub(crate) fn permits(
&self,
principal: &str,
job: &JobPayload,
@@ -293,7 +293,7 @@ fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
}
Ok(())
}
fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
pub(crate) fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
no_symlink_components(path)?;
protected_parent_chain(path, owner)?;
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
@@ -374,9 +374,12 @@ pub async fn authorize(
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)?;
if crate::managed_scripts::permits(principal, job, &capabilities)? {
return Ok(());
}
let policy = load()?;
if !policy.permits(principal, job, &capabilities, Utc::now()) {
return Err(Error(
StatusCode::FORBIDDEN,
@@ -0,0 +1,16 @@
services:
api:
environment:
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
volumes:
- ../devstate/managed-scripts:/managed-scripts:ro
public-api:
environment:
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
volumes:
- ../devstate/managed-scripts:/managed-scripts:ro
gateway:
environment:
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
volumes:
- ../devstate/managed-scripts:/managed-scripts:ro
+42 -40
View File
@@ -27,6 +27,7 @@ import {
scriptPlatform,
type Identity,
type Interpreter,
type Revision,
type Script
} from './script-catalog';
import { ScriptFields } from './script-library';
@@ -137,9 +138,9 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
const ticket = canPlanScript ? savedTicket : null;
const [mode, setMode] = useState<'library' | 'once' | 'reboot'>(() => canPlanScript ? 'library' : 'reboot');
const [revisionId, choose] = useState('');
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [fullRoot, setFullRoot] = useState(false);
const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now()));
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
@@ -221,6 +222,9 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
);
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity;
const rebootIdentity = hasWindows ? 'system' : 'root';
const rebootAsset = mode === 'reboot' && step === 2 && selected.length === 1 ? selected[0] : null;
const rebootTarget = useResource(async signal => {
@@ -248,8 +252,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
);
const identity = revision.execution_identity;
if (identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
if (identity && identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
}
if (mode === 'reboot') {
@@ -285,16 +288,14 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
const windowUpdate =
mode === 'library' &&
revision?.script_sha256 === windowsUpdateScriptHash &&
revision.execution_identity === 'system';
const identity =
mode === 'library' ? revision?.execution_identity : (hasWindows ? windows : linux).execution_identity;
const maxRuntime = windowUpdate
? 3600
: identity === 'system'
? 120
: identity === 'root' && (mode === 'library' || fullRoot)
? 300
: 3600;
identity === 'system';
const maxRuntime = windowUpdate ? 3600 : identity === 'system' ? 120 : identity === 'root' ? 300 : 3600;
function chooseLibrary(next: Revision | undefined) {
choose(next?.revision_id ?? '');
setLibraryIdentity(null);
setRuntime(next?.script_sha256 === windowsUpdateScriptHash && next.execution_identity === 'system' ? 3600 : 120);
setLimit(65536);
}
async function prepare(e: FormEvent) {
e.preventDefault();
if (lock.current || !(mode === 'reboot' ? canPlanReboot : canPlanScript) || issues.length || !selected.length) return;
@@ -354,7 +355,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
raw = await request(path('/script-revisions/' + revision.revision_id + '/plan'), {
csrf: auth.csrf_token,
body: { ...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit }
body: {
...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit,
...(libraryIdentity ? { execution_identity: libraryIdentity } : {})
}
});
} else {
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
@@ -375,7 +379,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
expected_stdout: expectedStdout(expected, expectedFormat),
timeout_seconds: runtime,
max_output_bytes: limit,
...(identity === 'system' || (identity === 'root' && fullRoot)
...(identity === 'system' || identity === 'root'
? { privileged_script_profile: fullMaintenanceScriptProfile }
: {})
};
@@ -399,7 +403,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
!selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
j.script !== script?.script_utf8 ||
j.identity !== script.execution_identity ||
j.identity !== identity ||
j.interpreter !== script.interpreter ||
j.runtimeSeconds !== runtime ||
j.outputBytes !== limit ||
@@ -701,9 +705,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
required
value={revision?.name ?? ''}
onChange={(e) => {
const next = heads.find((h) => h.name === e.target.value);
choose(next?.revision_id ?? '');
setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);
chooseLibrary(heads.find((h) => h.name === e.target.value));
}}
>
<option value="">Skript wählen</option>
@@ -721,15 +723,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
Version
<select
value={revisionId}
onChange={(e) => {
choose(e.target.value);
setRuntime(
scripts.data?.find((r) => r.revision_id === e.target.value)?.script_sha256 ===
windowsUpdateScriptHash
? 3600
: 120
);
}}
onChange={(e) => chooseLibrary(scripts.data?.find((r) => r.revision_id === e.target.value))}
>
{scripts.data
?.filter((r) => r.name === revision.name)
@@ -740,12 +734,23 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
))}
</select>
</label>
<p>
{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}
</p>
{revision.execution_identity !== 'agent_service' && (
<p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>
)}
<p>{interpreterNames[revision.interpreter]}</p>
<label>
Ausführen als
<select value={identity} onChange={(e) => {
const next = e.target.value as Identity;
setLibraryIdentity(next);
setRuntime(revision.script_sha256 === windowsUpdateScriptHash && next === 'system' ? 3600 : 120);
setLimit(65536);
}}>
<option value="agent_service">{identityNames.agent_service}</option>
{(['root', 'system'] as const).filter((value) =>
value === (revision.interpreter === 'powershell' ? 'system' : 'root')
).map((value) => (
<option key={value} value={value} disabled={!allowed(auth, value + ':execute')}>{identityNames[value]}</option>
))}
</select>
</label>
</>
)}
</>
@@ -753,12 +758,6 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{linux.execution_identity === 'root' && hasLinux && (
<label>
<input type="checkbox" checked={fullRoot} onChange={(e) => setFullRoot(e.target.checked)} />
Vollwartung als root anfordern
</label>
)}
</>
) : (
<p className="warning">
@@ -766,6 +765,9 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
Der Agent muss nach dem Neustart wieder Kontakt aufnehmen.
</p>
)}
{mode !== 'reboot' && identity && identity !== 'agent_service' && (
<p className="warning">Der genehmigte Skriptauftrag erhält volle Hostrechte als {identityNames[identity]}.</p>
)}
<label>
Begründung
<input required maxLength={1024} value={reason} onChange={(e) => setReason(e.target.value)} />