Integrate signed agent catalog, tenant enrollment and HTTPS installers
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
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'
|
||||
)
|
||||
$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()
|
||||
}
|
||||
$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'
|
||||
$serviceName = 'RmmDiscoveryWindows'
|
||||
$releaseService = 'RmmDiscoveryReleasePull'
|
||||
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
|
||||
if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) {
|
||||
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
|
||||
$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
|
||||
$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) $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'}
|
||||
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)
|
||||
[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'))
|
||||
# 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
|
||||
$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
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user