//! Freshness through TUF ().
//!
//! A project's TUF repository signs one target, `release.json`
//! (`{"release": "2.0"}`): which release is the latest. The client follows
//! the specification's update workflow (section 5): it walks the root chain
//! from the root the user pinned (rotation), refuses expired metadata (freeze
//! attacks) and versions lower than ones it has seen (rollback), checks every
//! role's threshold, and checks lengths and hashes along the way. So a
//! correctly attested but older release can't be passed off as current.
//!
//! Layout, as tuftool, python-tuf and tuf-on-ci write it: `metadata/`
//! (`.root.json`, `timestamp.json`, snapshot and targets; consistent
//! snapshots or not) and `targets/`.
//!
//! Keys: `ed25519` (hex public key) and `ecdsa`/`ecdsa-sha2-nistp256` (PEM),
//! signatures in hex, as securesystemslib writes them.
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::time::SystemTime;
use anyhow::{Context, Result, anyhow, bail};
use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
use serde_json::{Value, json};
use sha2::{Digest, Sha256, Sha512};
use crate::cjson;
use crate::keyring::PubKey;
use crate::source::Source;
use crate::time;
/// Root versions to walk at most in one update.
const MAX_ROOT_ROTATIONS: u64 = 1024;
pub const RELEASE_TARGET: &str = "release.json";
/// A repository's metadata directory.
pub fn metadata(url: &str) -> Source {
Source::parse(&format!("{}/metadata", url.trim_end_matches('/')))
}
/// A repository's targets directory.
pub fn targets(url: &str) -> Source {
Source::parse(&format!("{}/targets", url.trim_end_matches('/')))
}
// ── metadata and signatures ─────────────────────────────────────────────────
struct Meta {
signed: Value,
/// (keyid, signature bytes)
sigs: Vec<(String, Vec)>,
}
fn parse(bytes: &[u8], typ: &str) -> Result {
let v: Value =
serde_json::from_slice(bytes).with_context(|| format!("{typ} metadata isn't JSON"))?;
let signed = v
.get("signed")
.cloned()
.with_context(|| format!("{typ} metadata has no \"signed\""))?;
let got = signed["_type"].as_str().unwrap_or("");
if got != typ {
bail!("expected {typ} metadata, got {got:?}");
}
let sigs = v["signatures"]
.as_array()
.with_context(|| format!("{typ} metadata has no signatures"))?
.iter()
.filter_map(|s| {
Some((
s["keyid"].as_str()?.to_string(),
hex::decode(s["sig"].as_str()?).ok()?,
))
})
.collect();
Ok(Meta { signed, sigs })
}
impl Meta {
fn version(&self) -> Result {
self.signed["version"]
.as_u64()
.context("metadata without a version")
}
fn expires(&self) -> Result {
time::parse(
self.signed["expires"]
.as_str()
.context("metadata without an expiry")?,
)
}
fn check_fresh(&self, typ: &str, now: SystemTime) -> Result<()> {
let exp = self.expires()?;
if exp <= now {
bail!(
"FROZEN: {typ} metadata expired {}: the server may be replaying old data, \
or the project hasn't refreshed it",
time::format(exp)
);
}
Ok(())
}
}
/// A key as it appears in root metadata.
fn tuf_key(v: &Value) -> Result {
let typ = v["keytype"].as_str().unwrap_or("");
let scheme = v["scheme"].as_str().unwrap_or("");
let public = v["keyval"]["public"]
.as_str()
.context("key without keyval.public")?;
match (typ, scheme) {
("ed25519", "ed25519") => {
let bytes: [u8; 32] = hex::decode(public)?
.try_into()
.map_err(|_| anyhow!("Ed25519 public key isn't 32 bytes"))?;
Ok(PubKey::Ed25519(ed25519_dalek::VerifyingKey::from_bytes(
&bytes,
)?))
}
("ecdsa" | "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256") => Ok(PubKey::P256(
p256::ecdsa::VerifyingKey::from_public_key_pem(public)
.context("bad ECDSA P-256 key")?,
)),
_ => bail!("unsupported key type {typ:?} / scheme {scheme:?}"),
}
}
fn verify_sig(key: &PubKey, msg: &[u8], sig: &[u8]) -> bool {
match key {
PubKey::Ed25519(k) => ed25519_dalek::Signature::from_slice(sig)
.map(|s| k.verify_strict(msg, &s).is_ok())
.unwrap_or(false),
PubKey::P256(k) => {
use p256::ecdsa::signature::Verifier;
p256::ecdsa::Signature::from_der(sig)
.or_else(|_| p256::ecdsa::Signature::from_slice(sig))
.map(|s| k.verify(msg, &s).is_ok())
.unwrap_or(false)
}
PubKey::Pgp(_) => false,
}
}
/// Checks that `meta` is signed by at least `role`'s threshold of `root`'s
/// keys for it. A key counts once, however many key IDs it is listed under.
fn verify_role(meta: &Meta, root: &Value, role: &str) -> Result<()> {
let r = &root["roles"][role];
let threshold = r["threshold"]
.as_u64()
.with_context(|| format!("root has no {role} threshold"))?;
if threshold == 0 {
bail!("{role} threshold is 0");
}
let keyids: Vec<&str> = r["keyids"]
.as_array()
.map(|a| a.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let msg = cjson::encode(&meta.signed)?;
let mut counted: HashSet = HashSet::new();
for (keyid, sig) in &meta.sigs {
if !keyids.contains(&keyid.as_str()) {
continue;
}
let Ok(key) = tuf_key(&root["keys"][keyid.as_str()]) else {
continue;
};
if verify_sig(&key, &msg, sig) {
counted.insert(key.fingerprint());
}
}
if (counted.len() as u64) < threshold {
bail!(
"{} metadata has {} valid signature(s) from {role} keys; {threshold} needed",
meta.signed["_type"].as_str().unwrap_or(role),
counted.len()
);
}
Ok(())
}
/// Checks `length` and any `hashes` (sha256, sha512) that `info` lists for `data`.
fn check_hashes(data: &[u8], info: &Value, what: &str) -> Result<()> {
if let Some(len) = info.get("length").and_then(Value::as_u64)
&& data.len() as u64 != len
{
bail!("{what} is {} bytes; the metadata says {len}", data.len());
}
if let Some(hashes) = info.get("hashes").and_then(Value::as_object) {
let mut known = 0;
for (alg, want) in hashes {
let got = match alg.as_str() {
"sha256" => hex::encode(Sha256::digest(data)),
"sha512" => hex::encode(Sha512::digest(data)),
_ => continue,
};
known += 1;
if !want.as_str().is_some_and(|w| w.eq_ignore_ascii_case(&got)) {
bail!("{what}'s {alg} doesn't match the metadata");
}
}
if known == 0 {
bail!("{what}: no hash algorithm we know (sha256, sha512)");
}
}
Ok(())
}
// ── the client ──────────────────────────────────────────────────────────────
pub struct Fresh {
pub latest: String,
pub root_version: u64,
pub timestamp_expires: SystemTime,
}
fn read_local(dir: &Path, name: &str, typ: &str) -> Result