Add fresh device trust, installer recovery and scoped patch runtime
This commit is contained in:
@@ -176,14 +176,16 @@ def installed():
|
||||
|
||||
def healthy(version, baseline, duration=90):
|
||||
until = time.monotonic() + duration
|
||||
started = time.time()
|
||||
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):
|
||||
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
|
||||
and record['connection_generation'] > baseline
|
||||
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
|
||||
return True
|
||||
except (subprocess.SubprocessError, ValueError, OSError):
|
||||
pass
|
||||
@@ -249,6 +251,18 @@ def enable():
|
||||
service('enable', '--now', SERVICE, TIMER)
|
||||
|
||||
|
||||
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):
|
||||
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
|
||||
base = origin(base)
|
||||
@@ -256,12 +270,20 @@ def install(base, token_file):
|
||||
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=' + PLATFORM, metadata)
|
||||
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
|
||||
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
|
||||
enable()
|
||||
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
|
||||
(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 = 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')
|
||||
token = enrollment_token(token_file)
|
||||
try:
|
||||
account = pwd.getpwnam('rmm-discovery')
|
||||
except KeyError:
|
||||
@@ -290,8 +312,7 @@ def install(base, token_file):
|
||||
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)
|
||||
save_token(staging, token, account.pw_gid)
|
||||
staging.chmod(0o755)
|
||||
releases.chmod(0o755)
|
||||
os.rename(staging, ROOT)
|
||||
|
||||
@@ -106,6 +106,37 @@ async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
|
||||
.await?;
|
||||
t.ok_or_else(denied)
|
||||
}
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TimeTrust {
|
||||
key_generation: u64,
|
||||
server_instance: Uuid,
|
||||
public_keys_hex: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
fn device_trust_data(s: &crate::State) -> Result<Value, Error> {
|
||||
let job_public = hex::encode(s.job_signer.public_key()?);
|
||||
let path = std::env::var_os("RMM_AGENT_BOOTSTRAP_WINDOWS_FILE")
|
||||
.and_then(|slot| FsPath::new(&slot).parent().map(|p| p.join("windows-time-trust.json")));
|
||||
let trust = match path {
|
||||
Some(path) if path.try_exists().map_err(|_| fail("BOOTSTRAP_TIME_TRUST_INVALID"))? => {
|
||||
let trust: TimeTrust = serde_json::from_slice(&protected_file(&path, 8192)?)?;
|
||||
if trust.key_generation == 0 || trust.server_instance.is_nil()
|
||||
|| !(1..=8).contains(&trust.public_keys_hex.len())
|
||||
|| !trust.public_keys_hex.iter().all(|(id,key)| !id.is_empty() && id.len() <= 64
|
||||
&& id.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
|
||||
&& rmm_domain::agent_update::digest(key) && key != &job_public) {
|
||||
return Err(fail("BOOTSTRAP_TIME_TRUST_INVALID"));
|
||||
}
|
||||
Some(trust)
|
||||
}
|
||||
_ => None
|
||||
};
|
||||
Ok(json!({"job_signing_public_key_hex":job_public,"windows_time_trust":trust}))
|
||||
}
|
||||
pub(super) async fn device_trust(State(s): State<crate::State>, Extension(peer): Extension<crate::Peer>, headers: HeaderMap) -> Result<Response, Error> {
|
||||
device(&s, peer, &headers).await?;
|
||||
Ok(private_json(device_trust_data(&s)?))
|
||||
}
|
||||
pub(super) async fn current(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
@@ -126,8 +157,9 @@ pub(super) async fn current(
|
||||
.ca
|
||||
.to_pem()
|
||||
.map_err(|_| invalid())?;
|
||||
let trust = device_trust_data(&s)?;
|
||||
Ok(private_json(
|
||||
json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
|
||||
json!({"job_signing_public_key_hex":trust["job_signing_public_key_hex"],"windows_time_trust":trust["windows_time_trust"],"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}}),
|
||||
))
|
||||
|
||||
Reference in New Issue
Block a user