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;
const MAX_ROOT_ROTATIONS: u64 = 1024;
pub const RELEASE_TARGET: &str = "release.json";
pub fn metadata(url: &str) -> Source {
Source::parse(&format!("{}/metadata", url.trim_end_matches('/')))
}
pub fn targets(url: &str) -> Source {
Source::parse(&format!("{}/targets", url.trim_end_matches('/')))
}
struct Meta {
signed: Value,
sigs: Vec<(String, Vec<u8>)>,
}
fn parse(bytes: &[u8], typ: &str) -> Result<Meta> {
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<u64> {
self.signed["version"]
.as_u64()
.context("metadata without a version")
}
fn expires(&self) -> Result<SystemTime> {
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(())
}
}
fn tuf_key(v: &Value) -> Result<PubKey> {
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,
}
}
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<String> = 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(())
}
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(())
}
pub struct Fresh {
pub latest: String,
pub root_version: u64,
pub timestamp_expires: SystemTime,
}
fn read_local(dir: &Path, name: &str, typ: &str) -> Result<Option<Meta>> {
match fs::read(dir.join(name)) {
Ok(b) => Ok(Some(
parse(&b, typ).with_context(|| format!("the trusted {name}"))?,
)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
fn save(dir: &Path, name: &str, data: &[u8]) -> Result<()> {
let tmp = dir.join(format!("{name}.tmp"));
fs::write(&tmp, data)?;
fs::rename(&tmp, dir.join(name))?;
Ok(())
}
pub fn root_pin(data: &[u8]) -> String {
hex::encode(Sha256::digest(data))
}
pub fn pin_root(dir: &Path, data: &[u8]) -> Result<u64> {
let root = parse(data, "root")?;
verify_role(&root, &root.signed, "root")
.context("the root isn't signed by its own root keys")?;
fs::create_dir_all(dir)?;
for f in ["timestamp.json", "snapshot.json", "targets.json"] {
let _ = fs::remove_file(dir.join(f));
}
save(dir, "root.json", data)?;
root.version()
}
pub fn update(dir: &Path, src: &Source, targets_src: &Source, now: SystemTime) -> Result<Fresh> {
let mut root = read_local(dir, "root.json", "root")?.context("no pinned TUF root")?;
let first_version = root.version()?;
loop {
let next = root.version()? + 1;
if next > first_version + MAX_ROOT_ROTATIONS {
bail!("more than {MAX_ROOT_ROTATIONS} root versions in one update");
}
let Some(data) = src.get(&format!("{next}.root.json"))? else {
break;
};
let new = parse(&data, "root")?;
verify_role(&new, &root.signed, "root")
.with_context(|| format!("root v{next}: not signed by the trusted root's keys"))?;
verify_role(&new, &new.signed, "root")
.with_context(|| format!("root v{next}: not signed by its own keys"))?;
if new.version()? != next {
bail!("{next}.root.json says it's version {}", new.version()?);
}
let rotated = ["timestamp", "snapshot"]
.iter()
.any(|r| new.signed["roles"][r]["keyids"] != root.signed["roles"][r]["keyids"]);
if rotated {
let _ = fs::remove_file(dir.join("timestamp.json"));
let _ = fs::remove_file(dir.join("snapshot.json"));
}
save(dir, "root.json", &data)?;
root = new;
}
root.check_fresh("root", now)?;
let consistent = root.signed["consistent_snapshot"]
.as_bool()
.unwrap_or(false);
let data = src
.get("timestamp.json")?
.context("the project serves no timestamp.json")?;
let mut ts = parse(&data, "timestamp")?;
verify_role(&ts, &root.signed, "timestamp")?;
let snap_info = |m: &Meta| m.signed["meta"]["snapshot.json"].clone();
if let Some(old) = read_local(dir, "timestamp.json", "timestamp")? {
let (nv, ov) = (ts.version()?, old.version()?);
if nv < ov {
bail!("ROLLBACK: timestamp v{nv} offered, but v{ov} was seen before");
}
let (ns, os) = (
snap_info(&ts)["version"].as_u64(),
snap_info(&old)["version"].as_u64(),
);
if ns < os {
bail!("ROLLBACK: timestamp points at snapshot v{ns:?}, but v{os:?} was seen before");
}
if nv == ov {
ts = old;
} else {
save(dir, "timestamp.json", &data)?;
}
} else {
save(dir, "timestamp.json", &data)?;
}
ts.check_fresh("timestamp", now)?;
let sinfo = snap_info(&ts);
let sv = sinfo["version"]
.as_u64()
.context("timestamp without a snapshot version")?;
let path = if consistent {
format!("{sv}.snapshot.json")
} else {
"snapshot.json".into()
};
let data = src
.get(&path)?
.with_context(|| format!("the project serves no {path}"))?;
check_hashes(&data, &sinfo, "snapshot.json")?;
let snap = parse(&data, "snapshot")?;
verify_role(&snap, &root.signed, "snapshot")?;
if snap.version()? != sv {
bail!("snapshot is v{}, the timestamp says v{sv}", snap.version()?);
}
if let Some(old) = read_local(dir, "snapshot.json", "snapshot")?
&& let Some(files) = old.signed["meta"].as_object()
{
for (name, info) in files {
let was = info["version"].as_u64().unwrap_or(0);
match snap.signed["meta"][name]["version"].as_u64() {
None => bail!("ROLLBACK: snapshot dropped {name}"),
Some(v) if v < was => {
bail!("ROLLBACK: {name} v{v} offered, but v{was} was seen before")
}
_ => {}
}
}
}
snap.check_fresh("snapshot", now)?;
save(dir, "snapshot.json", &data)?;
let tinfo = snap.signed["meta"]["targets.json"].clone();
let tv = tinfo["version"]
.as_u64()
.context("snapshot without a targets version")?;
let path = if consistent {
format!("{tv}.targets.json")
} else {
"targets.json".into()
};
let data = src
.get(&path)?
.with_context(|| format!("the project serves no {path}"))?;
check_hashes(&data, &tinfo, "targets.json")?;
let targets = parse(&data, "targets")?;
verify_role(&targets, &root.signed, "targets")?;
if targets.version()? != tv {
bail!(
"targets is v{}, the snapshot says v{tv}",
targets.version()?
);
}
targets.check_fresh("targets", now)?;
save(dir, "targets.json", &data)?;
let info = targets.signed["targets"][RELEASE_TARGET].clone();
if info.is_null() {
bail!("the project's targets don't list {RELEASE_TARGET}");
}
let path = match info["hashes"]["sha256"].as_str() {
Some(h) if consistent => format!("{h}.{RELEASE_TARGET}"),
_ => RELEASE_TARGET.to_string(),
};
let data = targets_src
.get(&path)?
.with_context(|| format!("the project serves no {path} in {}", targets_src.describe()))?;
check_hashes(&data, &info, RELEASE_TARGET)?;
let release: Value = serde_json::from_slice(&data).context("release.json isn't JSON")?;
let latest = release["release"]
.as_str()
.context("release.json has no \"release\"")?
.to_string();
Ok(Fresh {
latest,
root_version: root.version()?,
timestamp_expires: ts.expires()?,
})
}
pub struct SignKey {
sk: ed25519_dalek::SigningKey,
}
impl SignKey {
pub fn load(path: &Path) -> Result<Self> {
let pem =
fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(&pem)
.with_context(|| format!("{}: not an Ed25519 PKCS#8 private key", path.display()))?;
Ok(SignKey { sk })
}
fn keyid_in(&self, root: &Value, role: &str) -> Result<String> {
let public = hex::encode(self.sk.verifying_key().as_bytes());
root["roles"][role]["keyids"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.find(|id| {
let k = &root["keys"][*id];
k["keytype"] == "ed25519" && k["keyval"]["public"].as_str() == Some(&public)
})
.map(String::from)
.with_context(|| format!("that key isn't one of the root's {role} keys"))
}
}
fn sign(signed: Value, key: &SignKey, keyid: &str) -> Result<Vec<u8>> {
use ed25519_dalek::Signer;
let msg = cjson::encode(&signed)?;
let sig = json!({"keyid": keyid, "sig": hex::encode(key.sk.sign(&msg).to_bytes())});
let mut out = serde_json::to_vec_pretty(&json!({"signed": signed, "signatures": [sig]}))?;
out.push(b'\n');
Ok(out)
}
fn read_json(dir: &Path, name: &str) -> Result<Value> {
let data = fs::read(dir.join(name)).with_context(|| format!("reading {name}"))?;
serde_json::from_slice(&data).with_context(|| format!("{name} isn't JSON"))
}
fn next(signed: &Value, exp: std::time::Duration, now: SystemTime) -> Result<(u64, Value)> {
let v = signed["version"].as_u64().context("no version")? + 1;
let mut s = signed.clone();
s["version"] = v.into();
s["expires"] = time::format(now + exp).into();
Ok((v, s))
}
pub struct Expiries {
pub snapshot: std::time::Duration,
pub timestamp: std::time::Duration,
}
pub fn refresh(
dir: &Path,
snapshot_key: Option<&SignKey>,
timestamp_key: &SignKey,
exp: &Expiries,
now: SystemTime,
) -> Result<()> {
let rv = (1..)
.take_while(|n| dir.join(format!("{n}.root.json")).exists())
.last()
.with_context(|| format!("no N.root.json in {}", dir.display()))?;
let root = read_json(dir, &format!("{rv}.root.json"))?["signed"].clone();
let consistent = root["consistent_snapshot"].as_bool().unwrap_or(false);
let snap_name = |v: u64| {
if consistent {
format!("{v}.snapshot.json")
} else {
"snapshot.json".to_string()
}
};
let ts = read_json(dir, "timestamp.json")?["signed"].clone();
let mut sv = ts["meta"]["snapshot.json"]["version"]
.as_u64()
.context("timestamp.json names no snapshot version")?;
if let Some(key) = snapshot_key {
let id = key.keyid_in(&root, "snapshot")?;
let old = read_json(dir, &snap_name(sv))?["signed"].clone();
let (v, signed) = next(&old, exp.snapshot, now)?;
fs::write(dir.join(snap_name(v)), sign(signed, key, &id)?)?;
sv = v;
}
let snap = fs::read(dir.join(snap_name(sv)))?;
let id = timestamp_key.keyid_in(&root, "timestamp")?;
let (_, mut signed) = next(&ts, exp.timestamp, now)?;
signed["meta"] = json!({"snapshot.json": {
"version": sv,
"length": snap.len(),
"hashes": {"sha256": hex::encode(Sha256::digest(&snap))},
}});
fs::write(
dir.join("timestamp.json"),
sign(signed, timestamp_key, &id)?,
)?;
Ok(())
}
pub fn describe_root(data: &[u8]) -> Result<String> {
let root = parse(data, "root")?;
let r = &root.signed["roles"];
let n = |role: &str| {
format!(
"{role} {}/{}",
r[role]["threshold"].as_u64().unwrap_or(0),
r[role]["keyids"].as_array().map(Vec::len).unwrap_or(0)
)
};
Ok(format!(
"root v{}, expires {}; thresholds: {}, {}, {}, {}",
root.version()?,
root.signed["expires"].as_str().unwrap_or("?"),
n("root"),
n("targets"),
n("snapshot"),
n("timestamp")
))
}