From c692316abe69c1a9ce18a2e3243c31057e86b46d Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Wed, 18 Nov 2026 11:58:55 +0100 Subject: [PATCH] Bind Windows script contexts to the installed signed helper --- Cargo.lock | 2 +- crates/agent-windows/Cargo.toml | 2 +- crates/agent-windows/src/helper_system.rs | 3 + crates/agent-windows/src/release_service.rs | 19 ++ .../src/release_service_switch.ps1 | 19 +- crates/agent-windows/src/runtime.rs | 25 ++- .../agent-windows/src/system_capabilities.rs | 3 + .../agent-windows/src/windows_update_setup.rs | 16 +- crates/server/src/bootstrap/install.ps1 | 190 +++++++++++++++++- tests/windows_script_helper_bootstrap.ps1 | 80 ++++++++ 10 files changed, 345 insertions(+), 14 deletions(-) create mode 100644 tests/windows_script_helper_bootstrap.ps1 diff --git a/Cargo.lock b/Cargo.lock index a560ff7..7e7a095 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2213,7 +2213,7 @@ dependencies = [ [[package]] name = "rmm-agent-windows" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index 4615324..31115f6 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rmm-agent-windows" -version = "0.1.11" +version = "0.1.12" edition.workspace = true license.workspace = true diff --git a/crates/agent-windows/src/helper_system.rs b/crates/agent-windows/src/helper_system.rs index 0b830b7..1e23540 100644 --- a/crates/agent-windows/src/helper_system.rs +++ b/crates/agent-windows/src/helper_system.rs @@ -1153,6 +1153,9 @@ impl SystemHelper { request, } => { let job = self.settings.binding.job(&request.job_bytes)?; + if self.settings.managed_scripts() { + ensure!(self.settings.permits_script(&job), "MANAGED_SYSTEM_SCRIPT_REQUIRED"); + } if matches!(job.action, Action::UpdateAgent { .. }) { ensure!( self.pending_update_activation.is_none(), diff --git a/crates/agent-windows/src/release_service.rs b/crates/agent-windows/src/release_service.rs index dea0513..54625f3 100644 --- a/crates/agent-windows/src/release_service.rs +++ b/crates/agent-windows/src/release_service.rs @@ -289,6 +289,25 @@ impl Device { } } +/// Report the signed release layout of the already authenticated live SCM/IPC pair. +/// The server independently verifies the pair's catalog release and helper digest. +pub(crate) fn managed_script_release(pin: &crate::helper_ipc::Pin) -> Result { + let dir = pin.helper.binary.parent().context("missing installed helper directory")?; + let release = dir.file_name().and_then(|n| n.to_str()).context("missing release directory")?; + let id = Uuid::parse_str(release)?; + ensure!(release == id.to_string() && dir == generation(id) + && pin.agent.binary == dir.join(AGENT) && pin.helper.binary == dir.join(HELPER), + "managed scripts require a pinned release pair"); + let path = dir.join("manifest.json"); + let raw = protected(&path, rmm_updater::MAX_MANIFEST_BYTES)?; + let manifest: ReleaseManifest = serde_json::from_slice(&raw)?; + ensure!(manifest.platform == VERIFY && manifest.release_id == id + && manifest.artifacts[0].sha256 == pin.agent.binary_sha256 + && manifest.artifacts[1].sha256 == pin.helper.binary_sha256, + "managed helper differs from installed release manifest"); + Ok(id) +} + fn local_manifest(installed: &Installed) -> Result { let root = generation(installed.release_id); let raw = protected(&root.join("manifest.json"), rmm_updater::MAX_MANIFEST_BYTES)?; diff --git a/crates/agent-windows/src/release_service_switch.ps1 b/crates/agent-windows/src/release_service_switch.ps1 index 5089252..9db1bc2 100644 --- a/crates/agent-windows/src/release_service_switch.ps1 +++ b/crates/agent-windows/src/release_service_switch.ps1 @@ -51,12 +51,29 @@ if ($managed) { $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.' } + # Old renderers require this input; the successor preserves the complete + # existing scope, including an absent long Windows Update permission. + $longRuntime = 3600 + if ($settings.PSObject.Properties['windows_update_max_runtime_seconds']) { $longRuntime = $settings.windows_update_max_runtime_seconds } $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) | + max_runtime_seconds=$longRuntime; 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 + # Rollback may select an earlier renderer. Compare the complete protected + # policy, allowing only the two release image paths and digests to change. + $scope = $pins.helper_settings | ConvertFrom-Json + if ($scope.agent.binary -cne (Join-Path (Split-Path $helperExe) 'rmm-agent-windows.exe') -or + $scope.helper.binary -cne $helperExe -or $scope.agent.binary_sha256 -cne 'SELECTED_AGENT_SHA256' -or + $scope.helper.binary_sha256 -cne 'SELECTED_HELPER_SHA256') { throw 'Rendered helper image pins differ from the selected release.' } + foreach ($role in @('agent','helper')) { + $scope.$role.binary = $settings.$role.binary + $scope.$role.binary_sha256 = $settings.$role.binary_sha256 + } + if (($scope | ConvertTo-Json -Depth 12 -Compress) -cne ($settings | ConvertTo-Json -Depth 12 -Compress)) { + throw 'Agent release cannot change the managed script authorization.' + } Wait-Stopped 'RmmDiscoveryWindows' Wait-Stopped 'RmmDiscoverySystemHelper' Replace-Pin $settingsPath $pins.helper_settings diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index 82f64d1..d7bccb5 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -1409,6 +1409,11 @@ impl Agent { Ok(()) } fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool { + if self.config.localservice_time_policy.is_some() + && !matches!(job.action, rmm_domain::jobs::Action::RunScript { .. }) + { + return false; + } if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service" && !(job.execution_identity == "system" && (self.config.windows_update_helper && job.action.windows_update_or_identity_probe() @@ -1564,7 +1569,7 @@ impl Agent { && native::require_local_service().is_ok() { caps.push("rmm.sync.v1".into()); - if !self.config.windows_echo_probe_only { + if !self.config.windows_echo_probe_only && self.config.localservice_time_policy.is_none() { caps.push("refresh_inventory".into()); } if rmm_agent_windows::actions::powershell().is_ok() { @@ -1579,8 +1584,22 @@ impl Agent { if !self.config.windows_echo_probe_only && let Some(helper) = &self.helper { - caps.extend(helper.qualified_capabilities()); - if helper.update_observer_configured() + let enrolled = self.config.localservice_time_policy.is_some(); + if enrolled { + if self.config.managed_script_helper || self.config.windows_update_helper { + caps.extend(helper.qualified_capabilities().into_iter().filter(|cap| { + matches!(cap.as_str(), "helper.system.v1" | "system:run_script" + | rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY + | rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY) + || cap.starts_with("helper.binary.sha256:") + || cap.starts_with("helper.policy.sha256:") + || cap.starts_with("script.helper.release:") + })); + } + } else { + caps.extend(helper.qualified_capabilities()); + } + if !enrolled && helper.update_observer_configured() && self.update_observer.cached().is_some_and(|r|r.observation.predecessor.as_ref().is_some_and(|p|p.helper_sha256==helper.helper_binary_hash())) { for cap in self.update_observer.capabilities(){if !caps.contains(&cap){caps.push(cap);}} } diff --git a/crates/agent-windows/src/system_capabilities.rs b/crates/agent-windows/src/system_capabilities.rs index 83bc15f..39e5df6 100644 --- a/crates/agent-windows/src/system_capabilities.rs +++ b/crates/agent-windows/src/system_capabilities.rs @@ -55,6 +55,9 @@ pub fn qualified( } if settings.managed_scripts() { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into()); + if let Ok(id) = crate::release_service::managed_script_release(pin) { + caps.push(format!("script.helper.release:{id}")); + } } return Ok(caps); } diff --git a/crates/agent-windows/src/windows_update_setup.rs b/crates/agent-windows/src/windows_update_setup.rs index 8e1b7d9..5e75255 100644 --- a/crates/agent-windows/src/windows_update_setup.rs +++ b/crates/agent-windows/src/windows_update_setup.rs @@ -1,5 +1,4 @@ -//! Render the two public configuration files for the narrowly scoped, enrolled -//! development helper. The operator installs them after reviewing the live pair. +//! Render the enrolled script helper settings and peer pin for installation or a signed pair update. use crate::{ helper_ipc::{self as ipc, PeerPin}, helper_system::Settings, @@ -49,7 +48,7 @@ pub fn render() -> Result<()> { binary_sha256: digest, }) }; - let settings = Settings { + let mut settings = Settings { schema_version: if data.managed_scripts { 5 } else { 3 }, binding: data.binding, agent: role( @@ -74,6 +73,17 @@ pub fn render() -> Result<()> { }), windows_update_max_runtime_seconds: Some(data.max_runtime_seconds), }; + if data.managed_scripts && std::path::Path::new(crate::helper_system::CONFIG_PATH).try_exists()? { + // Older fixed workers call this same renderer without a predecessor + // argument. Read the protected local settings before changing image pins. + let (previous, _pins) = crate::helper_system::read_settings()?; + ensure!( + previous.managed_scripts() + && ipc::binding_hash(&previous.binding)? == ipc::binding_hash(&settings.binding)?, + "MANAGED_SCRIPT_PREDECESSOR_SCOPE" + ); + settings = Settings { agent: settings.agent, helper: settings.helper, ..previous }; + } settings.validate()?; let pin = settings.pin()?; let result = serde_json::json!({"helper_settings":serde_json::to_string(&settings)?, diff --git a/crates/server/src/bootstrap/install.ps1 b/crates/server/src/bootstrap/install.ps1 index a25a88e..6b4d4c1 100644 --- a/crates/server/src/bootstrap/install.ps1 +++ b/crates/server/src/bootstrap/install.ps1 @@ -4,6 +4,7 @@ param( [Parameter(Mandatory)][Uri]$BootstrapBase, [Security.SecureString]$EnrollmentToken, + [switch]$EnableAdministratorScripts, [ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')] [string]$Platform = 'x86_64-pc-windows-gnu' ) @@ -66,8 +67,187 @@ function Set-Text([string]$Path, [string]$Value) { function Get-Hash([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } +# The network process stays LocalService. Only the pinned local helper consumes +# SYSTEM grants. Its private ledger persists across restarts and signed updates. +function Assert-AdminPath([string]$Path, [string]$StopAt) { + $item = Get-Item -LiteralPath $Path -Force + while ($item) { + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Unexpected reparse point: $($item.FullName)" } + $acl = Get-Acl -LiteralPath $item.FullName + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($administrators.Value,$system.Value)) { + throw "Administrator-owned path required: $($item.FullName)" + } + foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) { + if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrators.Value,$system.Value) -and + ([int64]$rule.FileSystemRights -band 0x500d0156)) { throw "Writable installation path: $($item.FullName)" } + } + if ($item.FullName -ieq $StopAt) { return } + $item = if ($item -is [IO.FileInfo]) { $item.Directory } else { $item.Parent } + } + throw 'Path outside the expected installation directory.' +} + +function Publish-HelperText([string]$Path, [string]$Text) { + $pending = $Path + '.' + [Guid]::NewGuid() + try { + $f = [IO.File]::Open($pending, 'CreateNew') + try { + $bytes = $utf8.GetBytes($Text) + $f.Write($bytes, 0, $bytes.Length) + $f.Flush($true) + } finally { $f.Dispose() } + $acl = Get-Acl -LiteralPath $pending + $acl.SetOwner($administrators) + Set-Acl -LiteralPath $pending -AclObject $acl + [IO.File]::Move($pending, $Path) + } finally { if (Test-Path -LiteralPath $pending) { Remove-Item -LiteralPath $pending } } +} + +function Install-ScriptHelper { + # Enrollment and ordinary updates cannot grant SYSTEM execution. This switch + # is a local administrator's choice for this particular installation. + if (!$EnableAdministratorScripts) { return } + $cfg = Join-Path $data 'config.json' + Assert-AdminPath $cfg $data + $guardPath = Join-Path $data 'release-job.lock' + Assert-AdminPath $guardPath $data + $gate = [IO.File]::Open($guardPath,'Open','ReadWrite','None') + try { + $config = [IO.File]::ReadAllText($cfg) | ConvertFrom-Json + if (!$config.PSObject.Properties['enable_jobs'] -or !$config.enable_jobs) { throw 'Local script execution is disabled.' } + $timePath = Join-Path $data 'job-time.json' + if ($config.localservice_time_policy -ine $timePath) { throw 'Expected the enrolled LocalService time policy.' } + if (($config.PSObject.Properties['windows_echo_probe_only'] -and $config.windows_echo_probe_only) -or + ($config.PSObject.Properties['windows_update_helper'] -and $config.windows_update_helper)) { + throw 'The existing restricted execution profile must finish and be closed before provisioning.' + } + $alreadyConfigured = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper + $records = Join-Path $data 'release-state' + if ((Test-Path (Join-Path $records 'release-transition.json')) -or (Test-Path (Join-Path $data 'release-transition.json'))) { + throw 'Agent update in progress. Retry the installer once it completes.' + } + $record = Join-Path $records 'installed-release.json' + if (!(Test-Path -LiteralPath $record)) { $record = Join-Path $data 'installed-release.json' } + Assert-AdminPath $record $data + $installed = [IO.File]::ReadAllText($record) | ConvertFrom-Json + $release = Get-Id $installed.release_id + $images = Join-Path $app ('releases\' + $release) + $agentExe = Join-Path $images 'rmm-agent-windows.exe' + $helperExe = Join-Path $images 'rmm-helper-windows.exe' + $worker = Join-Path $app 'rmm-updater-windows.exe' + $envelope = Join-Path $images 'envelope.json' + $ring = Join-Path $data 'release-keyring.json' + foreach ($path in @($agentExe,$helperExe,$worker,$envelope)) { Assert-AdminPath $path $app } + foreach ($path in @($ring,$timePath)) { Assert-AdminPath $path $data } + $service = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" + $pull = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryReleasePull'" + if (!$service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or + $service.PathName -cne ('"' + $agentExe + '" --service --config "' + $cfg + '"') -or + !$pull -or $pull.StartName -ine 'LocalSystem' -or $pull.PathName -cne ('"' + $worker + '" --release-service')) { + throw 'Service registrations do not match the installed release.' + } + $verified = & $worker --verify-bootstrap $ring $envelope $agentExe $helperExe + if ($LASTEXITCODE -ne 0 -or ($verified | ConvertFrom-Json).release_id -cne $release) { throw 'Installed code pair failed signature verification.' } + foreach ($binary in @($worker,$helperExe)) { + $supported = & $binary --managed-script-helper-version + if ($LASTEXITCODE -ne 0 -or $supported -cne 'managed-script-helper/1') { throw 'Update the agent pair and stable updater before enabling administrator scripts.' } + } + $id = [IO.File]::ReadAllText($identity) | ConvertFrom-Json + $policy = [IO.File]::ReadAllText($timePath) | ConvertFrom-Json + if ($policy.tenant_id -cne $installed.tenant_id -or $policy.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$') { + throw 'Enrolled job trust and installed release belong to different configurations.' + } + $binding = [ordered]@{tenant_id=(Get-Id $policy.tenant_id);agent_id=(Get-Id $id.agent_id);asset_id=(Get-Id $id.asset_id) + enrollment_generation=1;assignment_version=1;public_key_hex=$policy.job_signing_public_key_hex} + $helperName = 'RmmDiscoverySystemHelper' + $helperCommand = '"' + $helperExe + '" --service' + $agentSid = [Security.Principal.NTAccount]::new('NT SERVICE',$serviceName).Translate([Security.Principal.SecurityIdentifier]) + $root = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem' + $stamp = Join-Path $root 'script-helper-enrollment.json' + $owner = [ordered]@{agent_id=$binding.agent_id;asset_id=$binding.asset_id;tenant_id=$binding.tenant_id} | ConvertTo-Json -Compress + $helper = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'" + if ($helper -and !$alreadyConfigured -and !(Test-Path -LiteralPath $stamp)) { + throw 'Existing local helper registration must be reconciled before provisioning.' + } + if (!(Test-Path -LiteralPath $root)) { + $stage = Join-Path $data ('script-helper-' + [Guid]::NewGuid()) + [void][IO.Directory]::CreateDirectory($stage,(Get-DirectoryAcl $agentSid 'ReadAndExecute')) + try { + Publish-HelperText (Join-Path $stage 'script-helper-enrollment.json') $owner + [IO.Directory]::Move($stage,$root) + } finally { if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } } + } + Assert-AdminPath $root $root + if (Test-Path -LiteralPath $stamp) { + Assert-AdminPath $stamp $root + if ([IO.File]::ReadAllText($stamp) -cne $owner) { throw 'Local helper belongs to another enrollment.' } + } elseif (!$alreadyConfigured) { throw 'Existing helper state must be reconciled before migration.' } + + if ($helper -and ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cne $helperCommand)) { throw 'Unexpected local helper registration.' } + if (!$helper) { New-Service -Name $helperName -BinaryPathName $helperCommand -StartupType Manual | Out-Null } + & (Join-Path $env:SystemRoot 'System32\sc.exe') sidtype $helperName unrestricted | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Could not set the local helper service SID.' } + $inputDto = [ordered]@{binding=$binding;release_id=$release;agent_sha256=(Get-Hash $agentExe) + helper_sha256=(Get-Hash $helperExe);max_runtime_seconds=3600;managed_scripts=$true} + $rendered = ($inputDto | ConvertTo-Json -Depth 6 -Compress) | & $helperExe --prepare-enrolled-windows-update + if ($LASTEXITCODE -ne 0) { throw 'Helper could not bind the signed code pair to the enrollment.' } + $pins = $rendered | ConvertFrom-Json + foreach ($kv in @(@('helper.json',$pins.helper_settings),@('agent-pin.json',$pins.agent_pin))) { + $path = Join-Path $root $kv[0] + if (Test-Path -LiteralPath $path) { + Assert-AdminPath $path $root + if ([IO.File]::ReadAllText($path) -cne $kv[1]) { throw 'An existing helper pin differs from this release or enrollment.' } + } else { Publish-HelperText $path $kv[1] } + } + $private = Join-Path $root 'state' + if (!(Test-Path -LiteralPath $private)) { [void][IO.Directory]::CreateDirectory($private,(Get-DirectoryAcl $null '')) } + Assert-AdminPath $private $root + $intents = Join-Path $root 'agent-intents' + if (!(Test-Path -LiteralPath $intents)) { [void][IO.Directory]::CreateDirectory($intents,(Get-DirectoryAcl $agentSid 'ReadAndExecute')) } + Assert-AdminPath $intents $root + foreach ($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')) { + $path = Join-Path $intents $leaf + if (!(Test-Path -LiteralPath $path)) { [IO.File]::Open($path,'CreateNew').Dispose() } + if ((Get-Item -Force -LiteralPath $path).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected link in intent journal.' } + if (!$alreadyConfigured) { + $acl = [Security.AccessControl.FileSecurity]::new() + $acl.SetOwner($administrators) + $acl.SetAccessRuleProtection($true,$false) + foreach ($sid in @($system,$administrators)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')) } + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($agentSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow')) + Set-Acl -LiteralPath $path -AclObject $acl + } + } + if (!$alreadyConfigured) { + Stop-Service $serviceName + $temp = $cfg + '.' + [Guid]::NewGuid() + try { + $config | Add-Member -NotePropertyName managed_script_helper -NotePropertyValue $true -Force + Set-Text $temp ($config | ConvertTo-Json -Depth 12 -Compress) + [IO.File]::Replace($temp,$cfg,[NullString]::Value) + } catch { + Start-Service $serviceName + throw + } finally { + if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp } + } + } + try { + Set-Service $helperName -StartupType Automatic + Start-Service $helperName + } finally { Start-Service $serviceName } + } finally { $gate.Dispose() } +} + function Start-ReleaseAfterFirstContact { $receipt = Join-Path $state 'job-readiness.json' + # A previous installer can have stopped the enrolled agent just before + # committing its helper configuration. Resume the same local enrollment. + if ((Get-Service $serviceName).Status -eq 'Stopped') { + $agent = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" + if ($agent.StartName -ine 'NT AUTHORITY\LocalService') { throw 'Unexpected enrolled agent identity.' } + Start-Service $serviceName + } $until = [DateTime]::UtcNow.AddSeconds(120) while ([DateTime]::UtcNow -lt $until) { if ((Get-Service $serviceName).Status -ne 'Running') { throw 'Agent stopped before first gateway contact. Inspect the installed service.' } @@ -76,7 +256,7 @@ function Start-ReleaseAfterFirstContact { $enrolled = [IO.File]::ReadAllText($identity) | ConvertFrom-Json $hello = [IO.File]::ReadAllText($receipt) | ConvertFrom-Json if ($hello.agent_id -ceq $enrolled.agent_id -and $hello.connection_generation -ge 1) { - Start-Service $releaseService + try { Install-ScriptHelper } finally { Start-Service $releaseService } Remove-Item -LiteralPath $firstContact -Force return } @@ -85,6 +265,9 @@ function Start-ReleaseAfterFirstContact { } throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.' } +$utf8 = New-Object Text.UTF8Encoding($false) +$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') +$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18') $origin = Get-Origin $BootstrapBase $app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery' $data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery' @@ -95,7 +278,7 @@ $serviceName = 'RmmDiscoveryWindows' $releaseService = 'RmmDiscoveryReleasePull' $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) { - if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } + if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } else { Install-ScriptHelper } Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)." return } @@ -108,9 +291,6 @@ try { $token = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } if ($token -cnotmatch '^[0-9a-f]{64}$') { throw 'Invalid one-time enrollment token.' } $query = '?platform=' + $platform -$utf8 = New-Object Text.UTF8Encoding($false) -$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') -$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18') $stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N')) [void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null '')) $madeApp = $false diff --git a/tests/windows_script_helper_bootstrap.ps1 b/tests/windows_script_helper_bootstrap.ps1 new file mode 100644 index 0000000..1791d7a --- /dev/null +++ b/tests/windows_script_helper_bootstrap.ps1 @@ -0,0 +1,80 @@ +# Exercises the first-contact installer transaction with no system services or network. +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$path = Join-Path $PSScriptRoot '../crates/server/src/bootstrap/install.ps1' +$errors = $null +$ast = [Management.Automation.Language.Parser]::ParseFile((Resolve-Path $path), [ref]$null, [ref]$errors) +if ($errors) { throw ($errors.Message -join ' ') } +$setup = $ast.Find({ + param($node) + $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -ceq 'Install-ScriptHelper' +}, $false) +$realSetup = [scriptblock]::Create($setup.Body.Extent.Text.Substring(1, $setup.Body.Extent.Text.Length - 2)) +# With strict mode, trying even to look up the installation directory would fail. +$EnableAdministratorScripts = $false +& $realSetup +function Assert-AdminPath($Path, $StopAt) { } +$function = $ast.Find({ + param($node) + $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -ceq 'Start-ReleaseAfterFirstContact' +}, $false) +. ([scriptblock]::Create($function.Extent.Text)) + +$serviceName = 'RmmDiscoveryWindows' +$releaseService = 'RmmDiscoveryReleasePull' +$agentStatus = 'Stopped' +$updaterStarts = 0 +$attempt = 0 +function Get-Service($name) { + if ($name -cne $serviceName) { throw 'Unexpected SCM read' } + return @{Status=$script:agentStatus} +} +function Get-CimInstance($class, $Filter) { + if ($class -cne 'Win32_Service' -or $Filter -cne "Name='RmmDiscoveryWindows'") { throw 'Unexpected SCM registration' } + return @{StartName='NT AUTHORITY\LocalService'} +} +function Start-Service($name) { + if ($name -ceq $releaseService) { $script:updaterStarts++ } + elseif ($name -ceq $serviceName) { $script:agentStatus = 'Running' } + else { throw 'Unexpected SCM startup' } +} +function Install-ScriptHelper { + $script:attempt++ + if ($script:attempt -eq 1) { throw 'simulated provisioning interruption' } +} + +$state = Join-Path ([IO.Path]::GetTempPath()) ('rmm-script-install-test-' + [guid]::NewGuid()) +[void][IO.Directory]::CreateDirectory($state) +try { + $EnableAdministratorScripts = $true + $data = $state + $cfg = Join-Path $data 'config.json' + $policy = @{enable_jobs=$true;localservice_time_policy=(Join-Path $data 'job-time.json');windows_update_helper=$true} | ConvertTo-Json + [IO.File]::WriteAllText($cfg, $policy) + $lock = Join-Path $data 'release-job.lock' + [IO.File]::WriteAllText($lock, '') + $active = [IO.File]::Open($lock, 'Open', 'Read', 'Read') + try { + try { & $realSetup; throw 'Expected active job lock rejection' } + catch { if ($_.Exception.GetBaseException() -isnot [IO.IOException]) { throw } } + } finally { $active.Dispose() } + try { & $realSetup; throw 'Expected active restricted helper rejection' } + catch { if ($_.Exception.Message -notlike 'The existing restricted execution profile*') { throw } } + if ([IO.File]::ReadAllText($cfg) -cne $policy) { throw 'Existing job scope changed.' } + $identity = Join-Path $state 'identity.json' + $firstContact = Join-Path $state 'release-first-contact.pending' + $bytes = '{"agent_id":"8dc9094d-28f4-4aa0-86f8-abdef87d13b6"}' + [IO.File]::WriteAllText($identity, $bytes) + [IO.File]::WriteAllText((Join-Path $state 'job-readiness.json'), '{"agent_id":"8dc9094d-28f4-4aa0-86f8-abdef87d13b6","connection_generation":1}') + [IO.File]::WriteAllText($firstContact, 'pending') + try { Start-ReleaseAfterFirstContact; throw 'Expected interruption' } + catch { if ($_.Exception.Message -cne 'simulated provisioning interruption') { throw } } + if (!(Test-Path $firstContact) -or $updaterStarts -ne 1 -or $agentStatus -cne 'Running') { + throw 'Interrupted enrollment must retain its retry marker and keep both ordinary services running.' + } + Start-ReleaseAfterFirstContact + if ((Test-Path $firstContact) -or $updaterStarts -ne 2 -or $attempt -ne 2 -or [IO.File]::ReadAllText($identity) -cne $bytes) { + throw 'Retry must complete with the existing identity before removing its marker.' + } + Write-Output 'Local opt-in, active job lock, restricted helper, interrupted setup and first-contact retry passed.' +} finally { [IO.Directory]::Delete($state, $true) }