Integrate signed agent catalog, tenant enrollment and HTTPS installers

This commit is contained in:
2026-11-17 15:56:18 +01:00
parent 689f326460
commit 7fd17272d5
70 changed files with 12982 additions and 327 deletions
+205
View File
@@ -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
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Usage: sudo sh linux.sh https://bootstrap.example
set -eu
umask 077
file=$(mktemp)
trap 'rm -f "$file"' EXIT
cat >"$file" <<'RMM_BOOTSTRAP_PYTHON'
+400
View File
@@ -0,0 +1,400 @@
"""Bootstrap a Linux systemd client and maintain its signed release pair."""
import argparse
import datetime
import fcntl
import getpass
import hashlib
import json
import os
from pathlib import Path
import platform
import pwd
import re
import shutil
import socket
import sqlite3
import ssl
import subprocess
import sys
import tempfile
import time
from urllib.parse import urlsplit
import urllib.request
import uuid
ROOT = Path('/opt/rust-discovery-client')
STATE = Path('/var/lib/rmm-discovery')
SERVICE = 'rmm-discovery-agent.service'
TIMER = 'rmm-discovery-update.timer'
PLATFORM = 'x86_64-unknown-linux-gnu'
MAX_BINARY = 256 * 1024 * 1024
UNIT_DIR = Path('/etc/systemd/system')
def require(condition, message):
if not condition:
raise ValueError(message)
def origin(value):
parsed = urlsplit(value)
require(parsed.scheme == 'https' and parsed.hostname and parsed.username is None
and parsed.password is None and not parsed.query and not parsed.fragment
and parsed.path in ('', '/'), 'HTTPS origin required')
return 'https://' + parsed.netloc
def canonical_id(value):
require(str(uuid.UUID(value)) == value, 'invalid object identifier')
return value
def save(path, value, mode=0o644):
data = json.dumps(value, separators=(',', ':')).encode() if not isinstance(value, bytes) else value
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as tmp:
tmp.write(data)
os.fchmod(tmp.fileno(), mode)
tmp.flush()
os.fsync(tmp.fileno())
os.replace(tmp.name, path)
fd = os.open(path.parent, os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def read(path):
return json.loads(path.read_bytes())
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *_):
raise ValueError('unexpected HTTP redirect')
def retrieve(base, route, target, *, context, token=None, size=None, expected=None):
request = urllib.request.Request(origin(base) + route)
if token:
request.add_header('Authorization', 'Enrollment ' + token)
client = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(),
urllib.request.HTTPSHandler(context=context))
limit = 65536 if size is None else size
require(type(limit) is int and 0 < limit <= MAX_BINARY, 'download size outside profile')
digest = hashlib.sha256()
count = 0
with client.open(request, timeout=30) as response:
require(response.status == 200, 'download rejected')
while True:
chunk = response.read(min(65536, limit + 1 - count))
if not chunk:
break
count += len(chunk)
require(count <= limit, 'download larger than descriptor')
digest.update(chunk)
target.write(chunk)
if size is not None:
require(count == size and digest.hexdigest() == expected, 'download hash or size mismatch')
def as_device(action, *args, stdout=None):
return subprocess.run(['/usr/sbin/runuser', '-u', 'rmm-discovery', '--', sys.executable, '-I',
str(ROOT / 'lifecycle.py'), action, *map(str, args)],
stdout=stdout, check=True, timeout=240)
def device_get(route, size=None, digest=None):
config = read(ROOT / 'config.json')
version = canonical_id(read(STATE / 'certificates/current.json')['version'])
pair = STATE / 'certificates/versions' / version
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_verify_locations(cafile=str(ROOT / 'gateway-ca.pem'))
ctx.load_cert_chain(str(pair / 'device.pem'), str(pair / 'device.key'))
retrieve(config['gateway'], route, sys.stdout.buffer, context=ctx,
size=int(size) if size is not None else None, expected=digest)
def device_idle():
# The root worker holds the admission lock before consulting this journal.
with sqlite3.connect(f'file:{STATE}/journal.sqlite?mode=ro', uri=True) as conn:
busy, = conn.execute("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))").fetchone()
print('busy' if busy else 'idle')
def remote(source, route, target, descriptor=None):
size = digest = None
if descriptor:
size, digest = descriptor['bytes'], descriptor['sha256']
require(type(size) is int and 0 < size <= MAX_BINARY and re.fullmatch('[0-9a-f]{64}', digest),
'invalid binary descriptor')
with target.open('xb') as output:
if source:
base, token = source
retrieve(base, route, output, context=ssl.create_default_context(), token=token, size=size, expected=digest)
else:
args = [size, digest] if descriptor else []
as_device('fetch', route, *args, stdout=output)
output.flush()
os.fsync(output.fileno())
def pair(folder, doc, source, updater):
manifest = doc['manifest']
release_id = canonical_id(manifest['release_id'])
prefix = '/agent/v1/bootstrap/releases' if source else '/agent/v1/releases'
suffix = '?platform=' + PLATFORM if source else ''
save(folder / 'envelope.json', doc['release_envelope'])
for artifact, role in zip(manifest['artifacts'], ('agent', 'helper'), strict=True):
require(artifact['role'] == role, 'incorrect artifact role')
aid = canonical_id(artifact['artifact_id'])
remote(source, f'{prefix}/{release_id}/artifacts/{aid}{suffix}', folder / role, artifact)
(folder / role).chmod(0o755)
ring = updater.parent / 'keyring.json'
verified = subprocess.check_output([updater, '--verify-bootstrap', ring, folder / 'envelope.json',
folder / 'agent', folder / 'helper'], timeout=120)
require(json.loads(verified) == manifest, 'metadata differs from signed release')
save(folder / 'manifest.json', verified)
folder.chmod(0o755)
return manifest
def link(base, name):
target = base / 'current.next'
target.unlink(missing_ok=True)
target.symlink_to('releases/' + canonical_id(name))
os.replace(target, base / 'current')
fd = os.open(base, os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def installed():
return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout)
def healthy(version, baseline, duration=90):
until = time.monotonic() + duration
while time.monotonic() < until:
try:
record = installed()
contact = record.get('last_contact_at')
if contact:
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
if (time.time() - 65 < recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline):
return True
except (subprocess.SubprocessError, ValueError, OSError):
pass
time.sleep(2)
return False
def service(*args):
subprocess.run(['systemctl', *args], check=True, timeout=60)
def units():
program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py')
return {
SERVICE: f"""[Unit]
Description=Rust Discovery Linux agent
Wants=network-online.target
After=network-online.target time-sync.target
[Service]
User=rmm-discovery
Group=rmm-discovery
StateDirectory=rmm-discovery
StateDirectoryMode=0700
UMask=0077
ExecStart={program} run-agent
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
[Install]
WantedBy=multi-user.target
""",
'rmm-discovery-update.service': f"""[Unit]
Description=Check and activate a signed Rust Discovery agent release
After=network-online.target
[Service]
Type=oneshot
ExecStart={program} update
UMask=0077
""",
TIMER: """[Unit]
Description=Periodic Rust Discovery agent release check
[Timer]
OnBootSec=1min
OnUnitActiveSec=5min
RandomizedDelaySec=20
[Install]
WantedBy=timers.target
""",
}
def enable():
for name, data in units().items():
path = UNIT_DIR / name
if path.exists():
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
else:
save(path, data.encode())
service('daemon-reload')
service('enable', '--now', SERVICE, TIMER)
def install(base, token_file):
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
base = origin(base)
if ROOT.exists():
config = read(ROOT / 'config.json')
require(config['bootstrap'] == base and (ROOT / 'current/manifest.json').is_file(),
'existing installation differs')
enable()
return
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
'existing device installation requires migration')
token = Path(token_file).read_text().strip() if token_file else getpass.getpass('Einmalcode: ').strip()
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
try:
account = pwd.getpwnam('rmm-discovery')
except KeyError:
subprocess.run(['useradd', '--system', '--user-group', '--no-create-home', '--shell', '/usr/sbin/nologin',
'rmm-discovery'], check=True)
account = pwd.getpwnam('rmm-discovery')
require(account.pw_uid != 0 and account.pw_gid != 0, 'dedicated unprivileged service account required')
with tempfile.TemporaryDirectory(prefix='.rmm-', dir=ROOT.parent) as work:
staging = Path(work) / 'installation'
staging.mkdir()
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, staging / 'bootstrap.json')
doc = read(staging / 'bootstrap.json')
require(doc['schema_version'] == 1, 'unknown bootstrap profile')
save(staging / 'keyring.json', doc['keyring'])
save(staging / 'gateway-ca.pem', doc['ca_pem'].encode())
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
'tenant': canonical_id(doc['tenant_id'])})
updater = staging / 'updater'
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM, updater, doc['updater'])
updater.chmod(0o755)
releases = staging / 'releases'
releases.mkdir()
folder = releases / canonical_id(doc['manifest']['release_id'])
folder.mkdir()
manifest = pair(folder, doc, (base, token), updater)
link(staging, manifest['release_id'])
save(staging / 'lifecycle.py', Path(__file__).read_bytes())
save(staging / 'release.lock', b'')
save(staging / 'first.token', token.encode(), 0o440)
os.chown(staging / 'first.token', 0, account.pw_gid)
staging.chmod(0o755)
releases.chmod(0o755)
os.rename(staging, ROOT)
enable()
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
(ROOT / 'first.token').unlink(missing_ok=True)
def run_agent():
conf = read(ROOT / 'config.json')
url = urlsplit(conf['gateway'])
# Resolve again on each service start. TLS identity always uses the configured DNS name.
address = socket.getaddrinfo(url.hostname, url.port or 443, type=socket.SOCK_STREAM)[0][4][0]
if ':' in address:
address = '[' + address + ']'
os.environ.update(RMM_AGENT_STATE=str(STATE), RMM_CA_FILE=str(ROOT / 'gateway-ca.pem'),
RMM_CONNECT_ADDR=f'{address}:{url.port or 443}', RMM_SERVER_NAME=url.hostname,
RMM_TRANSPORT='https', RMM_ENROLLMENT_TOKEN_FILE=str(ROOT / 'first.token'),
RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1',
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
exe = str(ROOT / 'current/agent')
os.execv(exe, [exe])
def revert(intent):
# Persist failed sequence before restoring. An interruption re-enters recovery.
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
link(ROOT, intent['previous'])
service('restart', SERVICE)
(ROOT / 'pending.json').unlink()
raise RuntimeError('release activation unconfirmed; predecessor selected')
def update():
with (ROOT / 'release.lock').open('rb') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
pending = ROOT / 'pending.json'
if pending.exists():
revert(read(pending))
active = read(ROOT / 'current/manifest.json')
with tempfile.TemporaryDirectory(prefix='.incoming-', dir=ROOT / 'releases') as work:
staging = Path(work) / 'generation'
staging.mkdir()
remote(None, '/agent/v1/releases/current?platform=' + PLATFORM, staging / 'current.json')
response = read(staging / 'current.json')
if response['status'] == 'not_configured':
return
require(response['status'] == 'available', 'unexpected release status')
doc = response['release']
if doc['release_envelope'] == read(ROOT / 'current/envelope.json'):
return
floor = active['release_sequence']
if (ROOT / 'failed.json').exists():
floor = max(floor, read(ROOT / 'failed.json')['release_sequence'])
manifest = pair(staging, doc, None, ROOT / 'updater')
require(manifest['release_sequence'] > floor, 'release sequence previously activated or rejected')
# Guard only this device while it is being changed. A fresh offer may
# remain queued while the worker temporarily owns the admission lock.
if as_device('idle', stdout=subprocess.PIPE).stdout.strip() != b'idle':
return
previous_health = installed()
release = canonical_id(manifest['release_id'])
dest = ROOT / 'releases' / release
if dest.exists():
# A previous check may have staged this version before a crash.
require(read(dest / 'envelope.json') == doc['release_envelope'], 'release id conflict')
subprocess.run([ROOT / 'updater', '--verify-bootstrap', ROOT / 'keyring.json', dest / 'envelope.json',
dest / 'agent', dest / 'helper'], stdout=subprocess.DEVNULL, check=True)
else:
(staging / 'current.json').unlink()
os.rename(staging, dest)
intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']}
save(pending, intent)
link(ROOT, release)
service('restart', SERVICE)
if not healthy(manifest['version'], previous_health['connection_generation']):
revert(intent)
pending.unlink()
(ROOT / 'first.token').unlink(missing_ok=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'fetch', 'idle'))
parser.add_argument('values', nargs='*')
parser.add_argument('--token-file')
args = parser.parse_args()
if args.action in ('install', 'update'):
require(os.geteuid() == 0, 'administrative installation required')
os.umask(0o022)
if args.action == 'install':
require(len(args.values) == 1, 'one HTTPS bootstrap origin required')
install(args.values[0], args.token_file)
elif args.action == 'update':
update()
elif args.action == 'run-agent':
run_agent()
elif args.action == 'fetch':
device_get(*args.values)
else:
device_idle()
if __name__ == '__main__':
main()
+88
View File
@@ -0,0 +1,88 @@
//! Fresh-device bootstrap. Public scripts contain no credentials. Downloads use
//! the tenant's one-time enrollment token until the final enrollment consumes it.
use super::*;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Config {
gateway_origin: String,
updater_sha256: String,
updater_bytes: u64,
}
fn config(platform: Platform) -> Result<Config, Error> {
let slot = match platform {
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
};
let path = std::env::var(slot).map_err(|_| fail("BOOTSTRAP_NOT_CONFIGURED"))?;
let config: Config = serde_json::from_slice(&protected_file(FsPath::new(&path), 8192)?)?;
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty()
|| url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|| url.path() != "/" || !rmm_domain::agent_update::digest(&config.updater_sha256)
|| !(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&config.updater_bytes) {
return Err(fail("BOOTSTRAP_CONFIGURATION_INVALID"));
}
Ok(config)
}
fn private_json(body: Value) -> Response {
([("cache-control", "private, no-store")], Json(body)).into_response()
}
pub(super) async fn issue(State(s): State<crate::State>, headers: HeaderMap, Path(t): Path<Uuid>) -> Result<Response, Error> {
let p = s.auth.principal(&s, &headers, true).await.map_err(|status| Error(status, crate::auth::error_code(status)))?;
crate::jobs::scope(&p, t, true)?;
if p.session_hash.is_none() { return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED")); }
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
crate::permissions::require_principal(&mut tx, &p, "devices:enroll").await?;
let bootstrap_origin = std::env::var("RMM_BOOTSTRAP_ORIGIN").ok().map(|raw| {
let url = url::Url::parse(&raw).map_err(|_| invalid())?;
if url.scheme() != "https" || url.domain().is_none() || !url.username().is_empty() || url.password().is_some()
|| url.path() != "/" || url.query().is_some() || url.fragment().is_some() { return Err(invalid()); }
Ok(url.origin().ascii_serialization())
}).transpose()?;
let mut bytes = [0; 32];
openssl::rand::rand_bytes(&mut bytes).map_err(|_| fail("TOKEN_GENERATION_FAILED"))?;
let token = hex::encode(bytes);
let expires: chrono::DateTime<chrono::Utc> = sqlx::query_scalar("SELECT issue_enrollment_token($1)")
.bind(hash(token.as_bytes())).fetch_one(&mut *tx).await?;
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'enrollment_token_issued',$4,now())")
.bind(t).bind(Uuid::new_v4()).bind(p.name).bind(json!({"expires_at":expires})).execute(&mut *tx).await?;
tx.commit().await?;
Ok(private_json(json!({"token":token,"expires_at":expires,"bootstrap_origin":bootstrap_origin})))
}
async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
let denied = || Error(StatusCode::UNAUTHORIZED, "ENROLLMENT_TOKEN_REQUIRED");
let token = h.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Enrollment ")).filter(|v| rmm_domain::agent_update::digest(v)).ok_or_else(denied)?;
let t: Option<Uuid> = sqlx::query_scalar("SELECT bootstrap_enrollment_tenant($1)")
.bind(hash(token.as_bytes())).fetch_one(&s.pool).await?;
t.ok_or_else(denied)
}
pub(super) async fn current(State(s): State<crate::State>, headers: HeaderMap, Query(q): Query<Current>) -> Result<Response, Error> {
let t = token_tenant(&s, &headers).await?;
let c = config(q.platform)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
let release: Uuid = sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1")
.bind(platform_name(q.platform)).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
let (envelope, manifest) = checked_release(&mut tx, release).await?;
tx.commit().await?;
let ring: Value = serde_json::from_slice(&keyring_bytes(q.platform)?)?;
let ca = s.signer.as_ref().ok_or_else(missing)?.ca.to_pem().map_err(|_| invalid())?;
Ok(private_json(json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
"gateway_origin":c.gateway_origin,"ca_pem":String::from_utf8(ca).map_err(|_| invalid())?,
"keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}})))
}
pub(super) async fn artifact(State(s): State<crate::State>, headers: HeaderMap, Path((id, artifact)): Path<(Uuid,Uuid)>, Query(q): Query<Current>) -> Result<Response, Error> {
let tenant = token_tenant(&s, &headers).await?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let (_, manifest) = checked_release(&mut tx, id).await?;
if manifest.platform != q.platform { return Err(missing()); }
let d = manifest.artifacts.into_iter().find(|v| v.artifact_id == artifact).ok_or_else(missing)?;
tx.commit().await?;
verified_binary(tenant, d.sha256, d.bytes).await
}
pub(super) async fn updater(State(s): State<crate::State>, headers: HeaderMap, Query(q): Query<Current>) -> Result<Response, Error> {
let tenant = token_tenant(&s, &headers).await?;
let c = config(q.platform)?;
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
}