Enable per-order privileged scripts on managed devices
This commit is contained in:
@@ -8,6 +8,10 @@ fn main() -> anyhow::Result<()> {
|
|||||||
println!("enrolled-windows-update/1");
|
println!("enrolled-windows-update/1");
|
||||||
return Ok(());
|
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()
|
rmm_agent_windows::helper_system::dispatch()
|
||||||
}
|
}
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ fn main() -> anyhow::Result<()> {
|
|||||||
println!("release-job-lock/1");
|
println!("release-job-lock/1");
|
||||||
Ok(())
|
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" => {
|
Some(flag) if flag == "--verify-bootstrap" => {
|
||||||
let release = rmm_updater::verify_bootstrap_files(
|
let release = rmm_updater::verify_bootstrap_files(
|
||||||
rmm_agent_windows::release_platform::VERIFY,
|
rmm_agent_windows::release_platform::VERIFY,
|
||||||
|
|||||||
@@ -107,10 +107,13 @@ impl Settings {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
pub(crate) fn windows_update_only(&self) -> bool {
|
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_script_profiles.is_none() && self.allowed_services.is_empty()
|
||||||
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30
|
&& 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 {
|
fn permits_script(&self, job: &JobPayload) -> bool {
|
||||||
self.schema_version >= 3
|
self.schema_version >= 3
|
||||||
&& job.execution_identity == "system"
|
&& job.execution_identity == "system"
|
||||||
@@ -133,7 +136,12 @@ impl Settings {
|
|||||||
}
|
}
|
||||||
pub fn validate(&self) -> Result<()> {
|
pub fn validate(&self) -> Result<()> {
|
||||||
ensure!(
|
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 >= 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||||
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
|
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
|
||||||
&& self
|
&& self
|
||||||
@@ -891,7 +899,7 @@ impl SystemHelper {
|
|||||||
let pin = settings.pin()?;
|
let pin = settings.pin()?;
|
||||||
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
|
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 (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())
|
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
|
||||||
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
|
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
|
||||||
let boot = WindowsBoot::capture()?;
|
let boot = WindowsBoot::capture()?;
|
||||||
|
|||||||
@@ -319,10 +319,16 @@ fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
|
|||||||
|
|
||||||
// Only typed release UUIDs enter the fixed SCM command. The actual service path,
|
// 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.
|
// 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")
|
let script = include_str!("release_service_switch.ps1")
|
||||||
.replace("FROM_UUID", &from.to_string())
|
.replace("FROM_UUID", &from.release_id.to_string())
|
||||||
.replace("TO_UUID", &to.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 windows = std::env::var_os("SystemRoot").context("Windows directory")?;
|
||||||
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
|
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
|
||||||
let result = Command::new(ps)
|
let result = Command::new(ps)
|
||||||
@@ -338,8 +344,7 @@ fn select(from: Uuid, to: Uuid) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn rollback(t: &Transition) -> Result<()> {
|
async fn rollback(t: &Transition) -> Result<()> {
|
||||||
local_manifest(&t.old)?;
|
select(&t.new, &t.old)?;
|
||||||
select(t.new.release_id, t.old.release_id)?;
|
|
||||||
write_record("rejected-release.json", &t.new)?;
|
write_record("rejected-release.json", &t.new)?;
|
||||||
fs::remove_file(record_path(INTENT))?;
|
fs::remove_file(record_path(INTENT))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -494,7 +499,7 @@ async fn cycle() -> Result<()> {
|
|||||||
let t = Transition { old: active, new };
|
let t = Transition { old: active, new };
|
||||||
write_record(INTENT, &t)?;
|
write_record(INTENT, &t)?;
|
||||||
let start = chrono::Utc::now();
|
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() {
|
if selected.is_ok() {
|
||||||
for _ in 0..18 {
|
for _ in 0..18 {
|
||||||
if let Ok(h) = device.health().await
|
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')
|
$image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe')
|
||||||
return '"' + $image + '" --service --config "' + $configPath + '"'
|
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'
|
$configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json'
|
||||||
$from = Get-Image 'FROM_UUID'
|
$from = Get-Image 'FROM_UUID'
|
||||||
$to = Get-Image 'TO_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
|
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.' }
|
$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
|
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.' }
|
$service.PathName -cnotin @($from,$to) -or ([bool]$helper -ne [bool]$managed)) { throw 'Unexpected service configuration.' }
|
||||||
if ($service.PathName -cne $to) {
|
if ($managed) {
|
||||||
$control = Get-Service 'RmmDiscoveryWindows'
|
$helperExe = Get-HelperImage 'TO_UUID'
|
||||||
if ($control.Status -ne 'Stopped') {
|
$helperTo = '"' + $helperExe + '" --service'
|
||||||
$control.Stop()
|
$helperFrom = '"' + (Get-HelperImage 'FROM_UUID') + '" --service'
|
||||||
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
|
if ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cnotin @($helperFrom,$helperTo)) { throw 'Unexpected managed helper service.' }
|
||||||
}
|
$policyRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
|
||||||
$res = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{PathName=$to}
|
$settingsPath = Join-Path $policyRoot 'helper.json'
|
||||||
if ($res.ReturnValue -ne 0) { throw 'SCM path change failed.' }
|
$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'
|
$control = Get-Service 'RmmDiscoveryWindows'
|
||||||
if ($control.Status -ne 'Running') {
|
if ($control.Status -ne 'Running') {
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ struct Config {
|
|||||||
localservice_time_policy: Option<PathBuf>,
|
localservice_time_policy: Option<PathBuf>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
windows_update_helper: bool,
|
windows_update_helper: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
managed_script_helper: bool,
|
||||||
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
|
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
enable_jobs: bool,
|
enable_jobs: bool,
|
||||||
@@ -99,7 +101,8 @@ impl Config {
|
|||||||
fn read(path: &Path) -> Result<Self> {
|
fn read(path: &Path) -> Result<Self> {
|
||||||
let raw = protected_read(path, 32768)?;
|
let raw = protected_read(path, 32768)?;
|
||||||
let config: Self = serde_json::from_slice(&raw)?;
|
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");
|
ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED");
|
||||||
}
|
}
|
||||||
if let Some(policy) = &config.localservice_time_policy {
|
if let Some(policy) = &config.localservice_time_policy {
|
||||||
@@ -817,7 +820,8 @@ impl Agent {
|
|||||||
&identity.certificate_pem,
|
&identity.certificate_pem,
|
||||||
&identity.private_key_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
|
None
|
||||||
} else { rmm_agent_windows::helper_runtime::Client::discover(
|
} else { rmm_agent_windows::helper_runtime::Client::discover(
|
||||||
&self.identity.agent_id,
|
&self.identity.agent_id,
|
||||||
@@ -1406,7 +1410,9 @@ impl Agent {
|
|||||||
}
|
}
|
||||||
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
|
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
|
||||||
if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service"
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
if self.config.windows_echo_probe_only
|
if self.config.windows_echo_probe_only
|
||||||
|
|||||||
@@ -42,12 +42,21 @@ pub fn qualified(
|
|||||||
pin.validate()?;
|
pin.validate()?;
|
||||||
let (settings, _handles) = helper_system::read_settings()?;
|
let (settings, _handles) = helper_system::read_settings()?;
|
||||||
ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin");
|
ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin");
|
||||||
if settings.windows_update_only() {
|
if settings.windows_update_only() || settings.managed_scripts() {
|
||||||
// The caller has verified an independent helper-role clock and the live
|
// The caller has verified the live enrolled peer and its independent clock.
|
||||||
// peer. Only the two built-in scripts pass both local and server gates.
|
let mut caps = vec![
|
||||||
return Ok(vec!["helper.system.v1".into(), format!("helper.binary.sha256:{}",pin.helper.binary_sha256),
|
"helper.system.v1".into(),
|
||||||
format!("helper.policy.sha256:{}",pin.policy_sha256), "system:run_script".into(),
|
format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
|
||||||
rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()]);
|
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 ordinary = load_ordinary(pin);
|
||||||
let (q, result_bytes) = match ordinary {
|
let (q, result_bytes) = match ordinary {
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ struct Input {
|
|||||||
agent_sha256: String,
|
agent_sha256: String,
|
||||||
helper_sha256: String,
|
helper_sha256: String,
|
||||||
max_runtime_seconds: u32,
|
max_runtime_seconds: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
managed_scripts: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn render() -> Result<()> {
|
pub fn render() -> Result<()> {
|
||||||
@@ -48,7 +50,7 @@ pub fn render() -> Result<()> {
|
|||||||
})
|
})
|
||||||
};
|
};
|
||||||
let settings = Settings {
|
let settings = Settings {
|
||||||
schema_version: 3,
|
schema_version: if data.managed_scripts { 5 } else { 3 },
|
||||||
binding: data.binding,
|
binding: data.binding,
|
||||||
agent: role(
|
agent: role(
|
||||||
crate::SERVICE_NAME,
|
crate::SERVICE_NAME,
|
||||||
@@ -63,11 +65,13 @@ pub fn render() -> Result<()> {
|
|||||||
data.helper_sha256,
|
data.helper_sha256,
|
||||||
)?,
|
)?,
|
||||||
allowed_services: vec![],
|
allowed_services: vec![],
|
||||||
max_runtime_seconds: 30,
|
max_runtime_seconds: if data.managed_scripts { 120 } else { 30 },
|
||||||
enable_effects: true,
|
enable_effects: true,
|
||||||
allow_reboot: false,
|
allow_reboot: false,
|
||||||
allowed_msi_recipe_sha256: None,
|
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),
|
windows_update_max_runtime_seconds: Some(data.max_runtime_seconds),
|
||||||
};
|
};
|
||||||
settings.validate()?;
|
settings.validate()?;
|
||||||
|
|||||||
@@ -78,9 +78,11 @@ impl Config {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn validate_profile(&self) -> Result<()> {
|
fn validate_profile(&self) -> Result<()> {
|
||||||
|
let state = self.state.as_path();
|
||||||
ensure!(
|
ensure!(
|
||||||
self.state.as_path()
|
state == std::path::Path::new(rmm_privileged_helper::readiness::SHARED_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"
|
"SHARED_HELPER_LEDGER_REQUIRED"
|
||||||
);
|
);
|
||||||
if self.profile == HelperProfile::FullMaintenanceV1 {
|
if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||||
|
|||||||
@@ -1629,8 +1629,6 @@ mod windows_contract_tests {
|
|||||||
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
|
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1])
|
|
||||||
.await;
|
|
||||||
let mut request = input();
|
let mut request = input();
|
||||||
request.targets.asset_ids = assets.clone();
|
request.targets.asset_ids = assets.clone();
|
||||||
let view = plan(&state, &principal, tenant, request.clone())
|
let view = plan(&state, &principal, tenant, request.clone())
|
||||||
@@ -1729,6 +1727,8 @@ mod windows_contract_tests {
|
|||||||
.execute(&admin)
|
.execute(&admin)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1])
|
||||||
|
.await;
|
||||||
let view = plan(&state, &principal, tenant, profiled).await.unwrap();
|
let view = plan(&state, &principal, tenant, profiled).await.unwrap();
|
||||||
let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||||
let bytes: Vec<u8> =
|
let bytes: Vec<u8> =
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ mod oidc;
|
|||||||
mod pagination;
|
mod pagination;
|
||||||
mod permissions;
|
mod permissions;
|
||||||
mod root_policy;
|
mod root_policy;
|
||||||
|
mod managed_scripts;
|
||||||
mod scheduler;
|
mod scheduler;
|
||||||
mod script_library;
|
mod script_library;
|
||||||
mod synchronization;
|
mod synchronization;
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -126,7 +126,7 @@ fn tools() -> Vec<Tool> {
|
|||||||
),
|
),
|
||||||
tool::<PlanScript>(
|
tool::<PlanScript>(
|
||||||
"scripts.plan",
|
"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>(
|
tool::<Devices>(
|
||||||
"updates.list_releases",
|
"updates.list_releases",
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub struct RootPolicy {
|
|||||||
}
|
}
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
struct RootScope {
|
pub(crate) struct RootScope {
|
||||||
tenant_id: Uuid,
|
tenant_id: Uuid,
|
||||||
asset_id: Uuid,
|
asset_id: Uuid,
|
||||||
agent_id: Uuid,
|
agent_id: Uuid,
|
||||||
@@ -158,7 +158,7 @@ impl RootScope {
|
|||||||
&& self.enrollment_generation == job.enrollment_generation
|
&& self.enrollment_generation == job.enrollment_generation
|
||||||
&& self.assignment_version == job.assignment_version
|
&& self.assignment_version == job.assignment_version
|
||||||
}
|
}
|
||||||
fn permits(
|
pub(crate) fn permits(
|
||||||
&self,
|
&self,
|
||||||
principal: &str,
|
principal: &str,
|
||||||
job: &JobPayload,
|
job: &JobPayload,
|
||||||
@@ -338,6 +338,11 @@ pub async fn authorize(
|
|||||||
for permission in required_permissions(job, false) {
|
for permission in required_permissions(job, false) {
|
||||||
crate::permissions::require(tx, principal, permission).await?;
|
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 policy = load()?;
|
||||||
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
|
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
|
||||||
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
|
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?;
|
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
|
if !policy
|
||||||
.scopes
|
.scopes
|
||||||
.iter()
|
.iter()
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ pub struct Selection {
|
|||||||
pub reason: String,
|
pub reason: String,
|
||||||
pub max_runtime_seconds: u32,
|
pub max_runtime_seconds: u32,
|
||||||
pub max_output_bytes: u32,
|
pub max_output_bytes: u32,
|
||||||
|
pub execution_identity: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
|
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
|
||||||
@@ -169,7 +170,9 @@ pub async fn plan(
|
|||||||
version: row.get("version"),
|
version: row.get("version"),
|
||||||
script_sha256: hash(body.as_bytes()),
|
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 action = script(row.get("interpreter"), &identity, body)?;
|
||||||
let plan = PlanInput {
|
let plan = PlanInput {
|
||||||
targets: input.targets,
|
targets: input.targets,
|
||||||
@@ -259,7 +262,59 @@ pub(crate) mod tests {
|
|||||||
) {
|
) {
|
||||||
let tenant = p.tenant;
|
let tenant = p.tenant;
|
||||||
let initial = list(s, p, tenant, PageQuery::default()).await.unwrap();
|
let initial = list(s, p, tenant, PageQuery::default()).await.unwrap();
|
||||||
let template = &initial["items"][0];
|
let items = initial["items"].as_array().unwrap();
|
||||||
|
assert_eq!(items.len(), 13);
|
||||||
|
let template = items
|
||||||
|
.iter()
|
||||||
|
.find(|item| item["name"] == "Windows-Updates installieren")
|
||||||
|
.unwrap();
|
||||||
|
for (prefix, interpreter, asset) in [
|
||||||
|
("Linux · ", "posix_sh", linux),
|
||||||
|
("Windows · ", "powershell", windows),
|
||||||
|
] {
|
||||||
|
let revisions: Vec<_> = items
|
||||||
|
.iter()
|
||||||
|
.filter(|item| item["name"].as_str().unwrap().starts_with(prefix))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(revisions.len(), 6);
|
||||||
|
for row in revisions {
|
||||||
|
let identity = if row["name"] == "Windows · Betriebssystem-Updatebedarf anzeigen" {
|
||||||
|
"system"
|
||||||
|
} else {
|
||||||
|
"agent_service"
|
||||||
|
};
|
||||||
|
assert_eq!(row["interpreter"], interpreter);
|
||||||
|
assert_eq!(row["execution_identity"], identity);
|
||||||
|
assert_eq!(row["version"], 1);
|
||||||
|
let id = Uuid::parse_str(row["revision_id"].as_str().unwrap()).unwrap();
|
||||||
|
let selection = Selection {
|
||||||
|
targets: Targets {
|
||||||
|
asset_ids: vec![asset],
|
||||||
|
},
|
||||||
|
schedule: Schedule {
|
||||||
|
not_before: Utc::now(),
|
||||||
|
start_before: Utc::now() + Duration::minutes(30),
|
||||||
|
},
|
||||||
|
rollout: Rollout {
|
||||||
|
max_parallel: 1,
|
||||||
|
halt_after_failures: 1,
|
||||||
|
},
|
||||||
|
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" {
|
||||||
|
assert_eq!(planned.unwrap_err().0, StatusCode::FORBIDDEN);
|
||||||
|
} else {
|
||||||
|
assert_eq!(
|
||||||
|
planned.unwrap()["plan_payload"]["script_revision"]["script_sha256"],
|
||||||
|
row["script_sha256"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
assert_eq!(template["name"], "Windows-Updates installieren");
|
assert_eq!(template["name"], "Windows-Updates installieren");
|
||||||
assert_eq!(template["interpreter"], "powershell");
|
assert_eq!(template["interpreter"], "powershell");
|
||||||
let native = script(
|
let native = script(
|
||||||
@@ -343,6 +398,7 @@ pub(crate) mod tests {
|
|||||||
reason: "isolated library contract".into(),
|
reason: "isolated library contract".into(),
|
||||||
max_runtime_seconds: 60,
|
max_runtime_seconds: 60,
|
||||||
max_output_bytes: 4096,
|
max_output_bytes: 4096,
|
||||||
|
execution_identity: None,
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
plan(s, p, tenant, id, selection(windows))
|
plan(s, p, tenant, id, selection(windows))
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ struct SystemPolicy {
|
|||||||
}
|
}
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
struct SystemScope {
|
pub(crate) struct SystemScope {
|
||||||
tenant_id: Uuid,
|
tenant_id: Uuid,
|
||||||
asset_id: Uuid,
|
asset_id: Uuid,
|
||||||
agent_id: Uuid,
|
agent_id: Uuid,
|
||||||
@@ -76,7 +76,7 @@ fn fixture_service(name: &str) -> bool {
|
|||||||
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
|
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
|
||||||
}
|
}
|
||||||
impl SystemScope {
|
impl SystemScope {
|
||||||
fn valid(&self) -> bool {
|
pub(crate) fn valid(&self) -> bool {
|
||||||
!self.tenant_id.is_nil()
|
!self.tenant_id.is_nil()
|
||||||
&& !self.asset_id.is_nil()
|
&& !self.asset_id.is_nil()
|
||||||
&& !self.agent_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)
|
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
|
||||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||||
}
|
}
|
||||||
fn permits(
|
pub(crate) fn permits(
|
||||||
&self,
|
&self,
|
||||||
principal: &str,
|
principal: &str,
|
||||||
job: &JobPayload,
|
job: &JobPayload,
|
||||||
@@ -293,7 +293,7 @@ fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
|
|||||||
}
|
}
|
||||||
Ok(())
|
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)?;
|
no_symlink_components(path)?;
|
||||||
protected_parent_chain(path, owner)?;
|
protected_parent_chain(path, owner)?;
|
||||||
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
||||||
@@ -374,9 +374,12 @@ pub async fn authorize(
|
|||||||
if matches!(job.action, Action::RunScript { .. }) {
|
if matches!(job.action, Action::RunScript { .. }) {
|
||||||
crate::permissions::require(tx, principal, "scripts:execute").await?;
|
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 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)?;
|
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()) {
|
if !policy.permits(principal, job, &capabilities, Utc::now()) {
|
||||||
return Err(Error(
|
return Err(Error(
|
||||||
StatusCode::FORBIDDEN,
|
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
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
-- Give existing and newly created customers the same editable starting revisions.
|
||||||
|
CREATE FUNCTION seed_standard_diagnostic_scripts(target_tenant uuid) RETURNS void
|
||||||
|
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $seed$
|
||||||
|
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
|
||||||
|
BEGIN
|
||||||
|
PERFORM set_config('app.tenant_id', target_tenant::text, true);
|
||||||
|
INSERT INTO public.script_revisions(tenant_id, name, version, interpreter, execution_identity, created_by, script_utf8)
|
||||||
|
SELECT target_tenant, name, 1, interpreter, execution_identity, 'system:bootstrap', body
|
||||||
|
FROM (VALUES
|
||||||
|
('Linux · Agent und Updater prüfen', 'posix_sh', 'agent_service', $linux_agent$#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
printf 'Ausführungskonto: %s\n' "$(id -un)"
|
||||||
|
version=$(python3 -I -c 'import json; print(json.load(open("/opt/rust-discovery-client/current/manifest.json"))["version"])' 2>/dev/null) ||
|
||||||
|
version='unbekannt (Release-Manifest nicht lesbar)'
|
||||||
|
printf 'Agent-Release auf dem Datenträger: %s\n' "$version"
|
||||||
|
systemctl show --no-pager -p Id -p LoadState -p ActiveState -p SubState rmm-discovery-agent.service
|
||||||
|
systemctl show --no-pager -p Id -p LoadState -p ActiveState -p LastTriggerUSec -p NextElapseUSecRealtime rmm-discovery-update.timer
|
||||||
|
systemctl list-timers --all --no-pager rmm-discovery-update.timer
|
||||||
|
systemctl show --no-pager -p Id -p LoadState -p Result rmm-discovery-update.service
|
||||||
|
$linux_agent$),
|
||||||
|
('Windows · Agent und Updater prüfen', 'powershell', 'agent_service', $windows_agent$$ErrorActionPreference = 'Stop'
|
||||||
|
Write-Output ('Ausfuehrungskonto: ' + [Security.Principal.WindowsIdentity]::GetCurrent().Name)
|
||||||
|
$agent = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryWindows'"
|
||||||
|
$updater = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryReleasePull'"
|
||||||
|
foreach ($entry in @(
|
||||||
|
@{ Name = 'RmmDiscoveryWindows'; Service = $agent }
|
||||||
|
@{ Name = 'RmmDiscoveryReleasePull'; Service = $updater }
|
||||||
|
)) {
|
||||||
|
$service = $entry.Service
|
||||||
|
if ($null -eq $service) {
|
||||||
|
Write-Output ($entry.Name + ': fehlt')
|
||||||
|
} else {
|
||||||
|
Write-Output ('{0}: {1}; Starttyp: {2}; Dienstkonto: {3}' -f $service.Name, $service.State, $service.StartMode, $service.StartName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($agent.PathName -match '^"([^"]+)"') {
|
||||||
|
$manifest = Join-Path (Split-Path -Parent $Matches[1]) 'manifest.json'
|
||||||
|
try {
|
||||||
|
$release = Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json
|
||||||
|
if (-not $release.version) { throw 'Version fehlt.' }
|
||||||
|
Write-Output ('Agent-Release auf dem Datentraeger: ' + $release.version)
|
||||||
|
} catch {
|
||||||
|
Write-Output 'Agent-Release: unbekannt (Release-Manifest nicht lesbar)'
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Output 'Agent-Release: unbekannt (Dienstpfad fehlt oder hat ein anderes Format)'
|
||||||
|
}
|
||||||
|
$windows_agent$),
|
||||||
|
('Linux · Speicherengpässe prüfen', 'posix_sh', 'agent_service', $linux_storage$#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
export LC_ALL=C
|
||||||
|
rows=$(df --local --block-size=1 --output=size,avail,pcent,itotal,iavail,ipcent,fstype,target)
|
||||||
|
printf 'Lokale Dateisysteme (Warnung ab 90 Prozent Block- oder Inode-Auslastung)\n'
|
||||||
|
printf '%s\n' "$rows" | awk '
|
||||||
|
NR > 1 && $1 > 0 && ($7 !~ /^(tmpfs|devtmpfs|ramfs|squashfs|iso9660)$/ || $8 == "/") {
|
||||||
|
blocks = $3 + 0
|
||||||
|
inodes = $6 + 0
|
||||||
|
score = blocks > inodes ? blocks : inodes
|
||||||
|
mount = $0
|
||||||
|
for (i = 1; i <= 7; i++) sub(/^[[:space:]]*[^[:space:]]+[[:space:]]+/, "", mount)
|
||||||
|
printf "%d\t%s\t%s\t%s/%s Byte frei (%s belegt)\tInodes frei: %s/%s (%s belegt)\n",
|
||||||
|
score, (score >= 90 ? "WARNUNG" : "OK"), mount, $2, $1, $3, $5, $4, $6
|
||||||
|
}
|
||||||
|
' | sort -t "$(printf '\t')" -k1,1nr | awk -F '\t' '
|
||||||
|
NR <= 40 { sub(/^[^\t]+\t/, ""); print }
|
||||||
|
END {
|
||||||
|
if (NR == 0) { print "Keine lokalen Dateisysteme gefunden"; exit 1 }
|
||||||
|
if (NR > 40) print "Weitere Dateisysteme: " NR - 40
|
||||||
|
}
|
||||||
|
'
|
||||||
|
$linux_storage$),
|
||||||
|
('Windows · Speicherengpässe prüfen', 'powershell', 'agent_service', $windows_storage$$ErrorActionPreference = 'Stop'
|
||||||
|
$volumes = @(Get-CimInstance -ClassName Win32_Volume -Filter 'DriveType=3' |
|
||||||
|
Where-Object { $_.Capacity -gt 0 -and $null -ne $_.FreeSpace } |
|
||||||
|
ForEach-Object {
|
||||||
|
[pscustomobject]@{
|
||||||
|
Volume = $_.Name
|
||||||
|
Capacity = $_.Capacity
|
||||||
|
Free = $_.FreeSpace
|
||||||
|
Used = 100.0 * ($_.Capacity - $_.FreeSpace) / $_.Capacity
|
||||||
|
}
|
||||||
|
} | Sort-Object Used -Descending)
|
||||||
|
if ($volumes.Count -eq 0) { throw 'Keine lokalen Volumes mit Kapazitaetswerten gefunden.' }
|
||||||
|
Write-Output 'Lokale Volumes (Warnung ab 90 Prozent Auslastung)'
|
||||||
|
foreach ($volume in ($volumes | Select-Object -First 40)) {
|
||||||
|
$status = if ($volume.Used -ge 90) { 'WARNUNG' } else { 'OK' }
|
||||||
|
Write-Output ('{0} {1} {2}/{3} Byte frei ({4:N1}% belegt)' -f $status, $volume.Volume, $volume.Free, $volume.Capacity, $volume.Used)
|
||||||
|
}
|
||||||
|
if ($volumes.Count -gt 40) { Write-Output ('Weitere Volumes: ' + ($volumes.Count - 40)) }
|
||||||
|
$windows_storage$),
|
||||||
|
('Linux · Discovery-Verbindung prüfen', 'posix_sh', 'agent_service', $linux_gateway$#!/bin/sh
|
||||||
|
exec python3 -I - <<'PYTHON'
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
root = Path("/opt/rust-discovery-client")
|
||||||
|
try:
|
||||||
|
url = urlsplit(json.loads((root / "config.json").read_text())["gateway"])
|
||||||
|
host, port = url.hostname, url.port or 443
|
||||||
|
if url.scheme != "https" or not host or url.username is not None:
|
||||||
|
raise ValueError("invalid gateway origin")
|
||||||
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
context.load_verify_locations(cafile=root / "gateway-ca.pem")
|
||||||
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
|
sys.exit("Gateway-Konfiguration oder CA-Datei fehlt oder ist nicht lesbar.")
|
||||||
|
|
||||||
|
print(f"Konfiguriertes Gateway: {host}:{port}", flush=True)
|
||||||
|
try:
|
||||||
|
family, kind, protocol, _, address = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)[0]
|
||||||
|
except OSError:
|
||||||
|
sys.exit("DNS: fehlgeschlagen.")
|
||||||
|
print(f"DNS: OK ({address[0]})", flush=True)
|
||||||
|
with socket.socket(family, kind, protocol) as client:
|
||||||
|
client.settimeout(8)
|
||||||
|
try:
|
||||||
|
client.connect(address)
|
||||||
|
except OSError:
|
||||||
|
sys.exit("TCP: fehlgeschlagen.")
|
||||||
|
print("TCP: OK", flush=True)
|
||||||
|
try:
|
||||||
|
with context.wrap_socket(client, server_hostname=host) as tls:
|
||||||
|
print(f"TLS: Servername und Zertifikatskette geprüft ({tls.version()})")
|
||||||
|
except ssl.SSLCertVerificationError as error:
|
||||||
|
sys.exit(f"TLS: Zertifikatsprüfung fehlgeschlagen ({error.verify_message}).")
|
||||||
|
except OSError:
|
||||||
|
sys.exit("TLS: Handshake fehlgeschlagen.")
|
||||||
|
PYTHON
|
||||||
|
$linux_gateway$),
|
||||||
|
('Windows · Discovery-Verbindung prüfen', 'powershell', 'agent_service', $windows_gateway$$ErrorActionPreference = 'Stop'
|
||||||
|
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery'
|
||||||
|
$config = Get-Content -LiteralPath (Join-Path $data 'config.json') -Raw | ConvertFrom-Json
|
||||||
|
$server = $config.server_name
|
||||||
|
if ($server -notmatch '^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$' -or
|
||||||
|
$config.connect_address -notmatch '^(\[[0-9a-fA-F:]+\]|[0-9.]+):([0-9]{1,5})$') {
|
||||||
|
throw 'Ungueltiger Gatewayname oder TCP-Endpunkt in der Agentkonfiguration.'
|
||||||
|
}
|
||||||
|
$address = [Net.IPAddress]::Parse($Matches[1].Trim('[', ']'))
|
||||||
|
$port = [int]$Matches[2]
|
||||||
|
if ($port -notin (1..65535)) { throw 'Ungueltiger Gatewayport.' }
|
||||||
|
Write-Output ('Konfiguriertes Gateway: {0}:{1}; TCP-Ziel: {2}' -f $server, $port, $address)
|
||||||
|
$dnsOk = $true
|
||||||
|
try {
|
||||||
|
$addresses = @([Net.Dns]::GetHostAddresses($server))
|
||||||
|
if ($addresses.Count -eq 0) { throw 'Keine Adressen.' }
|
||||||
|
Write-Output ('DNS: OK ({0}); konfiguriertes TCP-Ziel im DNS: {1}' -f (($addresses | Select-Object -First 8) -join ', '), ($addresses -contains $address))
|
||||||
|
} catch {
|
||||||
|
$dnsOk = $false
|
||||||
|
Write-Output 'DNS: fehlgeschlagen.'
|
||||||
|
}
|
||||||
|
$anchors = [Security.Cryptography.X509Certificates.X509Certificate2Collection]::new()
|
||||||
|
$pem = Get-Content -LiteralPath $config.ca_file -Raw
|
||||||
|
foreach ($block in [regex]::Matches($pem, '-----BEGIN CERTIFICATE-----\s*(?<body>[A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')) {
|
||||||
|
[void]$anchors.Add([Security.Cryptography.X509Certificates.X509Certificate2]::new(
|
||||||
|
[Convert]::FromBase64String($block.Groups['body'].Value)))
|
||||||
|
}
|
||||||
|
if ($anchors.Count -eq 0) { throw 'Gateway-CA-Datei enthaelt kein Zertifikat.' }
|
||||||
|
|
||||||
|
$client = [Net.Sockets.TcpClient]::new($address.AddressFamily)
|
||||||
|
$tls = $null
|
||||||
|
try {
|
||||||
|
$connection = $client.ConnectAsync($address, $port)
|
||||||
|
if (-not $connection.Wait(8000)) { throw 'TCP-Zeitlimit' }
|
||||||
|
Write-Output 'TCP: OK'
|
||||||
|
} catch {
|
||||||
|
$client.Dispose()
|
||||||
|
throw 'TCP: fehlgeschlagen.'
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$client.ReceiveTimeout = 8000
|
||||||
|
$client.SendTimeout = 8000
|
||||||
|
$validate = [Net.Security.RemoteCertificateValidationCallback] {
|
||||||
|
param($sender, $certificate, $osChain, $errors)
|
||||||
|
# SslStream checks the name. The agent's configured CA anchors the chain.
|
||||||
|
if ($null -eq $certificate -or
|
||||||
|
($errors -band (-bnot [Net.Security.SslPolicyErrors]::RemoteCertificateChainErrors))) { return $false }
|
||||||
|
$chain = [Security.Cryptography.X509Certificates.X509Chain]::new()
|
||||||
|
$leaf = [Security.Cryptography.X509Certificates.X509Certificate2]::new($certificate)
|
||||||
|
try {
|
||||||
|
$policy = $chain.ChainPolicy
|
||||||
|
$policy.ExtraStore.AddRange($anchors)
|
||||||
|
foreach ($element in $osChain.ChainElements) { [void]$policy.ExtraStore.Add($element.Certificate) }
|
||||||
|
$policy.VerificationFlags = [Security.Cryptography.X509Certificates.X509VerificationFlags]::AllowUnknownCertificateAuthority
|
||||||
|
$policy.RevocationMode = [Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck
|
||||||
|
$policy.UrlRetrievalTimeout = [TimeSpan]::FromSeconds(2)
|
||||||
|
[void]$policy.ApplicationPolicy.Add([Security.Cryptography.Oid]::new('1.3.6.1.5.5.7.3.1'))
|
||||||
|
if (-not $chain.Build($leaf)) { return $false }
|
||||||
|
$root = $chain.ChainElements[$chain.ChainElements.Count - 1].Certificate
|
||||||
|
foreach ($anchor in $anchors) {
|
||||||
|
if ($root.Equals($anchor)) { return $true }
|
||||||
|
}
|
||||||
|
return $false
|
||||||
|
} finally {
|
||||||
|
$leaf.Dispose()
|
||||||
|
$chain.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$tls = [Net.Security.SslStream]::new($client.GetStream(), $false, $validate)
|
||||||
|
$tls.AuthenticateAsClient($server, [Security.Cryptography.X509Certificates.X509CertificateCollection]::new(),
|
||||||
|
[Security.Authentication.SslProtocols]::None, $false)
|
||||||
|
Write-Output ('TLS: Servername und Zertifikatskette geprueft (' + $tls.SslProtocol + ').')
|
||||||
|
} finally {
|
||||||
|
if ($null -ne $tls) { $tls.Dispose() }
|
||||||
|
$client.Dispose()
|
||||||
|
foreach ($anchor in $anchors) { $anchor.Dispose() }
|
||||||
|
}
|
||||||
|
if (-not $dnsOk) { exit 1 }
|
||||||
|
$windows_gateway$),
|
||||||
|
('Linux · Neustartbedarf prüfen', 'posix_sh', 'agent_service', $linux_boot$#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
export LC_ALL=C
|
||||||
|
boot=$(awk '$1 == "btime" { print $2 }' /proc/stat)
|
||||||
|
test -n "$boot"
|
||||||
|
printf 'Letzte Bootzeit (UTC): %s\n' "$(date -u -d "@$boot" +%FT%TZ)"
|
||||||
|
if [ -e /run/reboot-required ]; then
|
||||||
|
printf 'Neustart ausstehend: ja (/run/reboot-required)\n'
|
||||||
|
elif [ -d /run ] && [ -x /run ]; then
|
||||||
|
printf 'Neustartbedarf: unbekannt (kein Marker in /run; abhängig von Distribution und Paketen)\n'
|
||||||
|
else
|
||||||
|
printf 'Neustartbedarf: unbekannt (/run nicht zugänglich)\n'
|
||||||
|
fi
|
||||||
|
$linux_boot$),
|
||||||
|
('Windows · Neustartbedarf prüfen', 'powershell', 'agent_service', $windows_boot$$ErrorActionPreference = 'Stop'
|
||||||
|
$event = Get-WinEvent -FilterHashtable @{ LogName='System'; ProviderName='Microsoft-Windows-Kernel-General'; Id=12 } -MaxEvents 1
|
||||||
|
$start = ([xml]$event.ToXml()).Event.EventData.Data | Where-Object { $_.Name -ceq 'StartTime' }
|
||||||
|
$utc = [Xml.XmlConvert]::ToDateTimeOffset($start.InnerText).UtcDateTime.ToString('o')
|
||||||
|
Write-Output ('Letzte Bootzeit (UTC, Windows-Systemereignis): ' + $utc)
|
||||||
|
$sources = @(
|
||||||
|
@{ Name = 'Windows Update'; Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' }
|
||||||
|
@{ Name = 'Komponentenwartung (CBS)'; Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' }
|
||||||
|
)
|
||||||
|
$present = $false
|
||||||
|
$unknown = $false
|
||||||
|
foreach ($source in $sources) {
|
||||||
|
try {
|
||||||
|
$marker = Test-Path -LiteralPath $source.Key
|
||||||
|
$present = $present -or $marker
|
||||||
|
$state = if ($marker) { 'vorhanden' } else { 'fehlt' }
|
||||||
|
Write-Output ($source.Name + ': ' + $state)
|
||||||
|
} catch {
|
||||||
|
$unknown = $true
|
||||||
|
Write-Output ($source.Name + ': nicht lesbar')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($present) { Write-Output 'Neustart ausstehend: ja' }
|
||||||
|
elseif ($unknown) { Write-Output 'Neustartbedarf: unbekannt' }
|
||||||
|
else { Write-Output 'Neustartbedarf: keiner laut den beiden geprueften Markern' }
|
||||||
|
$windows_boot$),
|
||||||
|
('Linux · Letzte Agent- und Updatefehler', 'posix_sh', 'agent_service', $linux_logs$#!/bin/sh
|
||||||
|
exec python3 -I - <<'PYTHON'
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["journalctl", "--since=24 hours ago", "--no-pager", "--lines=400", "--output=json",
|
||||||
|
"--output-fields=PRIORITY,MESSAGE,_SYSTEMD_UNIT",
|
||||||
|
"-u", "rmm-discovery-agent.service", "-u", "rmm-discovery-update.service"],
|
||||||
|
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||||
|
)
|
||||||
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
sys.exit("Agentjournal konnte nicht gelesen werden.")
|
||||||
|
if result.returncode != 0:
|
||||||
|
sys.exit("Agentjournal nicht lesbar (Dienstkonto oder Journal nicht verfügbar).")
|
||||||
|
partial = bool(result.stderr.strip())
|
||||||
|
if partial:
|
||||||
|
print("Agentjournal möglicherweise nur teilweise lesbar (Journalzugriff prüfen).")
|
||||||
|
|
||||||
|
print("Agent und Updater: Fehler und Warnungen aus den letzten 400 Einträgen innerhalb von 24 Stunden")
|
||||||
|
messages = []
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
event = json.loads(line)
|
||||||
|
message = event.get("MESSAGE")
|
||||||
|
if isinstance(message, str) and (
|
||||||
|
event.get("PRIORITY") in {"0", "1", "2", "3", "4"}
|
||||||
|
or re.search(r"\b(fail(?:ed|ure)?|err(?:or)?|warn(?:ing)?|timed?\s*out|denied|panic)\b", message, re.I)
|
||||||
|
):
|
||||||
|
when = datetime.fromtimestamp(int(event["__REALTIME_TIMESTAMP"]) / 1e6, timezone.utc)
|
||||||
|
messages.append(f"{when.isoformat(timespec='seconds')} {' '.join(message.split())[:300]}")
|
||||||
|
for message in messages[-20:]:
|
||||||
|
print(message)
|
||||||
|
if not messages and not partial:
|
||||||
|
print("Keine passenden Einträge gefunden.")
|
||||||
|
PYTHON
|
||||||
|
$linux_logs$),
|
||||||
|
('Windows · Letzte Agent- und Updatefehler', 'powershell', 'agent_service', $windows_logs$$ErrorActionPreference = 'Stop'
|
||||||
|
function Read-Events($filter, $limit) {
|
||||||
|
try {
|
||||||
|
Get-WinEvent -FilterHashtable $filter -MaxEvents $limit
|
||||||
|
} catch {
|
||||||
|
if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound,*') { throw }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$since = (Get-Date).AddHours(-24)
|
||||||
|
$names = @('RmmDiscoveryWindows', 'RmmDiscoveryReleasePull')
|
||||||
|
$names += @(Get-Service -Name $names -ErrorAction SilentlyContinue | Select-Object -ExpandProperty DisplayName)
|
||||||
|
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery'
|
||||||
|
$releaseStatus = Join-Path $data 'release-state\release-status.json'
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path -LiteralPath $releaseStatus -PathType Leaf)) {
|
||||||
|
$releaseStatus = Join-Path $data 'release-status.json'
|
||||||
|
}
|
||||||
|
$last = Get-Content -LiteralPath $releaseStatus -Raw | ConvertFrom-Json
|
||||||
|
if ($last.status -notin 'ok', 'error') { throw 'Unbekannter Updaterstatus.' }
|
||||||
|
$checked = [DateTimeOffset]::Parse($last.observed_at).UtcDateTime
|
||||||
|
Write-Output ('Agent-Updater: letzter protokollierter Lauf {0:o}, Status {1}' -f $checked, $last.status)
|
||||||
|
} catch {
|
||||||
|
Write-Output 'Agent-Updater: letzter Lauf unbekannt (Statusdatei fehlt oder ist nicht lesbar).'
|
||||||
|
}
|
||||||
|
$failed = $false
|
||||||
|
$events = @()
|
||||||
|
try {
|
||||||
|
$scm = @{ LogName='System'; ProviderName='Service Control Manager'; StartTime=$since; Id=7000,7001,7009,7011,7023,7024,7031,7034 }
|
||||||
|
$events += @(Read-Events $scm 250 | Where-Object {
|
||||||
|
$event = $_
|
||||||
|
$names | Where-Object { $_ -in $event.Properties.Value }
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
Write-Warning 'Service-Control-Manager-Ereignisse nicht lesbar.'
|
||||||
|
$failed = $true
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$updates = @{ LogName='Microsoft-Windows-WindowsUpdateClient/Operational'; ProviderName='Microsoft-Windows-WindowsUpdateClient'; StartTime=$since; Level=2,3 }
|
||||||
|
$events += @(Read-Events $updates 20)
|
||||||
|
} catch {
|
||||||
|
Write-Warning 'Windows-Update-Ereignisse nicht lesbar.'
|
||||||
|
$failed = $true
|
||||||
|
}
|
||||||
|
Write-Output 'Agentdienste und Windows Update: letzte 24 Stunden, hoechstens 20 Ereignisse'
|
||||||
|
foreach ($event in ($events | Sort-Object TimeCreated -Descending | Select-Object -First 20)) {
|
||||||
|
$line = ([string]$event.Message -replace '\s+', ' ').Trim()
|
||||||
|
if ($line.Length -gt 300) { $line = $line.Substring(0, 300) }
|
||||||
|
Write-Output ('{0:o} {1} #{2} {3}' -f $event.TimeCreated.ToUniversalTime(), $event.ProviderName, $event.Id, $line)
|
||||||
|
}
|
||||||
|
if ($events.Count -eq 0 -and -not $failed) { Write-Output 'Keine passenden Ereignisse gefunden.' }
|
||||||
|
if ($failed) { exit 1 }
|
||||||
|
$windows_logs$),
|
||||||
|
('Linux · Betriebssystem-Updatebedarf anzeigen', 'posix_sh', 'agent_service', $linux_updates$#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
export LC_ALL=C
|
||||||
|
if ! grep -Eq '^ID=(debian|ubuntu|"debian"|"ubuntu")$' /etc/os-release ||
|
||||||
|
! command -v apt >/dev/null; then
|
||||||
|
printf 'Diese Vorlage benötigt Debian oder Ubuntu mit APT.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
cutoff=$(date +%s)
|
||||||
|
count=0
|
||||||
|
oldest=
|
||||||
|
for index in /var/lib/apt/lists/*_Packages /var/lib/apt/lists/*_Packages.*; do
|
||||||
|
[ -f "$index" ] || continue
|
||||||
|
modified=$(stat -c %Y -- "$index")
|
||||||
|
if [ -z "$oldest" ] || [ "$modified" -lt "$oldest" ]; then oldest=$modified; fi
|
||||||
|
count=$((count + 1))
|
||||||
|
done
|
||||||
|
if [ "$count" -eq 0 ]; then
|
||||||
|
printf 'Keine lokalen APT-Paketlisten gefunden. Updatebedarf unbekannt.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
printf 'APT-Paketlisten: %s; ältester Zeitstempel (UTC): %s; Alter: %s Tage\n' \
|
||||||
|
"$count" "$(date -u -d "@$oldest" +%FT%TZ)" "$(((cutoff - oldest) / 86400))"
|
||||||
|
list=$(apt list --upgradable 2>/dev/null) || {
|
||||||
|
printf 'APT-Paketlisten konnten nicht ausgewertet werden.\n' >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
printf '%s\n' "$list" | awk '
|
||||||
|
/^[^[:space:]\/]+\// { if (++found <= 50) print }
|
||||||
|
END { print "Aktualisierbare installierte Pakete laut lokalem Stand: " (found + 0) }
|
||||||
|
'
|
||||||
|
$linux_updates$),
|
||||||
|
('Windows · Betriebssystem-Updatebedarf anzeigen', 'powershell', 'system', $windows_updates$$ErrorActionPreference = 'Stop'
|
||||||
|
$session = New-Object -ComObject Microsoft.Update.Session
|
||||||
|
$searcher = $session.CreateUpdateSearcher()
|
||||||
|
$searcher.ServerSelection = 0
|
||||||
|
$searcher.Online = $true
|
||||||
|
$searcher.CanAutomaticallyUpgradeService = $false
|
||||||
|
Write-Output 'Suche nach fehlenden Softwareupdates ueber die konfigurierte Windows-Updatequelle.'
|
||||||
|
$result = $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'")
|
||||||
|
if ($result.ResultCode -ne 2) {
|
||||||
|
throw ('Windows-Update-Suche nicht vollstaendig erfolgreich (WUA-Ergebnis ' + $result.ResultCode + ').')
|
||||||
|
}
|
||||||
|
Write-Output ('Verfuegbare Softwareupdates: ' + $result.Updates.Count)
|
||||||
|
for ($i = 0; $i -lt [Math]::Min($result.Updates.Count, 50); $i++) {
|
||||||
|
$update = $result.Updates.Item($i)
|
||||||
|
$title = $update.Title -replace '\s+', ' '
|
||||||
|
if ($title.Length -gt 300) { $title = $title.Substring(0, 300) }
|
||||||
|
Write-Output $title
|
||||||
|
}
|
||||||
|
$windows_updates$)
|
||||||
|
) AS scripts(name, interpreter, execution_identity, body)
|
||||||
|
ON CONFLICT (tenant_id, name, version) DO NOTHING;
|
||||||
|
PERFORM set_config('app.tenant_id', previous_tenant, true);
|
||||||
|
END
|
||||||
|
$seed$;
|
||||||
|
REVOKE ALL ON FUNCTION seed_standard_diagnostic_scripts(uuid) FROM PUBLIC;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION seed_tenant_script_library() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER
|
||||||
|
SET search_path = pg_catalog, public AS $$
|
||||||
|
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
|
||||||
|
BEGIN
|
||||||
|
PERFORM set_config('app.tenant_id', NEW.tenant_id::text, true);
|
||||||
|
PERFORM public.seed_windows_update_script(NEW.tenant_id);
|
||||||
|
PERFORM public.seed_standard_diagnostic_scripts(NEW.tenant_id);
|
||||||
|
PERFORM set_config('app.tenant_id', previous_tenant, true);
|
||||||
|
RETURN NEW;
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION seed_tenant_script_library() FROM PUBLIC;
|
||||||
|
|
||||||
|
DO $backfill$
|
||||||
|
BEGIN
|
||||||
|
LOCK TABLE tenants IN SHARE ROW EXCLUSIVE MODE;
|
||||||
|
PERFORM public.seed_standard_diagnostic_scripts(tenant_id) FROM tenants;
|
||||||
|
END
|
||||||
|
$backfill$;
|
||||||
+1
-1
@@ -705,7 +705,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
|||||||
{route.page === 'auftraege' && (
|
{route.page === 'auftraege' && (
|
||||||
route.tab === 'neu' ? <>
|
route.tab === 'neu' ? <>
|
||||||
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
|
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
|
||||||
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} />
|
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} onDraft={showDraft} />
|
||||||
<details className="advanced-order"><summary>Weitere Wartungsaktionen</summary>
|
<details className="advanced-order"><summary>Weitere Wartungsaktionen</summary>
|
||||||
<p>Inventur, Dienstverwaltung und weitere Wartungsaufträge planen.</p>
|
<p>Inventur, Dienstverwaltung und weitere Wartungsaufträge planen.</p>
|
||||||
<a className="quiet" href="#auftraege/wartung">Wartungsauftrag planen</a>
|
<a className="quiet" href="#auftraege/wartung">Wartungsauftrag planen</a>
|
||||||
|
|||||||
+126
-67
@@ -27,6 +27,7 @@ import {
|
|||||||
scriptPlatform,
|
scriptPlatform,
|
||||||
type Identity,
|
type Identity,
|
||||||
type Interpreter,
|
type Interpreter,
|
||||||
|
type Revision,
|
||||||
type Script
|
type Script
|
||||||
} from './script-catalog';
|
} from './script-catalog';
|
||||||
import { ScriptFields } from './script-library';
|
import { ScriptFields } from './script-library';
|
||||||
@@ -37,6 +38,7 @@ type Props = {
|
|||||||
auth: Session;
|
auth: Session;
|
||||||
initialAssetIds: string[];
|
initialAssetIds: string[];
|
||||||
onSubmitted: (operationId: string) => void;
|
onSubmitted: (operationId: string) => void;
|
||||||
|
onDraft: (planId: string) => void;
|
||||||
};
|
};
|
||||||
type Target = {
|
type Target = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -119,21 +121,26 @@ function issueMessage(err: unknown) {
|
|||||||
return errorText(err);
|
return errorText(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, customerName }: Props) {
|
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, onDraft, customerName }: Props) {
|
||||||
const path = (suffix: string) => tenantPath(tenantId, suffix);
|
const path = (suffix: string) => tenantPath(tenantId, suffix);
|
||||||
const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]);
|
const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]);
|
||||||
const [ticket, setTicket] = useState<Ticket | null>(() => resumeTicket(key));
|
const [savedTicket, setTicket] = useState<Ticket | null>(() => resumeTicket(key));
|
||||||
const [step, setStep] = useState<1 | 2>(1);
|
const [step, setStep] = useState<1 | 2>(1);
|
||||||
const [selected, setSelected] = useState<string[]>(() => [...new Set(initialAssetIds)]);
|
const [selected, setSelected] = useState<string[]>(() => [...new Set(initialAssetIds)]);
|
||||||
const [known, setKnown] = useState<Record<string, Target>>({});
|
const [known, setKnown] = useState<Record<string, Target>>({});
|
||||||
const [query, setQuery] = useState('');
|
const [query, setQuery] = useState('');
|
||||||
const [cursor, setCursor] = useState<string | null>(null);
|
const [cursor, setCursor] = useState<string | null>(null);
|
||||||
const [prior, setPrior] = useState<(string | null)[]>([]);
|
const [prior, setPrior] = useState<(string | null)[]>([]);
|
||||||
const [mode, setMode] = useState<'library' | 'once'>('library');
|
const canCreate = ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit']
|
||||||
|
.every((permission) => allowed(auth, permission));
|
||||||
|
const canPlanScript = canCreate && allowed(auth, 'scripts:execute');
|
||||||
|
const canPlanReboot = canCreate && (allowed(auth, 'root:execute') || allowed(auth, 'system:execute'));
|
||||||
|
const ticket = canPlanScript ? savedTicket : null;
|
||||||
|
const [mode, setMode] = useState<'library' | 'once' | 'reboot'>(() => canPlanScript ? 'library' : 'reboot');
|
||||||
const [revisionId, choose] = useState('');
|
const [revisionId, choose] = useState('');
|
||||||
|
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
|
||||||
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
|
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
|
||||||
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
|
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
|
||||||
const [fullRoot, setFullRoot] = useState(false);
|
|
||||||
const [reason, setReason] = useState('');
|
const [reason, setReason] = useState('');
|
||||||
const [start, setStart] = useState(() => localDate(Date.now()));
|
const [start, setStart] = useState(() => localDate(Date.now()));
|
||||||
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
|
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
|
||||||
@@ -153,13 +160,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
mounted.current = false;
|
mounted.current = false;
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
const canPlan = [
|
const canPlan = canPlanScript || canPlanReboot;
|
||||||
'inventory:read',
|
|
||||||
'operations:read',
|
|
||||||
'operations:plan',
|
|
||||||
'scripts:execute',
|
|
||||||
'operations:submit'
|
|
||||||
].every((p) => allowed(auth, p));
|
|
||||||
|
|
||||||
const devices = useResource(
|
const devices = useResource(
|
||||||
async (signal) => {
|
async (signal) => {
|
||||||
@@ -174,7 +175,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
);
|
);
|
||||||
const review = useResource(
|
const review = useResource(
|
||||||
async (signal) => {
|
async (signal) => {
|
||||||
if (!ticket) return null;
|
if (!ticket || !canPlanScript) return null;
|
||||||
const checked = await verifiedScriptOrder(
|
const checked = await verifiedScriptOrder(
|
||||||
await request(path('/operation-plans/' + ticket.id), { signal }),
|
await request(path('/operation-plans/' + ticket.id), { signal }),
|
||||||
tenantId,
|
tenantId,
|
||||||
@@ -184,7 +185,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
|
throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
|
||||||
return checked;
|
return checked;
|
||||||
},
|
},
|
||||||
[tenantId, ticket?.id, ticket?.hash, auth.principal.id]
|
[tenantId, ticket?.id, ticket?.hash, auth.principal.id, canPlanScript]
|
||||||
);
|
);
|
||||||
const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]);
|
const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]);
|
||||||
const restored = useResource(
|
const restored = useResource(
|
||||||
@@ -216,11 +217,15 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
const hasLinux = targets.some((d) => d?.platform === 'linux');
|
const hasLinux = targets.some((d) => d?.platform === 'linux');
|
||||||
const hasWindows = targets.some((d) => d?.platform === 'windows');
|
const hasWindows = targets.some((d) => d?.platform === 'windows');
|
||||||
const scripts = useResource(
|
const scripts = useResource(
|
||||||
(signal) => (canPlan && step === 2 && !ticket ? loadRevisions(tenantId, signal) : Promise.resolve([])),
|
(signal) => (canPlanScript && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
|
||||||
[tenantId, canPlan, step, !!ticket]
|
[tenantId, canPlanScript, step, !!ticket, mode]
|
||||||
);
|
);
|
||||||
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
|
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
|
||||||
const heads = latestRevisions(scripts.data ?? []);
|
const heads = latestRevisions(scripts.data ?? []);
|
||||||
|
const identity = mode === 'library'
|
||||||
|
? libraryIdentity ?? revision?.execution_identity
|
||||||
|
: (hasWindows ? windows : linux).execution_identity;
|
||||||
|
const rebootIdentity = hasWindows ? 'system' : 'root';
|
||||||
const issues: string[] = [];
|
const issues: string[] = [];
|
||||||
if (targets.some((d) => !d?.current))
|
if (targets.some((d) => !d?.current))
|
||||||
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
|
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
|
||||||
@@ -233,10 +238,13 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
issues.push(
|
issues.push(
|
||||||
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
|
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
|
||||||
);
|
);
|
||||||
const identity = revision.execution_identity;
|
if (identity && identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
|
||||||
if (identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
|
|
||||||
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
|
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
|
||||||
}
|
}
|
||||||
|
if (mode === 'reboot') {
|
||||||
|
if (selected.length !== 1) issues.push('Wählen Sie ein einzelnes Gerät für den Neustart.');
|
||||||
|
if (!allowed(auth, rebootIdentity + ':execute')) issues.push('Die Berechtigung für ' + identityNames[rebootIdentity] + ' fehlt.');
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
mode === 'once' &&
|
mode === 'once' &&
|
||||||
hasLinux &&
|
hasLinux &&
|
||||||
@@ -263,19 +271,17 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
const windowUpdate =
|
const windowUpdate =
|
||||||
mode === 'library' &&
|
mode === 'library' &&
|
||||||
revision?.script_sha256 === windowsUpdateScriptHash &&
|
revision?.script_sha256 === windowsUpdateScriptHash &&
|
||||||
revision.execution_identity === 'system';
|
identity === 'system';
|
||||||
const identity =
|
const maxRuntime = windowUpdate ? 3600 : identity === 'system' ? 120 : identity === 'root' ? 300 : 3600;
|
||||||
mode === 'library' ? revision?.execution_identity : (hasWindows ? windows : linux).execution_identity;
|
function chooseLibrary(next: Revision | undefined) {
|
||||||
const maxRuntime = windowUpdate
|
choose(next?.revision_id ?? '');
|
||||||
? 3600
|
setLibraryIdentity(null);
|
||||||
: identity === 'system'
|
setRuntime(next?.script_sha256 === windowsUpdateScriptHash && next.execution_identity === 'system' ? 3600 : 120);
|
||||||
? 120
|
setLimit(65536);
|
||||||
: identity === 'root' && (mode === 'library' || fullRoot)
|
}
|
||||||
? 300
|
|
||||||
: 3600;
|
|
||||||
async function prepare(e: FormEvent) {
|
async function prepare(e: FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (lock.current || !canPlan || issues.length || !selected.length) return;
|
if (lock.current || !(mode === 'reboot' ? canPlanReboot : canPlanScript) || issues.length || !selected.length) return;
|
||||||
lock.current = true;
|
lock.current = true;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -285,12 +291,56 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
throw Error('Die Startfrist muss nach dem frühesten Start und in der Zukunft liegen.');
|
throw Error('Die Startfrist muss nach dem frühesten Start und in der Zukunft liegen.');
|
||||||
const rollout = { max_parallel: parallel, halt_after_failures: halt };
|
const rollout = { max_parallel: parallel, halt_after_failures: halt };
|
||||||
const bound = { targets: { asset_ids: selected }, rollout, reason: reason.trim() };
|
const bound = { targets: { asset_ids: selected }, rollout, reason: reason.trim() };
|
||||||
|
if (mode === 'reboot') {
|
||||||
|
const input: PlanInput = {
|
||||||
|
...bound,
|
||||||
|
tenant_id: tenantId,
|
||||||
|
action: 'reboot',
|
||||||
|
schedule: { ...schedule, offline_policy: 'wait_until_deadline' },
|
||||||
|
rollout: { max_parallel: 1, halt_after_failures: 1 },
|
||||||
|
parameters: {
|
||||||
|
execution_identity: rebootIdentity,
|
||||||
|
reason: bound.reason,
|
||||||
|
dependency_group: 'asset-' + selected[0],
|
||||||
|
reconnect_timeout_seconds: hasWindows ? 180 : 300,
|
||||||
|
timeout_seconds: 60,
|
||||||
|
max_output_bytes: 4096
|
||||||
|
}
|
||||||
|
};
|
||||||
|
validateInput(input);
|
||||||
|
await validateSensitiveInput(input, auth);
|
||||||
|
const plan = record(await request(path('/operation-plans'), { csrf: auth.csrf_token, body: input }));
|
||||||
|
if (!Array.isArray(plan.plan_payload_bytes)) throw Error('Die gespeicherten Bytes des Neustartplans fehlen.');
|
||||||
|
await verifyPlanIntegrity(plan);
|
||||||
|
const planId = objectId(plan, 'plan');
|
||||||
|
const fixed = record(plan.plan_payload);
|
||||||
|
const jobs = Array.isArray(fixed.jobs) ? fixed.jobs : [];
|
||||||
|
const job = record(record(jobs[0]).payload);
|
||||||
|
const action = record(job.action);
|
||||||
|
if (
|
||||||
|
fixed.plan_id !== planId || fixed.tenant_id !== tenantId || fixed.principal !== auth.principal.id ||
|
||||||
|
fixed.reason !== bound.reason || fixed.max_parallel !== 1 || fixed.halt_after_failures !== 1 ||
|
||||||
|
jobs.length !== 1 || job.asset_id !== selected[0] || job.execution_identity !== rebootIdentity ||
|
||||||
|
action.action !== 'reboot' || action.reason !== bound.reason ||
|
||||||
|
action.dependency_group !== input.parameters.dependency_group ||
|
||||||
|
action.reconnect_timeout_seconds !== input.parameters.reconnect_timeout_seconds ||
|
||||||
|
job.max_runtime_seconds !== input.parameters.timeout_seconds ||
|
||||||
|
job.max_output_bytes !== input.parameters.max_output_bytes ||
|
||||||
|
Date.parse(String(job.not_before)) !== Date.parse(schedule.not_before) ||
|
||||||
|
Date.parse(String(job.start_before)) !== Date.parse(schedule.start_before)
|
||||||
|
) throw Error('Der erstellte Neustartplan weicht von diesem Entwurf ab.');
|
||||||
|
if (mounted.current) onDraft(planId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let raw: unknown;
|
let raw: unknown;
|
||||||
if (mode === 'library') {
|
if (mode === 'library') {
|
||||||
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
|
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
|
||||||
raw = await request(path('/script-revisions/' + revision.revision_id + '/plan'), {
|
raw = await request(path('/script-revisions/' + revision.revision_id + '/plan'), {
|
||||||
csrf: auth.csrf_token,
|
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 {
|
} else {
|
||||||
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
|
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
|
||||||
@@ -311,7 +361,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
expected_stdout: expectedStdout(expected, expectedFormat),
|
expected_stdout: expectedStdout(expected, expectedFormat),
|
||||||
timeout_seconds: runtime,
|
timeout_seconds: runtime,
|
||||||
max_output_bytes: limit,
|
max_output_bytes: limit,
|
||||||
...(identity === 'system' || (identity === 'root' && fullRoot)
|
...(identity === 'system' || identity === 'root'
|
||||||
? { privileged_script_profile: fullMaintenanceScriptProfile }
|
? { privileged_script_profile: fullMaintenanceScriptProfile }
|
||||||
: {})
|
: {})
|
||||||
};
|
};
|
||||||
@@ -335,7 +385,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
!selected.includes(j.assetId) ||
|
!selected.includes(j.assetId) ||
|
||||||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
|
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
|
||||||
j.script !== script?.script_utf8 ||
|
j.script !== script?.script_utf8 ||
|
||||||
j.identity !== script.execution_identity ||
|
j.identity !== identity ||
|
||||||
j.interpreter !== script.interpreter ||
|
j.interpreter !== script.interpreter ||
|
||||||
j.runtimeSeconds !== runtime ||
|
j.runtimeSeconds !== runtime ||
|
||||||
j.outputBytes !== limit ||
|
j.outputBytes !== limit ||
|
||||||
@@ -365,7 +415,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function submit() {
|
async function submit() {
|
||||||
if (!ticket || !review.data || !canPlan || lock.current) return;
|
if (!ticket || !review.data || !canPlanScript || lock.current) return;
|
||||||
lock.current = true;
|
lock.current = true;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -413,7 +463,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
<h1>Neuer Auftrag</h1>
|
<h1>Neuer Auftrag</h1>
|
||||||
</div>
|
</div>
|
||||||
<ol className="order-progress" aria-label="Auftragsschritte">
|
<ol className="order-progress" aria-label="Auftragsschritte">
|
||||||
{['Geräte', 'Skript', 'Zusammenfassung'].map((name, i) => (
|
{['Geräte', 'Aktion', 'Zusammenfassung'].map((name, i) => (
|
||||||
<li key={name} aria-current={stepNumber === i + 1 ? 'step' : undefined}>
|
<li key={name} aria-current={stepNumber === i + 1 ? 'step' : undefined}>
|
||||||
{i + 1}. {name}
|
{i + 1}. {name}
|
||||||
</li>
|
</li>
|
||||||
@@ -423,11 +473,11 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
{!canPlan ? (
|
{!canPlan ? (
|
||||||
<section>
|
<section>
|
||||||
<p>
|
<p>
|
||||||
Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von
|
Zum Erstellen eines Auftrags benötigen Sie Gerätezugriff, Rechte zum Planen und Einreichen und das
|
||||||
Skriptaufträgen.
|
Ausführungsrecht für die gewählte Aktion.
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
) : ticket ? (
|
) : ticket && canPlanScript ? (
|
||||||
<section aria-label="Auftrag prüfen">
|
<section aria-label="Auftrag prüfen">
|
||||||
<h2>Zusammenfassung</h2>
|
<h2>Zusammenfassung</h2>
|
||||||
{review.data ? (
|
{review.data ? (
|
||||||
@@ -603,7 +653,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
setError(null);
|
setError(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Weiter zum Skript
|
{canPlanReboot ? 'Weiter zur Aktion' : 'Weiter zum Skript'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
|
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
|
||||||
@@ -611,18 +661,22 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
</section>
|
</section>
|
||||||
) : (
|
) : (
|
||||||
<section>
|
<section>
|
||||||
<h2>Skript auswählen</h2>
|
<h2>{canPlanReboot ? 'Aktion auswählen' : 'Skript auswählen'}</h2>
|
||||||
<form onSubmit={prepare}>
|
<form onSubmit={prepare}>
|
||||||
<fieldset disabled={busy} className="work-form">
|
<fieldset disabled={busy} className="work-form">
|
||||||
<div className="order-source">
|
<div className="order-source">
|
||||||
<label>
|
{canPlanScript && <label>
|
||||||
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
|
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
|
||||||
Aus der Bibliothek
|
Aus der Bibliothek
|
||||||
</label>
|
</label>}
|
||||||
<label>
|
{canPlanScript && <label>
|
||||||
<input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')} />
|
<input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')} />
|
||||||
Einmaliges Skript
|
Einmaliges Skript
|
||||||
</label>
|
</label>}
|
||||||
|
{canPlanReboot && <label>
|
||||||
|
<input type="radio" name="quelle" checked={mode === 'reboot'} onChange={() => setMode('reboot')} />
|
||||||
|
Gerät neu starten
|
||||||
|
</label>}
|
||||||
</div>
|
</div>
|
||||||
{mode === 'library' ? (
|
{mode === 'library' ? (
|
||||||
<>
|
<>
|
||||||
@@ -632,9 +686,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
required
|
required
|
||||||
value={revision?.name ?? ''}
|
value={revision?.name ?? ''}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const next = heads.find((h) => h.name === e.target.value);
|
chooseLibrary(heads.find((h) => h.name === e.target.value));
|
||||||
choose(next?.revision_id ?? '');
|
|
||||||
setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="">Skript wählen</option>
|
<option value="">Skript wählen</option>
|
||||||
@@ -652,15 +704,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
Version
|
Version
|
||||||
<select
|
<select
|
||||||
value={revisionId}
|
value={revisionId}
|
||||||
onChange={(e) => {
|
onChange={(e) => chooseLibrary(scripts.data?.find((r) => r.revision_id === e.target.value))}
|
||||||
choose(e.target.value);
|
|
||||||
setRuntime(
|
|
||||||
scripts.data?.find((r) => r.revision_id === e.target.value)?.script_sha256 ===
|
|
||||||
windowsUpdateScriptHash
|
|
||||||
? 3600
|
|
||||||
: 120
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{scripts.data
|
{scripts.data
|
||||||
?.filter((r) => r.name === revision.name)
|
?.filter((r) => r.name === revision.name)
|
||||||
@@ -671,26 +715,39 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<p>
|
<p>{interpreterNames[revision.interpreter]}</p>
|
||||||
{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}
|
<label>
|
||||||
</p>
|
Ausführen als
|
||||||
{revision.execution_identity !== 'agent_service' && (
|
<select value={identity} onChange={(e) => {
|
||||||
<p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>
|
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>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : mode === 'once' ? (
|
||||||
<>
|
<>
|
||||||
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
|
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
|
||||||
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
|
{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">
|
||||||
|
Der Auftrag startet das ausgewählte Gerät nach Genehmigung neu. Ausführung als {identityNames[rebootIdentity]}.
|
||||||
|
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>
|
<label>
|
||||||
Begründung
|
Begründung
|
||||||
@@ -707,6 +764,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
Startfrist
|
Startfrist
|
||||||
<input required type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} />
|
<input required type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} />
|
||||||
</label>
|
</label>
|
||||||
|
{mode !== 'reboot' && <>
|
||||||
<label>
|
<label>
|
||||||
Laufzeit je Gerät in Sekunden
|
Laufzeit je Gerät in Sekunden
|
||||||
<input
|
<input
|
||||||
@@ -750,6 +808,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
|
|||||||
onChange={(e) => setHalt(Number(e.target.value))}
|
onChange={(e) => setHalt(Number(e.target.value))}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
</>}
|
||||||
</div>
|
</div>
|
||||||
{mode === 'once' && (
|
{mode === 'once' && (
|
||||||
<>
|
<>
|
||||||
|
|||||||
Reference in New Issue
Block a user