737 lines
31 KiB
Python
737 lines
31 KiB
Python
"""Bootstrap a Linux systemd client and maintain its signed release pair."""
|
|
import argparse
|
|
import contextlib
|
|
import datetime
|
|
import fcntl
|
|
import getpass
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import platform
|
|
import pwd
|
|
import re
|
|
import shutil
|
|
import socket
|
|
import sqlite3
|
|
import ssl
|
|
import stat
|
|
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'
|
|
HELPER = 'rmm-discovery-managed-script-helper.service'
|
|
HELPER_SOCKET = Path('/run/rmm-discovery-script-helper/control.sock')
|
|
OLD_HELPER_CONFIG = Path('/etc/rmm-discovery-managed-scripts')
|
|
MAX_BINARY = 256 * 1024 * 1024
|
|
UNIT_DIR = Path('/etc/systemd/system')
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise ValueError(message)
|
|
|
|
|
|
def release_platform():
|
|
machine = platform.machine()
|
|
require(platform.system() == 'Linux' and machine in ('x86_64', 'aarch64'),
|
|
'Linux x86-64 or ARM64 required')
|
|
return machine + '-unknown-linux-gnu'
|
|
|
|
|
|
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','unknown','awaiting_reboot'))"
|
|
).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'
|
|
target = release_platform()
|
|
require(manifest['platform'] == target, 'release architecture differs from this device')
|
|
suffix = '?platform=' + target 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, pin=None):
|
|
until = time.monotonic() + duration
|
|
started = time.time()
|
|
certificate_pointer = STATE / 'certificates/current.json'
|
|
while time.monotonic() < until:
|
|
# The agent writes this pointer after obtaining its first device certificate.
|
|
if not certificate_pointer.is_file():
|
|
time.sleep(2)
|
|
continue
|
|
try:
|
|
record = installed()
|
|
contact = record.get('last_contact_at')
|
|
if contact:
|
|
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
|
|
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
|
|
and record['connection_generation'] > baseline
|
|
and (pin is None or {'root:run_script', 'helper.policy.sha256:' + pin['policy_sha256'],
|
|
'helper.binary.sha256:' + pin['helper_binary_sha256']}.issubset(record['capabilities']))
|
|
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
|
|
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 active_folder():
|
|
release = canonical_id(read(ROOT / 'current/manifest.json')['release_id'])
|
|
folder = ROOT / 'releases' / release
|
|
require((ROOT / 'current').resolve(strict=True) == folder and folder.resolve() == folder,
|
|
'unexpected active generation path')
|
|
return folder
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def account_file(path, uid):
|
|
# Open only a checked inode a second time for TLS. No privileged open of a
|
|
# device or FIFO, and no path re-resolution after validation.
|
|
fd = os.open(path, os.O_PATH | os.O_NOFOLLOW)
|
|
try:
|
|
info = os.fstat(fd)
|
|
require(stat.S_ISREG(info.st_mode) and info.st_uid == uid and info.st_nlink == 1
|
|
and info.st_mode & 0o077 == 0 and 0 < info.st_size <= 65536,
|
|
'device credential metadata differs')
|
|
yield Path('/proc/self/fd') / str(fd)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def script_binding(account):
|
|
# The root helper trusts only the signing key from the original HTTPS
|
|
# bootstrap and the binding returned by the authenticated device gateway.
|
|
boot = read(ROOT / 'bootstrap.json')
|
|
certs = STATE / 'certificates'
|
|
with account_file(certs / 'current.json', account.pw_uid) as selector:
|
|
version = canonical_id(read(selector)['version'])
|
|
creds = certs / 'versions' / version
|
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
context.load_verify_locations(cafile=str(ROOT / 'gateway-ca.pem'))
|
|
with (account_file(creds / 'device.pem', account.pw_uid) as cert,
|
|
account_file(creds / 'device.key', account.pw_uid) as key):
|
|
context.load_cert_chain(str(cert), str(key))
|
|
response = io.BytesIO()
|
|
conf = read(ROOT / 'config.json')
|
|
retrieve(conf['gateway'], '/agent/v1/releases/installed', response, context=context)
|
|
own = json.loads(response.getvalue())
|
|
public_key = boot.get('job_signing_public_key_hex')
|
|
if public_key is None:
|
|
trust = io.BytesIO()
|
|
retrieve(conf['gateway'], '/agent/v1/releases/device-trust', trust, context=context)
|
|
public_key = json.loads(trust.getvalue())['job_signing_public_key_hex']
|
|
require(re.fullmatch('[0-9a-f]{64}', public_key), 'invalid job signing key')
|
|
require(own['tenant_id'] == conf['tenant'] == boot['tenant_id'], 'device binding tenant mismatch')
|
|
binding = {field: canonical_id(own[field]) for field in ('tenant_id', 'asset_id', 'agent_id')}
|
|
for field in ('enrollment_generation', 'assignment_version'):
|
|
require(type(own[field]) is int and own[field] > 0, 'invalid device generation')
|
|
binding[field] = own[field]
|
|
binding['public_key_hex'] = public_key
|
|
return binding
|
|
|
|
|
|
def script_settings(binding, account, digest):
|
|
return dict(profile='full_maintenance_v1', binding=binding, agent_uid=account.pw_uid,
|
|
socket_gid=account.pw_gid, socket=str(HELPER_SOCKET), state='/var/lib/rmm-discovery-helper',
|
|
allowed_services=[], allow_reboot=False, allow_root_scripts=True,
|
|
allowed_script_profiles=['full_maintenance_v1'], helper_binary_sha256=digest)
|
|
|
|
|
|
def prepare_script_helper(folder, binding, account):
|
|
manifest = json.loads(subprocess.check_output([
|
|
ROOT / 'updater', '--verify-bootstrap', ROOT / 'keyring.json', folder / 'envelope.json',
|
|
folder / 'agent', folder / 'helper'], timeout=120))
|
|
require(manifest == read(folder / 'manifest.json') and manifest['release_id'] == folder.name,
|
|
'helper generation differs from signed release')
|
|
digest = next(a['sha256'] for a in manifest['artifacts'] if a['role'] == 'helper')
|
|
settings = script_settings(binding, account, digest)
|
|
config = folder / 'script-helper.json'
|
|
if config.exists():
|
|
require(read(config) == settings, 'installed helper binding changed')
|
|
else:
|
|
save(config, settings, 0o600)
|
|
raw = subprocess.check_output([folder / 'helper', '--inspect-full-maintenance-profile'],
|
|
env={'PATH': '/usr/bin:/bin', 'RMM_HELPER_CONFIG': str(config)}, timeout=30)
|
|
pin = json.loads(raw)
|
|
require(pin['helper_binary_sha256'] == digest and re.fullmatch('[0-9a-f]{64}', pin['policy_sha256']),
|
|
'helper pin differs from signed release')
|
|
save(folder / 'script-pin.json', raw)
|
|
return pin
|
|
|
|
|
|
def helper_unit(executable, config=None):
|
|
command = f'Environment=RMM_HELPER_CONFIG={config}\n' if config else ''
|
|
return f"""[Unit]
|
|
Description=Rust Discovery helper for approved root scripts
|
|
After=time-sync.target
|
|
|
|
[Service]
|
|
User=root
|
|
Group=rmm-discovery
|
|
StateDirectory=rmm-discovery-helper
|
|
StateDirectoryMode=0700
|
|
RuntimeDirectory=rmm-discovery-script-helper
|
|
RuntimeDirectoryMode=0750
|
|
UMask=0077
|
|
{command}ExecStart={executable}
|
|
Restart=on-failure
|
|
RestartSec=5
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
""".encode()
|
|
|
|
|
|
def helper_unit_files(binding, account):
|
|
unit = UNIT_DIR / HELPER
|
|
dropdir = UNIT_DIR / (SERVICE + '.d')
|
|
dropdir.mkdir(mode=0o755, exist_ok=True)
|
|
require(not dropdir.is_symlink() and not dropdir.stat().st_mode & 0o022, 'unsafe service drop-in directory')
|
|
drop = dropdir / '50-managed-scripts.conf'
|
|
order = f'[Unit]\nAfter={HELPER}\n'.encode()
|
|
old_order = (f'[Unit]\nWants={HELPER}\nAfter={HELPER}\n'
|
|
f'\n[Service]\nEnvironment=RMM_FULL_MAINTENANCE_HELPER_SOCKET={HELPER_SOCKET}\n'
|
|
f'Environment=RMM_FULL_MAINTENANCE_POLICY_FILE={OLD_HELPER_CONFIG}/agent-pin.json\n').encode()
|
|
changed = []
|
|
for path, desired in (
|
|
(unit, helper_unit(f'/usr/bin/python3 -I {ROOT}/lifecycle.py run-helper')),
|
|
(drop, order),
|
|
):
|
|
if path.is_symlink():
|
|
raise ValueError('unexpected systemd symlink: ' + str(path))
|
|
if path.exists():
|
|
current = path.read_bytes()
|
|
if current == desired:
|
|
continue
|
|
old = old_order
|
|
if path == unit:
|
|
exe = re.search(rb'^ExecStart=(.+)$', current, re.M)
|
|
require(exe is not None, 'unrecognized helper service')
|
|
candidate = Path(os.fsdecode(exe[1]))
|
|
require(candidate == ROOT / 'releases' / canonical_id(candidate.parent.name) / 'helper',
|
|
'unexpected legacy helper image')
|
|
private = OLD_HELPER_CONFIG / 'helper.json'
|
|
old = helper_unit(candidate, private)
|
|
settings = read(private)
|
|
require(settings == script_settings(binding, account, settings['helper_binary_sha256']),
|
|
'existing helper belongs to a different binding or profile')
|
|
require(current == old, 'unrecognized managed service file: ' + str(path))
|
|
changed.append((path, desired))
|
|
return changed
|
|
|
|
|
|
def start_pair():
|
|
service('start', HELPER)
|
|
until = time.monotonic() + 15
|
|
while not HELPER_SOCKET.is_socket():
|
|
require(time.monotonic() < until, 'script helper socket unavailable')
|
|
time.sleep(.2)
|
|
service('start', SERVICE)
|
|
|
|
|
|
def helper_state():
|
|
probe = subprocess.run(['systemctl', 'is-enabled', HELPER], stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL, text=True, timeout=10)
|
|
return probe.stdout.strip()
|
|
|
|
|
|
def provision_scripts(enable_admin_scripts):
|
|
with (ROOT / 'release.lock').open('rb') as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
pending = ROOT / 'pending.json'
|
|
if pending.exists():
|
|
revert(read(pending))
|
|
folder = active_folder()
|
|
intent = ROOT / 'script-helper-installing.json'
|
|
state = helper_state()
|
|
known = (UNIT_DIR / HELPER).exists() or OLD_HELPER_CONFIG.exists() or (folder / 'script-helper.json').exists()
|
|
if state != 'enabled':
|
|
new = enable_admin_scripts and not known and state in ('', 'not-found')
|
|
resume = (enable_admin_scripts and intent.is_file() and read(intent) == folder.name
|
|
and state in ('', 'not-found', 'disabled'))
|
|
if not (new or resume):
|
|
print('Keeping the local script helper activation policy: ' + (state or 'not installed'), file=sys.stderr)
|
|
return
|
|
else:
|
|
require((UNIT_DIR / HELPER).is_file(), 'refusing to replace an externally managed helper unit')
|
|
require(as_device('idle', stdout=subprocess.PIPE).stdout.strip() == b'idle', 'active job prevents helper switch')
|
|
account = pwd.getpwnam('rmm-discovery')
|
|
require(account.pw_uid > 0 and account.pw_gid > 0, 'dedicated service account required')
|
|
binding = script_binding(account)
|
|
changed = helper_unit_files(binding, account)
|
|
if state != 'enabled':
|
|
save(intent, folder.name)
|
|
pin = prepare_script_helper(folder, binding, account)
|
|
observed = installed()
|
|
if (not changed and 'root:run_script' in observed['capabilities']
|
|
and 'helper.binary.sha256:' + pin['helper_binary_sha256'] in observed['capabilities']
|
|
and 'helper.policy.sha256:' + pin['policy_sha256'] in observed['capabilities']):
|
|
intent.unlink(missing_ok=True)
|
|
return
|
|
service('stop', SERVICE)
|
|
if (UNIT_DIR / HELPER).exists():
|
|
service('stop', HELPER)
|
|
for path, raw in changed:
|
|
save(path, raw)
|
|
service('daemon-reload')
|
|
service('enable', HELPER)
|
|
start_pair()
|
|
require(healthy(read(folder / 'manifest.json')['version'], observed['connection_generation'], pin=pin),
|
|
'device has not confirmed the script helper')
|
|
intent.unlink(missing_ok=True)
|
|
|
|
|
|
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 provision_serial_credential():
|
|
# DMI serial files usually require root. Pass this one value to the agent
|
|
# through systemd's read-only per-service credentials directory.
|
|
source = Path('/sys/class/dmi/id/product_serial')
|
|
try:
|
|
with source.open('rb') as stream:
|
|
serial = stream.read(256).strip()
|
|
except OSError:
|
|
return
|
|
if not serial or len(serial) >= 255:
|
|
return
|
|
target = ROOT / 'bios-serial'
|
|
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
|
|
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
|
|
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
|
|
if dropin.exists() or dropin.is_symlink():
|
|
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
|
|
else:
|
|
dropin.parent.mkdir(mode=0o755, exist_ok=True)
|
|
save(target, serial, 0o600)
|
|
if not dropin.exists():
|
|
save(dropin, content)
|
|
|
|
|
|
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())
|
|
provision_serial_credential()
|
|
service('daemon-reload')
|
|
service('enable', '--now', SERVICE)
|
|
|
|
|
|
def enrollment_token(path):
|
|
token = Path(path).read_text().strip() if path else getpass.getpass('Einmalcode: ').strip()
|
|
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
|
|
return token
|
|
|
|
|
|
def save_token(base, token, gid):
|
|
path = base / 'first.token'
|
|
save(path, token.encode(), 0o440)
|
|
os.chown(path, 0, gid)
|
|
|
|
|
|
def install(base, token_file, enable_admin_scripts=False):
|
|
target = release_platform()
|
|
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')
|
|
if not (STATE / 'identity.json').is_file():
|
|
token = enrollment_token(token_file)
|
|
with tempfile.TemporaryDirectory() as work:
|
|
metadata = Path(work) / 'bootstrap.json'
|
|
remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, metadata)
|
|
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
|
|
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
|
|
# An operator rerunning the HTTPS installer can update the lifecycle
|
|
# harness without replacing the device identity or its stable verifier.
|
|
with (ROOT / 'release.lock').open('rb') as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
harness = ROOT / 'lifecycle.py'
|
|
current = Path(__file__).read_bytes()
|
|
if harness.read_bytes() != current:
|
|
save(harness, current)
|
|
pending = ROOT / 'pending.json'
|
|
if pending.exists():
|
|
revert(read(pending), report_failure=False)
|
|
enable()
|
|
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
|
|
provision_scripts(enable_admin_scripts)
|
|
service('enable', '--now', TIMER)
|
|
(ROOT / 'first.token').unlink(missing_ok=True)
|
|
return
|
|
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
|
|
'existing device installation requires migration')
|
|
token = enrollment_token(token_file)
|
|
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=' + target, 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=' + target + '&sha256=' + doc['updater']['sha256'], 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_token(staging, token, account.pw_gid)
|
|
staging.chmod(0o755)
|
|
releases.chmod(0o755)
|
|
os.rename(staging, ROOT)
|
|
enable()
|
|
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
|
|
provision_scripts(enable_admin_scripts)
|
|
# OnBootSec may already be in the past on a running machine. The first
|
|
# timer check can run immediately once the device has reported its platform.
|
|
service('enable', '--now', TIMER)
|
|
(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'])
|
|
folder = active_folder()
|
|
os.environ.pop('RMM_SCRIPT_HELPER_RELEASE', None)
|
|
if (folder / 'script-pin.json').is_file() and helper_state() in ('enabled', 'enabled-runtime'):
|
|
pins = {'RMM_FULL_MAINTENANCE_HELPER_SOCKET': str(HELPER_SOCKET),
|
|
'RMM_FULL_MAINTENANCE_POLICY_FILE': str(folder / 'script-pin.json')}
|
|
if all(os.environ.get(name, value) == value for name, value in pins.items()):
|
|
os.environ.update(pins, RMM_SCRIPT_HELPER_RELEASE=folder.name)
|
|
exe = str(folder / 'agent')
|
|
os.execv(exe, [exe])
|
|
|
|
|
|
def revert(intent, report_failure=True):
|
|
# Persist failed sequence before restoring. An interruption re-enters recovery.
|
|
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
|
|
enabled = intent.get('script_helper') and helper_state() in ('enabled', 'enabled-runtime')
|
|
if intent.get('script_helper'):
|
|
service('stop', SERVICE, HELPER)
|
|
link(ROOT, intent['previous'])
|
|
if enabled:
|
|
start_pair()
|
|
previous = active_folder()
|
|
require(healthy(read(previous / 'manifest.json')['version'], 0, pin=read(previous / 'script-pin.json')),
|
|
'predecessor has not yet confirmed the previous script helper')
|
|
else:
|
|
service('restart', SERVICE)
|
|
(ROOT / 'pending.json').unlink()
|
|
if report_failure:
|
|
raise RuntimeError('release activation unconfirmed; predecessor selected')
|
|
|
|
|
|
def update():
|
|
target = release_platform()
|
|
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=' + target, 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']}
|
|
active_config = active_folder() / 'script-helper.json'
|
|
pin = None
|
|
if active_config.exists() and helper_state() in ('enabled', 'enabled-runtime'):
|
|
settings = read(active_config)
|
|
account = pwd.getpwnam('rmm-discovery')
|
|
active_hash = next(a['sha256'] for a in active['artifacts'] if a['role'] == 'helper')
|
|
require(settings == script_settings(settings['binding'], account, active_hash),
|
|
'existing script helper policy changed')
|
|
pin = prepare_script_helper(dest, settings['binding'], account)
|
|
intent['script_helper'] = True
|
|
save(pending, intent)
|
|
try:
|
|
if pin:
|
|
service('stop', SERVICE, HELPER)
|
|
link(ROOT, release)
|
|
if pin:
|
|
start_pair()
|
|
else:
|
|
service('restart', SERVICE)
|
|
except (OSError, ValueError, subprocess.SubprocessError):
|
|
revert(intent)
|
|
if not healthy(manifest['version'], previous_health['connection_generation'], pin=pin):
|
|
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', 'run-helper', 'fetch', 'idle'))
|
|
parser.add_argument('values', nargs='*')
|
|
parser.add_argument('--token-file')
|
|
parser.add_argument('--enable-admin-scripts', action='store_true',
|
|
help='enable this enrolled device to run individually approved root scripts')
|
|
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, args.enable_admin_scripts)
|
|
elif args.action == 'update':
|
|
update()
|
|
elif args.action == 'run-helper':
|
|
require(os.geteuid() == 0, 'privileged script helper service required')
|
|
folder = active_folder()
|
|
os.environ.setdefault('RMM_HELPER_CONFIG', str(folder / 'script-helper.json'))
|
|
os.execv(folder / 'helper', [str(folder / 'helper')])
|
|
elif args.action == 'run-agent':
|
|
run_agent()
|
|
elif args.action == 'fetch':
|
|
device_get(*args.values)
|
|
else:
|
|
device_idle()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|