diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index d1c3e74..f2d492f 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -59,6 +59,8 @@ pub const WINDOWS_UPDATE_SCRIPT_UTF8: &str = include_str!("windows_update.ps1"); pub const WINDOWS_UPDATE_SCRIPT_SHA256: &str = "0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf"; pub const WINDOWS_UPDATE_MAX_SECONDS: u32 = 3600; +pub const WINDOWS_UPDATE_IDENTITY_PROBE: &str = + "Write-Output ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)\n"; pub const WINDOWS_UPDATE_LONG_CAPABILITY: &str = "script.windows_update.long/1"; pub fn valid_windows_update_limit(limit: Option) -> bool { limit.is_none_or(|seconds| (121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds)) @@ -412,11 +414,18 @@ impl Action { ) } pub fn is_windows_update_template(&self) -> bool { + self.exact_windows_maintenance_script(WINDOWS_UPDATE_SCRIPT_UTF8) + } + pub fn windows_update_or_identity_probe(&self) -> bool { + self.is_windows_update_template() + || self.exact_windows_maintenance_script(WINDOWS_UPDATE_IDENTITY_PROBE) + } + fn exact_windows_maintenance_script(&self, text: &str) -> bool { matches!(self, Self::RunScript { interpreter, script_utf8, arguments, expected_stdout: None, windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned), privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1), - } if interpreter == "powershell" && arguments.is_empty() && script_utf8 == WINDOWS_UPDATE_SCRIPT_UTF8) + } if interpreter == "powershell" && arguments.is_empty() && script_utf8 == text) } pub fn windows_system_runtime_limit(&self, normal: u32, windows_update: Option) -> u32 { if self.is_windows_update_template() { @@ -483,7 +492,9 @@ impl Action { let has = |cap: &str| capabilities.iter().any(|c| c == cap); if !has(self.name()) || (self.full_maintenance() - && !((has(FULL_MAINTENANCE_CAPABILITY) || (self.is_windows_update_template() && has(WINDOWS_UPDATE_LONG_CAPABILITY))) + && !((has(FULL_MAINTENANCE_CAPABILITY) + || (self.windows_update_or_identity_probe() + && has(WINDOWS_UPDATE_LONG_CAPABILITY))) && has("rmm.sync.v1") && has(&format!("{}:run_script", identity)) && has(if identity == "root" { diff --git a/crates/server/src/bootstrap/install.ps1 b/crates/server/src/bootstrap/install.ps1 index f8d31dd..5676dba 100644 --- a/crates/server/src/bootstrap/install.ps1 +++ b/crates/server/src/bootstrap/install.ps1 @@ -5,7 +5,7 @@ param( [Parameter(Mandatory)][Uri]$BootstrapBase, [Security.SecureString]$EnrollmentToken, [ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')] - [string]$Platform = 'x86_64-pc-windows-msvc' + [string]$Platform = 'x86_64-pc-windows-msvc' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest @@ -66,15 +66,36 @@ function Set-Text([string]$Path, [string]$Value) { function Get-Hash([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } +function Start-ReleaseAfterFirstContact { + $receipt = Join-Path $state 'job-readiness.json' + $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.' } + if ((Test-Path -LiteralPath $identity -PathType Leaf) -and (Test-Path -LiteralPath $receipt -PathType Leaf)) { + # The runtime persists this generation only after authenticating the gateway and completing ClientHello. + $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 + Remove-Item -LiteralPath $firstContact -Force + return + } + } + Start-Sleep -Seconds 2 + } + throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.' +} $origin = Get-Origin $BootstrapBase $app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery' $data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery' $state = Join-Path $data 'state' $identity = Join-Path $state 'identity.json' +$firstContact = Join-Path $data 'release-first-contact.pending' $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 } Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)." return } @@ -167,6 +188,7 @@ try { Set-Text (Join-Path $dataStage 'config.json') ($config | ConvertTo-Json -Compress) $baseline = [ordered]@{schema_version=1; tenant_id=$tenant; release_id=$releaseId; release_sequence=$verified.release_sequence; manifest_sha256=(Get-Hash (Join-Path $images 'manifest.json'))} Set-Text (Join-Path $dataStage 'installed-release.json') ($baseline | ConvertTo-Json -Compress) + Set-Text (Join-Path $dataStage 'release-first-contact.pending') $releaseId [IO.Directory]::Move($appStage, $app) $madeApp = $true [IO.Directory]::Move($dataStage, $data) @@ -200,16 +222,13 @@ try { $updaterBinary = '"' + (Join-Path $app 'rmm-updater-windows.exe') + '" --release-service' New-Service -Name $releaseService -BinaryPathName $updaterBinary -StartupType Automatic -Description 'Rust Discovery signed Windows release polling' | Out-Null $madeReleaseService = $true + & $sc failure $releaseService reset= 86400 actions= restart/15000/restart/60000/restart/300000 | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'SCM release recovery configuration failed.' } + & $sc failureflag $releaseService 1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'SCM release failure recovery flag failed.' } $startRequested = $true Start-Service $serviceName - $until = [DateTime]::UtcNow.AddSeconds(120) - while (-not (Test-Path -LiteralPath $identity -PathType Leaf)) { - if ([DateTime]::UtcNow -ge $until -or (Get-Service $serviceName).Status -ne 'Running') { - throw 'Enrollment has not completed. Installed configuration and device key are retained.' - } - Start-Sleep -Seconds 2 - } - Start-Service $releaseService + Start-ReleaseAfterFirstContact Write-Output "Enrolled Rust Discovery agent $($verified.version) over HTTPS." } catch { if (-not $startRequested) { diff --git a/crates/server/src/windows_policy.rs b/crates/server/src/windows_policy.rs index 78c668a..f0429e2 100644 --- a/crates/server/src/windows_policy.rs +++ b/crates/server/src/windows_policy.rs @@ -185,7 +185,8 @@ impl SystemScope { v.contains( &rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1, ) - }) || (self.windows_update_max_runtime_seconds.is_some() && job.action.is_windows_update_template())) + }) || (self.windows_update_max_runtime_seconds.is_some() + && job.action.windows_update_or_identity_probe())) && job.action.validate() && job .action @@ -595,6 +596,31 @@ mod tests { assert!(!policy.permits("selected", &job, &caps, Utc::now())); } #[test] + fn windows_update_window_accepts_only_the_two_fixed_scripts() { + use rmm_domain::jobs::{PrivilegedScriptProfile, WindowsExecutionProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY, WINDOWS_UPDATE_SCRIPT_UTF8}; + let (mut policy, mut job, mut caps) = fixture(); + policy.schema_version = 3; + let scope = &mut policy.scopes[0]; + scope.allowed_services.clear(); + scope.windows_update_max_runtime_seconds = Some(3600); + caps.extend(["run_script", "system:run_script", "script.powershell/1", "script.powershell.process_remote_signed/1", WINDOWS_UPDATE_LONG_CAPABILITY].map(str::to_owned)); + for (script, seconds, expected) in [ + (WINDOWS_UPDATE_SCRIPT_UTF8, 3600, true), + (WINDOWS_UPDATE_IDENTITY_PROBE, 30, true), + (WINDOWS_UPDATE_IDENTITY_PROBE, 31, false), + ("Write-Output 12", 30, false), + ] { + job.action = Action::RunScript { + interpreter:"powershell".into(), script_utf8:script.into(), + arguments:vec![], expected_stdout:None, + windows_execution_profile:Some(WindowsExecutionProfile::PowerShell51RemoteSigned), + privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1), + }; + job.max_runtime_seconds = seconds; + assert_eq!(policy.permits("selected", &job, &caps, Utc::now()), expected); + } + } + #[test] fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() { let (mut policy, mut job, caps) = fixture(); let now = Utc::now();