Integrate signed agent catalog, tenant enrollment and HTTPS installers
This commit is contained in:
@@ -63,7 +63,12 @@ pub async fn open(
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
control_lock(&mut tx, tenant, agent).await?;
|
||||
let generation:i64=sqlx::query_scalar("UPDATE agent_installations SET connection_generation=connection_generation+1,capabilities=$2,transport=$3,connection_boot_id=$4,restore_blocked=restore_blocked OR $5<=last_sequence,sequence_regressed=sequence_regressed OR $5<=last_sequence,sync_required=$6,sync_ready=NOT $6,helper_sync_ready=false,last_sequence=$5 WHERE agent_id=$1 AND revoked_at IS NULL RETURNING connection_generation").bind(agent).bind(serde_json::to_value(&client.capabilities)?).bind(transport).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(client.capabilities.iter().any(|c|c=="rmm.sync.v1")).fetch_one(&mut *tx).await?;
|
||||
anyhow::ensure!(
|
||||
client.agent_version.len() <= 64
|
||||
&& client.agent_version.bytes().all(|b| b.is_ascii_graphic()),
|
||||
"invalid agent version"
|
||||
);
|
||||
let generation:i64=sqlx::query_scalar("UPDATE agent_installations SET connection_generation=connection_generation+1,capabilities=$2,transport=$3,connection_boot_id=$4,restore_blocked=restore_blocked OR $5<=last_sequence,sequence_regressed=sequence_regressed OR $5<=last_sequence,sync_required=$6,sync_ready=NOT $6,helper_sync_ready=false,last_sequence=$5,reported_agent_version=NULLIF($7,'') WHERE agent_id=$1 AND revoked_at IS NULL RETURNING connection_generation").bind(agent).bind(serde_json::to_value(&client.capabilities)?).bind(transport).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(client.capabilities.iter().any(|c|c=="rmm.sync.v1")).bind(&client.agent_version).fetch_one(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(reply(
|
||||
e,
|
||||
|
||||
@@ -419,7 +419,7 @@ async fn issue(
|
||||
)?;
|
||||
let scope = match action.manifest().map_err(|_| denied())?.platform {
|
||||
update::Platform::LinuxX64 => "linux.base",
|
||||
update::Platform::WindowsX64 => "windows.base",
|
||||
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
|
||||
};
|
||||
// Health requires a fresh real base inventory of the restarted platform;
|
||||
// a not_configured update observation cannot stand in for that evidence.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Tenant release publication and update-only bounded object transport.
|
||||
//! Catalog metadata and passive checks never create/approve an execution job.
|
||||
#[path = "bootstrap/mod.rs"]
|
||||
mod bootstrap;
|
||||
use crate::{
|
||||
jobs::Error,
|
||||
update_artifact_store::{MAX_CHUNK_BYTES, UpdateArtifacts},
|
||||
@@ -42,6 +44,7 @@ pub fn platform_name(platform: Platform) -> &'static str {
|
||||
match platform {
|
||||
Platform::LinuxX64 => "x86_64-unknown-linux-gnu",
|
||||
Platform::WindowsX64 => "x86_64-pc-windows-msvc",
|
||||
Platform::WindowsGnuX64 => "x86_64-pc-windows-gnu",
|
||||
}
|
||||
}
|
||||
pub fn protected_file(path: &FsPath, maximum: u64) -> Result<Vec<u8>, Error> {
|
||||
@@ -122,9 +125,11 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
|
||||
}
|
||||
Ok(UpdateArtifacts::new(
|
||||
&std::env::var("RMM_PROFILE").unwrap_or_default(),
|
||||
path.parent()
|
||||
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?
|
||||
.join("agent-update-artifacts"),
|
||||
match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") {
|
||||
Some(value) if FsPath::new(&value).is_absolute() => value.into(),
|
||||
Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
|
||||
None => path.parent().ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?.join("agent-update-artifacts"),
|
||||
},
|
||||
metadata.uid(),
|
||||
)?)
|
||||
}
|
||||
@@ -132,6 +137,7 @@ fn verifier_platform(platform: Platform) -> rmm_updater::Platform {
|
||||
match platform {
|
||||
Platform::LinuxX64 => rmm_updater::Platform::LinuxX64,
|
||||
Platform::WindowsX64 => rmm_updater::Platform::WindowsX64,
|
||||
Platform::WindowsGnuX64 => rmm_updater::Platform::WindowsGnuX64,
|
||||
}
|
||||
}
|
||||
/// Network input can choose only one of two statically named protected
|
||||
@@ -143,6 +149,7 @@ fn keyring_path_with(
|
||||
let name = match platform {
|
||||
Platform::LinuxX64 => "RMM_AGENT_UPDATE_LINUX_KEYRING_FILE",
|
||||
Platform::WindowsX64 => "RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE",
|
||||
Platform::WindowsGnuX64 => "RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE",
|
||||
};
|
||||
if let Some(path) = lookup(name)? {
|
||||
if path.is_empty() || !FsPath::new(&path).is_absolute() {
|
||||
@@ -161,12 +168,10 @@ pub fn verify_envelope(
|
||||
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
|
||||
) -> Result<ReleaseManifest, Error> {
|
||||
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
|
||||
let path = keyring_path_with(platform, |name| match std::env::var(name) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
|
||||
})?;
|
||||
let raw = protected_file(&path, 16384)?;
|
||||
if platform == Platform::WindowsGnuX64 && std::env::var("RMM_PROFILE").as_deref() != Ok("development") {
|
||||
return Err(fail("AGENT_UPDATE_DEVELOPMENT_CHANNEL_REQUIRED"));
|
||||
}
|
||||
let raw = keyring_bytes(platform)?;
|
||||
verify_envelope_with_keyring(
|
||||
envelope,
|
||||
binding,
|
||||
@@ -177,6 +182,14 @@ pub fn verify_envelope(
|
||||
.map_err(|_| invalid())?,
|
||||
)
|
||||
}
|
||||
fn keyring_bytes(platform: Platform) -> Result<Vec<u8>, Error> {
|
||||
let path = keyring_path_with(platform, |name| match std::env::var(name) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
|
||||
})?;
|
||||
protected_file(&path, 16384)
|
||||
}
|
||||
fn verify_envelope_with_keyring(
|
||||
envelope: &ReleaseEnvelope,
|
||||
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
|
||||
@@ -242,6 +255,7 @@ fn verify_envelope_with_keyring(
|
||||
}
|
||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/api/v1/tenants/{tenant}/enrollment-tokens", post(bootstrap::issue))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/agent-releases",
|
||||
get(list).post(import),
|
||||
@@ -253,7 +267,20 @@ pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
}
|
||||
pub fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/install/linux.sh", get(|| async { ([("content-type", "text/x-shellscript")], concat!(include_str!("bootstrap/install.sh"),include_str!("bootstrap/lifecycle.py"),"
|
||||
RMM_BOOTSTRAP_PYTHON
|
||||
/usr/bin/python3 -I \"$file\" install \"$@\"
|
||||
")) }))
|
||||
.route("/install/windows.ps1", get(|| async { ([("content-type", "text/plain; charset=utf-8")], include_str!("bootstrap/install.ps1")) }))
|
||||
.route("/agent/v1/bootstrap/current", get(bootstrap::current))
|
||||
.route("/agent/v1/bootstrap/releases/{release}/artifacts/{artifact}", get(bootstrap::artifact))
|
||||
.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/{release}/artifacts/{artifact}",
|
||||
get(release_artifact),
|
||||
)
|
||||
.route("/agent/v1/update-artifacts/{artifact}", get(download))
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
@@ -412,12 +439,26 @@ pub async fn import(
|
||||
let sequence = i64::try_from(m.release_sequence).map_err(|_| invalid())?;
|
||||
resolve_artifacts(&mut tx, t, &m.artifacts).await?;
|
||||
let manifest_sha = hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes);
|
||||
sqlx::query("INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)")
|
||||
.bind(t).bind(m.release_id).bind(platform_name(m.platform)).bind(sequence).bind(&manifest_sha).bind(hash(&raw)).bind(raw)
|
||||
let inserted = sqlx::query("INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT DO NOTHING")
|
||||
.bind(t).bind(m.release_id).bind(platform_name(m.platform)).bind(sequence).bind(&manifest_sha).bind(hash(&raw)).bind(&raw)
|
||||
.bind(m.artifacts[0].artifact_id).bind(&m.artifacts[0].sha256).bind(m.artifacts[0].bytes as i64)
|
||||
.bind(m.artifacts[1].artifact_id).bind(&m.artifacts[1].sha256).bind(m.artifacts[1].bytes as i64).execute(&mut *tx).await?;
|
||||
if inserted.rows_affected() == 0 {
|
||||
let stored: Option<Vec<u8>> = sqlx::query_scalar(
|
||||
"SELECT envelope FROM agent_update_releases WHERE release_id=$1 AND platform=$2 AND release_sequence=$3",
|
||||
)
|
||||
.bind(m.release_id)
|
||||
.bind(platform_name(m.platform))
|
||||
.bind(sequence)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if stored.as_deref() != Some(raw.as_slice()) {
|
||||
return Err(fail("AGENT_UPDATE_RELEASE_CONFLICT"));
|
||||
}
|
||||
} else {
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'agent_update_release_imported',$4,now())").bind(t).bind(Uuid::new_v4()).bind(p.name)
|
||||
.bind(json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"testsimulation":p.testsimulation})).execute(&mut *tx).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(
|
||||
json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"release_envelope":envelope,"manifest":m}),
|
||||
@@ -496,6 +537,86 @@ async fn device(
|
||||
.await
|
||||
.map_err(|status| Error(status, "UNAUTHENTICATED"))
|
||||
}
|
||||
async fn installed(State(s): State<crate::State>, Extension(peer): Extension<crate::Peer>, headers: HeaderMap) -> Result<Response, Error> {
|
||||
let (tenant, agent) = device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let row = sqlx::query("SELECT reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(([("cache-control","private, no-store")], Json(json!({"agent_id":agent,
|
||||
"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||
"connection_generation":row.get::<i64,_>("connection_generation"),
|
||||
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")}))).into_response())
|
||||
}
|
||||
|
||||
async fn check_device_platform(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
agent: Uuid,
|
||||
platform: Platform,
|
||||
) -> Result<(), Error> {
|
||||
let caps: Value = sqlx::query_scalar(
|
||||
"SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
let caps: Vec<String> = serde_json::from_value(caps)?;
|
||||
let expected = match platform {
|
||||
Platform::LinuxX64 => "linux.base/1",
|
||||
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => return Err(missing()),
|
||||
Platform::WindowsX64 => "windows.base/1",
|
||||
Platform::WindowsGnuX64 => "agent.release.windows.gnu/1",
|
||||
};
|
||||
if !caps.iter().any(|c| c == expected) {
|
||||
return Err(missing());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A published release grants access to its two fixed binaries for authenticated
|
||||
/// devices of its own tenant and platform. A catalog write first verifies both
|
||||
/// objects. Fetching rechecks the live signing trust and the actual object.
|
||||
async fn release_artifact(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
Path((release, artifact)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let (_, manifest) = checked_release(&mut tx, release).await?;
|
||||
check_device_platform(&mut tx, agent, manifest.platform).await?;
|
||||
let descriptor = manifest.artifacts.into_iter()
|
||||
.find(|entry| entry.artifact_id == artifact).ok_or_else(missing)?;
|
||||
tx.commit().await?;
|
||||
verified_binary(tenant, descriptor.sha256, descriptor.bytes).await
|
||||
}
|
||||
|
||||
async fn verified_binary(tenant: Uuid, sha256: String, size: u64) -> Result<Response, Error> {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let digest = sha256.clone();
|
||||
let file = tokio::task::spawn_blocking(move || -> Result<std::fs::File, Error> {
|
||||
Ok(store()?.verified_file(tenant, &digest, size)?)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| fail("AGENT_UPDATE_ARTIFACT_UNAVAILABLE"))??;
|
||||
let reader = tokio::fs::File::from_std(file).take(size);
|
||||
let stream = futures_util::stream::try_unfold(reader, |mut reader| async move {
|
||||
let mut chunk = vec![0; 64 * 1024];
|
||||
let count = reader.read(&mut chunk).await?;
|
||||
chunk.truncate(count);
|
||||
Ok::<_, std::io::Error>((count != 0).then_some((chunk, reader)))
|
||||
});
|
||||
let mut response = Response::new(Body::from_stream(stream));
|
||||
let headers = response.headers_mut();
|
||||
headers.insert("content-type", HeaderValue::from_static("application/octet-stream"));
|
||||
headers.insert("content-length", HeaderValue::from(size));
|
||||
headers.insert("content-disposition", HeaderValue::from_static("attachment"));
|
||||
headers.insert("x-content-type-options", HeaderValue::from_static("nosniff"));
|
||||
headers.insert("cache-control", HeaderValue::from_static("private, no-store"));
|
||||
headers.insert("x-artifact-sha256", HeaderValue::from_str(&sha256).map_err(|_| invalid())?);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn current(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
@@ -504,20 +625,7 @@ async fn current(
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (tenant, agent) = device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let caps: Value = sqlx::query_scalar(
|
||||
"SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let caps: Vec<String> = serde_json::from_value(caps)?;
|
||||
let expected = match q.platform {
|
||||
Platform::LinuxX64 => "linux.base/1",
|
||||
Platform::WindowsX64 => "windows.base/1",
|
||||
};
|
||||
if !caps.iter().any(|c| c == expected) {
|
||||
return Err(missing());
|
||||
}
|
||||
check_device_platform(&mut tx, agent, q.platform).await?;
|
||||
let ids:Vec<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_all(&mut *tx).await?;
|
||||
let release = if let Some(id) = ids.first() {
|
||||
let (envelope, manifest) = checked_release(&mut tx, *id).await?;
|
||||
|
||||
@@ -128,7 +128,7 @@ async fn device_list(
|
||||
.map_err(|e| e.0)?;
|
||||
let mut page =
|
||||
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base') AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.reported_agent_version,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base') AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
.bind(asset)
|
||||
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
||||
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
@@ -141,7 +141,7 @@ async fn device_list(
|
||||
let revoked: Option<chrono::DateTime<Utc>> = r.get("revoked_at");
|
||||
let age = last.map(|t| (Utc::now()-t).num_seconds());
|
||||
let presence = if revoked.is_some() { "revoked" } else { match age { None=>"never_seen",Some(n) if n<90=>"online",Some(n) if n<180=>"stale",_=>"unreachable" } };
|
||||
json!({"agent_id":r.get::<Uuid,_>("agent_id"),"asset_id":r.get::<Uuid,_>("asset_id"),"certificate_sha256":r.get::<String,_>("certificate_sha256"),"last_authenticated_certificate_sha256":r.get::<Option<String>,_>("last_authenticated_certificate_sha256"),"last_authenticated_at":r.get::<Option<chrono::DateTime<Utc>>,_>("last_authenticated_at"),"capabilities":r.get::<Value,_>("capabilities"),"enrollment_generation":r.get::<i64,_>("enrollment_generation"),"assignment_version":r.get::<i64,_>("assignment_version"),"presence":presence,"last_contact_at":last,"inventory":r.get::<Option<Value>,_>("data"),"observed_at":r.get::<Option<chrono::DateTime<Utc>>,_>("observed_at"),"received_at":r.get::<Option<chrono::DateTime<Utc>>,_>("received_at"),"source_id":r.get::<Option<String>,_>("source_id"),"quality":if r.get::<Option<Value>,_>("data").is_some(){"valid"}else{"unknown"},"completeness":"partial","health":"unknown"})
|
||||
json!({"agent_id":r.get::<Uuid,_>("agent_id"),"asset_id":r.get::<Uuid,_>("asset_id"),"agent_version":r.get::<Option<String>,_>("reported_agent_version"),"certificate_sha256":r.get::<String,_>("certificate_sha256"),"last_authenticated_certificate_sha256":r.get::<Option<String>,_>("last_authenticated_certificate_sha256"),"last_authenticated_at":r.get::<Option<chrono::DateTime<Utc>>,_>("last_authenticated_at"),"capabilities":r.get::<Value,_>("capabilities"),"enrollment_generation":r.get::<i64,_>("enrollment_generation"),"assignment_version":r.get::<i64,_>("assignment_version"),"presence":presence,"last_contact_at":last,"inventory":r.get::<Option<Value>,_>("data"),"observed_at":r.get::<Option<chrono::DateTime<Utc>>,_>("observed_at"),"received_at":r.get::<Option<chrono::DateTime<Utc>>,_>("received_at"),"source_id":r.get::<Option<String>,_>("source_id"),"quality":if r.get::<Option<Value>,_>("data").is_some(){"valid"}else{"unknown"},"completeness":"partial","health":"unknown"})
|
||||
}).collect::<Vec<_>>();
|
||||
let next = if truncated {
|
||||
Some(page.next(state, rows[usize::from(page.limit) - 1].get("agent_id"))?)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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()
|
||||
@@ -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
|
||||
}
|
||||
+14
-11
@@ -1091,7 +1091,11 @@ pub async fn operation(
|
||||
"needs_attention"
|
||||
} else if c("succeeded") == n {
|
||||
"succeeded"
|
||||
} else if c("succeeded") + c("failed") + c("cancelled") + c("expired") + c("closed_unknown")
|
||||
} else if c("succeeded")
|
||||
+ c("failed")
|
||||
+ c("cancelled")
|
||||
+ c("expired")
|
||||
+ c("closed_unknown")
|
||||
== n
|
||||
{
|
||||
if c("succeeded") > 0 {
|
||||
@@ -1242,12 +1246,13 @@ pub async fn close_unknown(
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "plans:approve").await?;
|
||||
let row =
|
||||
sqlx::query("SELECT attempt_id,state,revision,result FROM jobs WHERE job_id=$1 FOR UPDATE")
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(missing)?;
|
||||
let row = sqlx::query(
|
||||
"SELECT attempt_id,state,revision,result FROM jobs WHERE job_id=$1 FOR UPDATE",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(missing)?;
|
||||
if row.get::<Uuid, _>("attempt_id") != input.attempt_id
|
||||
|| row.get::<i64, _>("revision") != input.revision
|
||||
{
|
||||
@@ -1287,11 +1292,9 @@ pub async fn close_unknown(
|
||||
.bind(tenant)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(&p.name)
|
||||
.bind(
|
||||
json!({"job_id":id,"attempt_id":input.attempt_id,"grant_id":grant,"closure_id":closure,
|
||||
.bind(json!({"job_id":id,"attempt_id":input.attempt_id,"grant_id":grant,"closure_id":closure,
|
||||
"original_revision":input.revision,"reason":input.reason,"session_hash":session,
|
||||
"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}),
|
||||
)
|
||||
"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}))
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -98,7 +98,7 @@ impl UpdateArtifacts {
|
||||
hasher: Sha256::new(),
|
||||
})
|
||||
}
|
||||
fn verified_file(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<File> {
|
||||
pub(crate) fn verified_file(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<File> {
|
||||
ensure!(descriptor(hash, bytes), "bounded update object descriptor");
|
||||
let parent = self.parent(tenant)?;
|
||||
let mut file = OpenOptions::new()
|
||||
|
||||
@@ -516,5 +516,5 @@ pub(super) async fn test_fixed_echo(
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
}
|
||||
crate::windows_echo_completion::test_completed_echo(admin, s, &p, &w).await;
|
||||
crate::windows_echo_completion::test_completed_echo(admin,s,&p,&w).await;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user