#requires -Version 5.1 #requires -RunAsAdministrator [CmdletBinding()] 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' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest if ($PSVersionTable.PSEdition -ne 'Desktop' -or -not [Environment]::Is64BitProcess -or $env:PROCESSOR_ARCHITECTURE -ne 'AMD64') { throw 'Use 64-bit Windows PowerShell on x64 Windows.' } function Get-Origin([Uri]$Uri) { if (-not $Uri.IsAbsoluteUri -or $Uri.Scheme -cne 'https' -or $Uri.HostNameType -ne 'Dns' -or $Uri.UserInfo -or $Uri.Fragment -or $Uri.Query -or $Uri.AbsolutePath -cne '/') { throw 'A DNS HTTPS origin is required.' } return $Uri.GetLeftPart([UriPartial]::Authority) } function Get-Id([string]$Value) { $id = [Guid]::ParseExact($Value, 'D') if ($id -eq [Guid]::Empty) { throw 'Empty release identifier.' } return $id.ToString('D') } function Get-Download([string]$Path, [string]$File, [long]$Limit, [bool]$Exact) { if ($Limit -lt 1 -or $Limit -gt 268435456) { throw 'Invalid bootstrap file size.' } $request = [Net.HttpWebRequest]::Create($origin + $Path) $request.AllowAutoRedirect = $false $request.Timeout = 60000 $request.ReadWriteTimeout = 60000 $request.Headers['Authorization'] = 'Enrollment ' + $token $response = $null try { $response = $request.GetResponse() if ([int]$response.StatusCode -ne 200 -or $response.ContentLength -gt $Limit) { throw 'Unexpected bootstrap response.' } $source = $response.GetResponseStream() $dest = [IO.File]::Open($File, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) try { $buffer = New-Object byte[] 65536 [long]$total = 0 while (($n = $source.Read($buffer, 0, $buffer.Length)) -gt 0) { $total += $n if ($total -gt $Limit) { throw 'Bootstrap response too large.' } $dest.Write($buffer, 0, $n) } if ($Exact -and $total -ne $Limit) { throw 'Incomplete bootstrap download.' } $dest.Flush($true) } finally { $dest.Dispose(); $source.Dispose() } } finally { if ($response) { $response.Dispose() } } } function Get-DirectoryAcl($ServiceSid, [string]$Rights) { $acl = New-Object Security.AccessControl.DirectorySecurity $acl.SetAccessRuleProtection($true, $false) $acl.SetOwner($administrators) foreach ($sid in @($administrators, $system)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) } if ($ServiceSid) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($ServiceSid, $Rights, 'ContainerInherit,ObjectInherit', 'None', 'Allow')) } return $acl } function Set-Text([string]$Path, [string]$Value) { [IO.File]::WriteAllText($Path, $Value, $utf8) } 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.' } } $preservesPolicy = & $worker --managed-script-policy-version if ($LASTEXITCODE -ne 0 -or $preservesPolicy -cne 'release-preserves-script-policy/1') { throw 'Administrator scripts require the stable updater that preserves the local policy during release switches and rollbacks.' } $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.' } 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) { try { Install-ScriptHelper } finally { 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.' } $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' $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 } else { Install-ScriptHelper } Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)." return } if ($service -or (Get-Service $releaseService -ErrorAction SilentlyContinue) -or (Test-Path -LiteralPath $app) -or (Test-Path -LiteralPath $data)) { throw 'Existing incomplete installation. Inspect the service and enrollment state before retrying.' } if (-not $EnrollmentToken) { $EnrollmentToken = Read-Host 'One-time enrollment token' -AsSecureString } $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($EnrollmentToken) 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 $stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N')) [void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null '')) $madeApp = $false $madeData = $false $madeService = $false $madeReleaseService = $false $startRequested = $false try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $metaPath = Join-Path $stage 'metadata.json' Get-Download ('/agent/v1/bootstrap/current' + $query) $metaPath 131072 $false $meta = [IO.File]::ReadAllText($metaPath) | ConvertFrom-Json if ($meta.schema_version -ne 1 -or $meta.manifest.platform -cne $platform -or $meta.manifest.artifacts.Count -ne 2 -or $meta.updater.sha256 -cnotmatch '^[0-9a-f]{64}$' -or $meta.ca_pem.Length -gt 32768 -or $meta.ca_pem -notmatch '-----BEGIN CERTIFICATE-----') { throw 'Invalid bootstrap metadata.' } $releaseId = Get-Id $meta.manifest.release_id $tenant = Get-Id $meta.tenant_id $gateway = [Uri](Get-Origin ([Uri]$meta.gateway_origin)) $addresses = @([Net.Dns]::GetHostAddresses($gateway.DnsSafeHost) | Sort-Object { $_.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork }) if (-not $addresses.Count) { throw 'Could not resolve the device gateway.' } $endpoint = [Net.IPEndPoint]::new($addresses[0], $gateway.Port) $appStage = Join-Path $stage 'application' $dataStage = Join-Path $stage 'data' $images = Join-Path $appStage ('releases\' + $releaseId) $private = Get-DirectoryAcl $null '' [void][IO.Directory]::CreateDirectory($appStage, $private) [void][IO.Directory]::CreateDirectory($images) [void][IO.Directory]::CreateDirectory($dataStage, $private) $ring = Join-Path $dataStage 'release-keyring.json' $envelope = Join-Path $images 'envelope.json' Set-Text $ring ($meta.keyring | ConvertTo-Json -Depth 16 -Compress) Set-Text $envelope ($meta.release_envelope | ConvertTo-Json -Depth 16 -Compress) $updater = Join-Path $appStage 'rmm-updater-windows.exe' Get-Download ('/agent/v1/bootstrap/updater' + $query + '&sha256=' + $meta.updater.sha256) $updater $meta.updater.bytes $true if ((Get-Hash $updater) -cne $meta.updater.sha256) { throw 'Bootstrap updater digest mismatch.' } $roles = @('agent', 'helper') for ($i = 0; $i -lt $roles.Count; $i++) { $descriptor = $meta.manifest.artifacts[$i] if ($descriptor.role -cne $roles[$i]) { throw 'Unexpected release role.' } $id = Get-Id $descriptor.artifact_id $file = Join-Path $images ('rmm-' + $roles[$i] + '-windows.exe') Get-Download ("/agent/v1/bootstrap/releases/$releaseId/artifacts/$id" + $query) $file $descriptor.bytes $true } $agentPath = Join-Path $images 'rmm-agent-windows.exe' $helperPath = Join-Path $images 'rmm-helper-windows.exe' $canonical = & $updater --verify-bootstrap $ring $envelope $agentPath $helperPath if ($LASTEXITCODE -ne 0 -or -not $canonical -or @($canonical).Count -ne 1) { throw 'Signed Windows release verification failed.' } $verified = $canonical | ConvertFrom-Json if ($verified.platform -cne $platform -or $verified.release_id -cne $releaseId) { throw 'Release identity mismatch.' } Set-Text (Join-Path $images 'manifest.json') $canonical $configPath = Join-Path $data 'config.json' $tokenPath = Join-Path $state 'enrollment.token' $ca = Join-Path $data 'server-ca.pem' Set-Text (Join-Path $dataStage 'server-ca.pem') $meta.ca_pem $config = [ordered]@{server_name=$gateway.DnsSafeHost; connect_address=$endpoint.ToString(); ca_file=$ca; state_directory=$state; enrollment_token_file=$tokenPath; transport='https'} $localJobs = $verified.minimum_updater_version -ge 2 if ($localJobs) { $features = & $agentPath --release-capabilities if ($LASTEXITCODE -ne 0 -or $features -cne 'enrolled-localservice/1') { throw 'Signed agent lacks its required LocalService profile.' } $features = & $updater --release-capabilities if ($LASTEXITCODE -ne 0 -or $features -cne 'release-job-lock/1') { throw 'Stable updater lacks coordinated job draining.' } $trust = $meta.windows_time_trust if (-not $trust -or $meta.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$' -or $trust.key_generation -lt 1 -or @($trust.public_keys_hex.PSObject.Properties).Count -notin (1..8)) { throw 'Missing enrolled Windows job trust.' } foreach ($key in $trust.public_keys_hex.PSObject.Properties) { if ($key.Value -cnotmatch '^[0-9a-f]{64}$' -or $key.Value -ceq $meta.job_signing_public_key_hex) { throw 'Invalid independent time signing key.' } } $policy = [ordered]@{schema_version=1; tenant_id=$tenant; job_signing_public_key_hex=$meta.job_signing_public_key_hex; key_generation=$trust.key_generation; server_instance=(Get-Id $trust.server_instance); public_keys_hex=$trust.public_keys_hex} Set-Text (Join-Path $dataStage 'job-time.json') ($policy | ConvertTo-Json -Depth 8 -Compress) Set-Text (Join-Path $dataStage 'release-job.lock') '' $config['enable_jobs'] = $true $config['localservice_time_policy'] = Join-Path $data 'job-time.json' $config['windows_execution_profile'] = 'powershell_51_remote_signed' } 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) $madeData = $true $liveAgent = Join-Path $app ("releases\$releaseId\rmm-agent-windows.exe") $binary = '"' + $liveAgent + '" --service --config "' + $configPath + '"' New-Service -Name $serviceName -BinaryPathName $binary -StartupType Manual -Description 'Rust Discovery HTTPS pull agent' | Out-Null $madeService = $true $sc = Join-Path $env:SystemRoot 'System32\sc.exe' & $sc config $serviceName start= auto obj= 'NT AUTHORITY\LocalService' | Out-Null if ($LASTEXITCODE -ne 0) { throw 'SCM agent identity configuration failed.' } & $sc sidtype $serviceName unrestricted | Out-Null if ($LASTEXITCODE -ne 0) { throw 'SCM service SID configuration failed.' } $sid = ([Security.Principal.NTAccount]::new('NT SERVICE', $serviceName)).Translate([Security.Principal.SecurityIdentifier]) Set-Acl -LiteralPath $app -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute') Set-Acl -LiteralPath $data -AclObject (Get-DirectoryAcl $sid 'ReadAndExecute') [void][IO.Directory]::CreateDirectory($state, (Get-DirectoryAcl $sid 'Modify')) if ($localJobs) { [void][IO.Directory]::CreateDirectory((Join-Path $state 'jobs'), (Get-DirectoryAcl $sid 'Modify')) } # Agent-side private-path checks authenticate the owner as well as the DACL. foreach ($root in @($app, $data)) { foreach ($item in @(Get-ChildItem -LiteralPath $root -Recurse -Force)) { $acl = Get-Acl -LiteralPath $item.FullName $acl.SetOwner($administrators) Set-Acl -LiteralPath $item.FullName -AclObject $acl } } Set-Text $tokenPath $token $tokenAcl = Get-Acl -LiteralPath $tokenPath $tokenAcl.SetOwner($administrators) Set-Acl -LiteralPath $tokenPath -AclObject $tokenAcl $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 Start-ReleaseAfterFirstContact Write-Output "Enrolled Rust Discovery agent $($verified.version) over HTTPS." } catch { if (-not $startRequested) { if ($madeReleaseService) { & (Join-Path $env:SystemRoot 'System32\sc.exe') delete $releaseService | Out-Null } if ($madeService) { & (Join-Path $env:SystemRoot 'System32\sc.exe') delete $serviceName | Out-Null } if ($madeData) { Remove-Item -LiteralPath $data -Recurse -Force } if ($madeApp) { Remove-Item -LiteralPath $app -Recurse -Force } } throw } finally { $token = $null Remove-Item -LiteralPath $stage -Recurse -Force }