388 lines
12 KiB
Rust
388 lines
12 KiB
Rust
use std::{collections::BTreeMap, io::Read};
|
|
|
|
use anyhow::{Context, Result, bail, ensure};
|
|
use ed25519_dalek::{Signature, VerifyingKey};
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use uuid::Uuid;
|
|
|
|
pub const MAX_MANIFEST_BYTES: usize = 16 * 1024;
|
|
/// Verification limit for a FUTURE update-specific streaming transport.
|
|
/// The existing server artifact route only permits 256 KiB and is unchanged.
|
|
pub const MAX_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
|
|
pub const RELEASE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-release.v1\0";
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum Platform {
|
|
#[serde(rename = "x86_64-unknown-linux-gnu")]
|
|
LinuxX64,
|
|
#[serde(rename = "x86_64-pc-windows-msvc")]
|
|
WindowsX64,
|
|
#[serde(rename = "x86_64-pc-windows-gnu")]
|
|
WindowsGnuX64,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum ArtifactRole {
|
|
Agent,
|
|
Helper,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct ArtifactDescriptor {
|
|
pub role: ArtifactRole,
|
|
pub artifact_id: Uuid,
|
|
pub sha256: String,
|
|
pub bytes: u64,
|
|
}
|
|
|
|
/// Exact field order defines codec version 1; no maps or floating point fields.
|
|
/// These public types describe UNTRUSTED metadata, never update authority.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct ReleaseManifest {
|
|
pub schema_version: u32,
|
|
pub release_id: Uuid,
|
|
pub release_sequence: u64,
|
|
pub version: String,
|
|
pub platform: Platform,
|
|
pub published_at: u64,
|
|
pub expires_at: u64,
|
|
pub protocol_major: u32,
|
|
pub state_schema: u32,
|
|
pub minimum_updater_version: u32,
|
|
pub artifacts: [ArtifactDescriptor; 2],
|
|
}
|
|
|
|
/// Already-decoded, bounded transport input. No algorithm negotiation exists.
|
|
pub struct SignedRelease<'a> {
|
|
pub schema_version: u32,
|
|
pub key_id: &'a str,
|
|
pub payload_bytes: &'a [u8],
|
|
pub signature: &'a [u8],
|
|
}
|
|
|
|
/// Provisioned update trust, not a key returned by a manifest/job/server request.
|
|
/// Construction validates raw keys and IDs; it does not authenticate provisioning.
|
|
pub struct TrustedUpdateKey {
|
|
key: VerifyingKey,
|
|
key_id: String,
|
|
platform: Platform,
|
|
first_sequence: u64,
|
|
last_sequence: u64,
|
|
revoked: bool,
|
|
}
|
|
|
|
impl TrustedUpdateKey {
|
|
pub fn new(
|
|
public_key: [u8; 32],
|
|
platform: Platform,
|
|
first_sequence: u64,
|
|
last_sequence: u64,
|
|
revoked: bool,
|
|
) -> Result<Self> {
|
|
let key = VerifyingKey::from_bytes(&public_key).context("invalid update public key")?;
|
|
ensure!(!key.is_weak(), "weak update public key");
|
|
ensure!(
|
|
first_sequence > 0 && last_sequence >= first_sequence,
|
|
"invalid key sequence range"
|
|
);
|
|
Ok(Self {
|
|
key,
|
|
key_id: digest(&public_key),
|
|
platform,
|
|
first_sequence,
|
|
last_sequence,
|
|
revoked,
|
|
})
|
|
}
|
|
|
|
pub fn key_id(&self) -> &str {
|
|
&self.key_id
|
|
}
|
|
}
|
|
|
|
pub struct UpdateKeyring {
|
|
generation: u64,
|
|
keys: BTreeMap<String, TrustedUpdateKey>,
|
|
}
|
|
|
|
impl UpdateKeyring {
|
|
pub fn new(generation: u64, keys: Vec<TrustedUpdateKey>) -> Result<Self> {
|
|
ensure!(
|
|
generation > 0 && !keys.is_empty() && keys.len() <= 16,
|
|
"invalid provisioned keyring"
|
|
);
|
|
let mut indexed = BTreeMap::new();
|
|
for key in keys {
|
|
ensure!(!indexed.contains_key(key.key_id()), "duplicate update key");
|
|
indexed.insert(key.key_id.clone(), key);
|
|
}
|
|
Ok(Self {
|
|
generation,
|
|
keys: indexed,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct ActiveRelease {
|
|
pub sequence: u64,
|
|
pub manifest_sha256: String,
|
|
}
|
|
|
|
/// Must be obtained from authenticated local state and a trusted clock.
|
|
/// No boolean `approved`/`ready` is accepted or produced here. Persistence,
|
|
/// rollback detection and independent sync remain the caller's responsibility.
|
|
pub struct TrustedContext {
|
|
pub platform: Platform,
|
|
pub now_utc_seconds: u64,
|
|
pub keyring_generation: u64,
|
|
pub protocol_major: u32,
|
|
pub state_schema: u32,
|
|
pub updater_version: u32,
|
|
pub minimum_release_sequence: u64,
|
|
pub active_release: Option<ActiveRelease>,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ReleaseRelation {
|
|
AboveActivationFloor,
|
|
/// Metadata identity only: neither actual binary health nor a job Noop proof.
|
|
SameActiveManifest,
|
|
}
|
|
|
|
/// Private construction proves only release metadata validity at verification.
|
|
/// Holding this value grants NO permission to download, stop, install or start.
|
|
pub struct VerifiedRelease {
|
|
manifest: ReleaseManifest,
|
|
manifest_sha256: String,
|
|
key_id: String,
|
|
keyring_generation: u64,
|
|
relation: ReleaseRelation,
|
|
}
|
|
|
|
impl VerifiedRelease {
|
|
pub fn manifest(&self) -> &ReleaseManifest {
|
|
&self.manifest
|
|
}
|
|
|
|
pub fn manifest_sha256(&self) -> &str {
|
|
&self.manifest_sha256
|
|
}
|
|
|
|
pub fn key_id(&self) -> &str {
|
|
&self.key_id
|
|
}
|
|
|
|
pub fn keyring_generation(&self) -> u64 {
|
|
self.keyring_generation
|
|
}
|
|
|
|
pub fn relation(&self) -> ReleaseRelation {
|
|
self.relation
|
|
}
|
|
|
|
/// Verify a complete reader with a fixed 32 KiB buffer and no file writes.
|
|
/// A caller supplying a socket/pipe must enforce its own timeout and permit.
|
|
/// Descriptors come only from this verified release, never caller input.
|
|
pub fn verify_artifact(&self, role: ArtifactRole, mut reader: impl Read) -> Result<()> {
|
|
let descriptor = match role {
|
|
ArtifactRole::Agent => &self.manifest.artifacts[0],
|
|
ArtifactRole::Helper => &self.manifest.artifacts[1],
|
|
};
|
|
let mut buffer = [0_u8; 32 * 1024];
|
|
let mut remaining = descriptor.bytes;
|
|
let mut hasher = Sha256::new();
|
|
while remaining > 0 {
|
|
let limit = remaining.min(buffer.len() as u64) as usize;
|
|
let size = match reader.read(&mut buffer[..limit]) {
|
|
Ok(size) => size,
|
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error).context("release artifact read failed"),
|
|
};
|
|
ensure!(size > 0, "release artifact truncated");
|
|
hasher.update(&buffer[..size]);
|
|
remaining -= size as u64;
|
|
}
|
|
loop {
|
|
match reader.read(&mut buffer[..1]) {
|
|
Ok(0) => break,
|
|
Ok(_) => bail!("release artifact has extra bytes"),
|
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error).context("release artifact EOF check failed"),
|
|
}
|
|
}
|
|
ensure!(
|
|
hex::encode(hasher.finalize()) == descriptor.sha256,
|
|
"release artifact hash mismatch"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
pub fn verify_release(
|
|
signed: SignedRelease<'_>,
|
|
keyring: &UpdateKeyring,
|
|
context: &TrustedContext,
|
|
) -> Result<VerifiedRelease> {
|
|
ensure!(
|
|
signed.schema_version == 1,
|
|
"unsupported release envelope schema"
|
|
);
|
|
ensure!(
|
|
!signed.payload_bytes.is_empty() && signed.payload_bytes.len() <= MAX_MANIFEST_BYTES,
|
|
"release manifest size limit"
|
|
);
|
|
ensure!(is_digest(signed.key_id), "invalid update key ID");
|
|
ensure!(
|
|
keyring.generation == context.keyring_generation,
|
|
"update trust generation mismatch"
|
|
);
|
|
let key = keyring
|
|
.keys
|
|
.get(signed.key_id)
|
|
.context("untrusted update key")?;
|
|
ensure!(
|
|
!key.revoked && key.platform == context.platform,
|
|
"update key revoked or wrong platform"
|
|
);
|
|
let signature =
|
|
Signature::from_slice(signed.signature).context("invalid release signature size")?;
|
|
let mut message =
|
|
Vec::with_capacity(RELEASE_SIGNATURE_DOMAIN.len() + signed.payload_bytes.len());
|
|
message.extend_from_slice(RELEASE_SIGNATURE_DOMAIN);
|
|
message.extend_from_slice(signed.payload_bytes);
|
|
key.key
|
|
.verify_strict(&message, &signature)
|
|
.context("release signature rejected")?;
|
|
|
|
let manifest: ReleaseManifest =
|
|
serde_json::from_slice(signed.payload_bytes).context("invalid release manifest schema")?;
|
|
ensure!(
|
|
serde_json::to_vec(&manifest)? == signed.payload_bytes,
|
|
"noncanonical release manifest"
|
|
);
|
|
validate_manifest(&manifest, context)?;
|
|
ensure!(
|
|
(key.first_sequence..=key.last_sequence).contains(&manifest.release_sequence),
|
|
"release outside update key sequence range"
|
|
);
|
|
let manifest_sha256 = digest(signed.payload_bytes);
|
|
let relation = match &context.active_release {
|
|
Some(active) => {
|
|
ensure!(
|
|
active.sequence > 0
|
|
&& is_digest(&active.manifest_sha256)
|
|
&& active.sequence <= context.minimum_release_sequence,
|
|
"invalid trusted active release state"
|
|
);
|
|
if manifest.release_sequence == active.sequence {
|
|
ensure!(
|
|
manifest_sha256 == active.manifest_sha256,
|
|
"release sequence content conflict"
|
|
);
|
|
ReleaseRelation::SameActiveManifest
|
|
} else {
|
|
ensure!(
|
|
manifest.release_sequence > context.minimum_release_sequence,
|
|
"release is not above activation floor"
|
|
);
|
|
ReleaseRelation::AboveActivationFloor
|
|
}
|
|
}
|
|
None => {
|
|
ensure!(
|
|
manifest.release_sequence > context.minimum_release_sequence,
|
|
"release is not above activation floor"
|
|
);
|
|
ReleaseRelation::AboveActivationFloor
|
|
}
|
|
};
|
|
Ok(VerifiedRelease {
|
|
manifest,
|
|
manifest_sha256,
|
|
key_id: signed.key_id.to_owned(),
|
|
keyring_generation: keyring.generation,
|
|
relation,
|
|
})
|
|
}
|
|
|
|
fn validate_manifest(manifest: &ReleaseManifest, context: &TrustedContext) -> Result<()> {
|
|
ensure!(
|
|
manifest.schema_version == 1,
|
|
"unsupported release manifest schema"
|
|
);
|
|
ensure!(
|
|
!manifest.release_id.is_nil() && manifest.release_sequence > 0,
|
|
"invalid release identity"
|
|
);
|
|
ensure!(
|
|
!manifest.version.is_empty()
|
|
&& manifest.version.len() <= 64
|
|
&& manifest
|
|
.version
|
|
.bytes()
|
|
.all(|byte| byte.is_ascii_alphanumeric() || b".-+_".contains(&byte)),
|
|
"invalid release version label"
|
|
);
|
|
ensure!(
|
|
manifest.platform == context.platform,
|
|
"release platform mismatch"
|
|
);
|
|
ensure!(
|
|
manifest.published_at <= context.now_utc_seconds
|
|
&& manifest.expires_at > context.now_utc_seconds
|
|
&& manifest.expires_at > manifest.published_at,
|
|
"release outside trusted validity interval"
|
|
);
|
|
ensure!(
|
|
context.protocol_major > 0 && manifest.protocol_major == context.protocol_major,
|
|
"incompatible release protocol"
|
|
);
|
|
ensure!(
|
|
context.state_schema > 0 && manifest.state_schema == context.state_schema,
|
|
"incompatible release state schema"
|
|
);
|
|
ensure!(
|
|
manifest.minimum_updater_version > 0
|
|
&& manifest.minimum_updater_version <= context.updater_version,
|
|
"updater version unsupported"
|
|
);
|
|
ensure!(
|
|
manifest.release_sequence >= context.minimum_release_sequence,
|
|
"release below activation floor"
|
|
);
|
|
ensure!(
|
|
manifest.artifacts[0].role == ArtifactRole::Agent
|
|
&& manifest.artifacts[1].role == ArtifactRole::Helper,
|
|
"release requires ordered agent and helper artifacts"
|
|
);
|
|
ensure!(
|
|
manifest.artifacts[0].artifact_id != manifest.artifacts[1].artifact_id,
|
|
"duplicate release artifact ID"
|
|
);
|
|
for artifact in &manifest.artifacts {
|
|
ensure!(
|
|
!artifact.artifact_id.is_nil()
|
|
&& is_digest(&artifact.sha256)
|
|
&& (1..=MAX_ARTIFACT_BYTES).contains(&artifact.bytes),
|
|
"invalid release artifact descriptor"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn digest(bytes: &[u8]) -> String {
|
|
hex::encode(Sha256::digest(bytes))
|
|
}
|
|
|
|
fn is_digest(value: &str) -> bool {
|
|
value.len() == 64
|
|
&& value
|
|
.bytes()
|
|
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
|
}
|