Add fresh device trust, installer recovery and scoped patch runtime
This commit is contained in:
@@ -308,6 +308,7 @@ RMM_BOOTSTRAP_PYTHON
|
||||
.route("/agent/v1/bootstrap/updater", get(bootstrap::updater))
|
||||
.route("/agent/v1/releases/current", get(current))
|
||||
.route("/agent/v1/releases/installed", get(installed))
|
||||
.route("/agent/v1/releases/device-trust", get(bootstrap::device_trust))
|
||||
.route(
|
||||
"/agent/v1/releases/{release}/artifacts/{artifact}",
|
||||
get(release_artifact),
|
||||
|
||||
@@ -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}}),
|
||||
))
|
||||
|
||||
@@ -723,6 +723,7 @@ pub(crate) async fn plan_resolved(
|
||||
artifact_references,
|
||||
script_revision,
|
||||
};
|
||||
crate::script_library::validate_plan_bindings(&payload)?;
|
||||
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
|
||||
crate::agent_updates::validate_plan_bindings(&payload)?;
|
||||
let bytes = encode(&payload)?;
|
||||
@@ -759,6 +760,7 @@ async fn load_plan(
|
||||
Ok((serde_json::from_slice(&bytes)?, h, bytes))
|
||||
}
|
||||
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
|
||||
crate::script_library::validate_plan_bindings(plan)?;
|
||||
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
|
||||
crate::agent_updates::validate_plan_bindings(plan)?;
|
||||
policy(tx).await?;
|
||||
|
||||
@@ -186,6 +186,27 @@ pub async fn plan(
|
||||
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
|
||||
}
|
||||
|
||||
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
|
||||
let Some(reference) = &plan.script_revision else {
|
||||
if plan.jobs.iter().any(|job| {
|
||||
job.payload.max_runtime_seconds > 120 && job.payload.action.is_windows_update_template()
|
||||
}) {
|
||||
return Err(Error(
|
||||
StatusCode::CONFLICT,
|
||||
"WINDOWS_UPDATE_REVISION_REQUIRED",
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
if reference.revision_id.is_nil() || reference.version < 1 || reference.name.is_empty() || plan.jobs.is_empty()
|
||||
|| plan.jobs.iter().any(|job| !matches!(&job.payload.action,
|
||||
Action::RunScript { script_utf8, .. } if hash(script_utf8.as_bytes()) == reference.script_sha256
|
||||
&& job.script_sha256.as_ref() == Some(&reference.script_sha256))) {
|
||||
return Err(Error(StatusCode::CONFLICT, "SCRIPT_REVISION_BINDING_MISMATCH"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
r.route(
|
||||
"/api/v1/tenants/{tenant}/script-revisions",
|
||||
@@ -247,7 +268,13 @@ pub(crate) mod tests {
|
||||
template["script_utf8"].as_str().unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(native.full_maintenance());
|
||||
assert!(native.is_windows_update_template());
|
||||
assert_eq!(
|
||||
template["script_sha256"],
|
||||
rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256
|
||||
);
|
||||
assert!(native.valid_job_limits(3600, 65536));
|
||||
assert!(!native.valid_job_limits(3601, 65536));
|
||||
|
||||
let v1 = Publish {
|
||||
name: "Agentversion".into(),
|
||||
@@ -335,6 +362,20 @@ pub(crate) mod tests {
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
let bound: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let mut extended = bound.clone();
|
||||
extended.jobs[0].payload.action = native;
|
||||
extended.jobs[0].payload.max_runtime_seconds = 3600;
|
||||
extended.jobs[0].script_sha256 =
|
||||
Some(rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256.into());
|
||||
assert_eq!(
|
||||
validate_plan_bindings(&extended).unwrap_err().1,
|
||||
"SCRIPT_REVISION_BINDING_MISMATCH"
|
||||
);
|
||||
extended.script_revision = None;
|
||||
assert_eq!(
|
||||
validate_plan_bindings(&extended).unwrap_err().1,
|
||||
"WINDOWS_UPDATE_REVISION_REQUIRED"
|
||||
);
|
||||
let reference = bound.script_revision.unwrap();
|
||||
assert_eq!(reference.revision_id, id);
|
||||
assert_eq!(reference.version, 1);
|
||||
|
||||
@@ -45,6 +45,8 @@ struct SystemScope {
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
#[serde(default)]
|
||||
windows_update_max_runtime_seconds: Option<u32>,
|
||||
#[serde(default, deserialize_with = "strict_optional_reboot")]
|
||||
allow_reboot: Option<bool>,
|
||||
}
|
||||
@@ -122,6 +124,10 @@ impl SystemScope {
|
||||
.allowed_script_profiles
|
||||
.as_deref()
|
||||
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& rmm_domain::jobs::valid_windows_update_limit(
|
||||
self.windows_update_max_runtime_seconds,
|
||||
self.allowed_script_profiles.as_deref(),
|
||||
)
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(
|
||||
@@ -154,7 +160,13 @@ impl SystemScope {
|
||||
"helper.binary.sha256:{}",
|
||||
self.helper_binary_sha256
|
||||
))
|
||||
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
|
||||
&& (1..=job.action.windows_system_runtime_limit(
|
||||
self.max_runtime_seconds,
|
||||
self.windows_update_max_runtime_seconds,
|
||||
))
|
||||
.contains(&job.max_runtime_seconds)
|
||||
&& (job.max_runtime_seconds <= 120
|
||||
|| has(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY))
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
&& match &job.action {
|
||||
Action::Reboot { .. } => {
|
||||
@@ -556,6 +568,32 @@ mod tests {
|
||||
policy.schema_version = 3;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
|
||||
let general = job.action.clone();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: Some(
|
||||
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
|
||||
),
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
caps.push("script.powershell.process_remote_signed/1".into());
|
||||
job.max_runtime_seconds = 3600;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].windows_update_max_runtime_seconds = Some(1800);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
|
||||
job.action = general;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
job.max_runtime_seconds = 30;
|
||||
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user