🏡 index : quine-global/quorum.git

//! DSSE envelopes carrying in-toto Statements
//! (<https://github.com/secure-systems-lab/dsse>,
//! <https://github.com/in-toto/attestation>).
//!
//! A rebuilder's attestation is one envelope whose Statement lists the files
//! they built as subjects, with their SHA-256: `quorum statement` writes the
//! Statement, cosign signs it (`cosign attest-blob --statement`) into a
//! Sigstore bundle, which carries the envelope. Signatures are over DSSE's PAE
//! encoding of the payload: Ed25519, or ECDSA P-256 with SHA-256 (DER or raw
//! r||s), which is what cosign writes.

use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::keyring::PubKey;

pub const PAYLOAD_TYPE: &str = "application/vnd.in-toto+json";
pub const STATEMENT_V1: &str = "https://in-toto.io/Statement/v1";
const STATEMENT_V01: &str = "https://in-toto.io/Statement/v0.1";
/// What `quorum statement` writes: "I rebuilt these files for this release."
/// Its `release` is checked against the release being verified.
pub const REBUILD_PREDICATE: &str = "https://quineglobal.com/quorum/rebuild/v0";

#[derive(Serialize, Deserialize)]
pub struct Envelope {
    #[serde(rename = "payloadType")]
    pub payload_type: String,
    pub payload: String,
    pub signatures: Vec<EnvSig>,
}

#[derive(Serialize, Deserialize)]
pub struct EnvSig {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub keyid: String,
    pub sig: String,
}

/// DSSE's Pre-Authentication Encoding: what is actually signed.
pub fn pae(payload_type: &str, payload: &[u8]) -> Vec<u8> {
    let mut out = format!(
        "DSSEv1 {} {} {} ",
        payload_type.len(),
        payload_type,
        payload.len()
    )
    .into_bytes();
    out.extend_from_slice(payload);
    out
}

fn b64(s: &str) -> Result<Vec<u8>> {
    STANDARD
        .decode(s.trim())
        .or_else(|_| URL_SAFE_NO_PAD.decode(s.trim().trim_end_matches('=')))
        .context("bad base64")
}

/// What a verified Statement says.
pub struct Statement {
    /// `(name, sha256)` for every subject with a SHA-256 digest.
    pub subjects: Vec<(String, String)>,
    /// The release, for a quorum rebuild predicate.
    pub release: Option<String>,
}

pub enum Outcome {
    /// Signed by one of the pinned keys.
    Good(Statement),
    /// No signature by a pinned key; the key IDs the envelope names.
    Bad(Vec<String>),
}

/// Checks an envelope's signatures against `keys`; reads the Statement only
/// if one of them is good.
pub fn verify(data: &[u8], keys: &[&PubKey]) -> Result<Outcome> {
    let v: Value = serde_json::from_slice(data).context("not JSON")?;
    // A Sigstore bundle carries the envelope; quorum checks its signature
    // against the pinned keys, not the bundle's certificates or log entries.
    // Its signatures have no keyid; its key hint (base64 SHA-256 of the
    // public key) is the same as our fingerprints, so a wrong signer is named.
    let hint = v["verificationMaterial"]["publicKey"]["hint"]
        .as_str()
        .and_then(|h| b64(h).ok())
        .map(hex::encode);
    let v = if v["dsseEnvelope"].is_object() {
        v["dsseEnvelope"].clone()
    } else {
        v
    };
    let mut env: Envelope =
        serde_json::from_value(v).context("not a DSSE envelope or Sigstore bundle")?;
    if let Some(h) = hint {
        for s in env.signatures.iter_mut().filter(|s| s.keyid.is_empty()) {
            s.keyid = h.clone();
        }
    }
    let payload = b64(&env.payload).context("the payload")?;
    let msg = pae(&env.payload_type, &payload);
    let good = env.signatures.iter().any(|s| {
        let Ok(sig) = b64(&s.sig) else { return false };
        keys.iter().any(|k| verify_one(k, &msg, &sig))
    });
    if !good {
        return Ok(Outcome::Bad(
            env.signatures
                .iter()
                .map(|s| s.keyid.clone())
                .filter(|k| !k.is_empty())
                .collect(),
        ));
    }
    if env.payload_type != PAYLOAD_TYPE {
        bail!(
            "payload type {:?}, not an in-toto Statement",
            env.payload_type
        );
    }
    Ok(Outcome::Good(parse_statement(&payload)?))
}

fn verify_one(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;
            let s = p256::ecdsa::Signature::from_der(sig)
                .or_else(|_| p256::ecdsa::Signature::from_slice(sig));
            s.map(|s| k.verify(msg, &s).is_ok()).unwrap_or(false)
        }
        PubKey::Pgp(_) => false,
    }
}

fn parse_statement(payload: &[u8]) -> Result<Statement> {
    let v: Value = serde_json::from_slice(payload).context("the Statement isn't JSON")?;
    let typ = v["_type"].as_str().unwrap_or("");
    if typ != STATEMENT_V1 && typ != STATEMENT_V01 {
        bail!("not an in-toto Statement (_type {typ:?})");
    }
    let predicate_type = v["predicateType"].as_str().unwrap_or("").to_string();
    let subjects = v["subject"]
        .as_array()
        .context("the Statement has no subjects")?
        .iter()
        .filter_map(|s| {
            let name = s["name"].as_str()?;
            let h = s["digest"]["sha256"].as_str()?;
            (h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()))
                .then(|| (name.to_string(), h.to_ascii_lowercase()))
        })
        .collect();
    let release = (predicate_type == REBUILD_PREDICATE)
        .then(|| v["predicate"]["release"].as_str().map(String::from))
        .flatten();
    Ok(Statement { subjects, release })
}

/// A signed rebuild attestation for `files` (name, sha256) of `release`.
/// The Statement of a rebuild: `files` (name, sha256) of `release`, for
/// cosign to sign.
pub fn rebuild_statement(release: &str, files: &[(String, String)]) -> Result<String> {
    let statement = json!({
        "_type": STATEMENT_V1,
        "subject": files.iter().map(|(n, h)| json!({"name": n, "digest": {"sha256": h}})).collect::<Vec<_>>(),
        "predicateType": REBUILD_PREDICATE,
        "predicate": {"release": release},
    });
    Ok(serde_json::to_string_pretty(&statement)? + "\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pae_matches_the_spec_example() {
        // From the DSSE protocol document.
        assert_eq!(
            pae("http://example.com/HelloWorld", b"hello world"),
            b"DSSEv1 29 http://example.com/HelloWorld 11 hello world"
        );
    }

    #[test]
    fn sign_then_verify() {
        let sk = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
        let pk = PubKey::Ed25519(sk.verifying_key());
        let other =
            PubKey::Ed25519(ed25519_dalek::SigningKey::from_bytes(&[8u8; 32]).verifying_key());
        let h = "a".repeat(64);
        let payload = rebuild_statement("1.0", &[("x.exe".into(), h.clone())]).unwrap();
        let sig = ed25519_dalek::Signer::sign(&sk, &pae(PAYLOAD_TYPE, payload.as_bytes()));
        let env = serde_json::to_string(&Envelope {
            payload_type: PAYLOAD_TYPE.into(),
            payload: STANDARD.encode(&payload),
            signatures: vec![EnvSig {
                keyid: "k".into(),
                sig: STANDARD.encode(sig.to_bytes()),
            }],
        })
        .unwrap();
        match verify(env.as_bytes(), &[&pk]).unwrap() {
            Outcome::Good(s) => {
                assert_eq!(s.subjects, vec![("x.exe".to_string(), h)]);
                assert_eq!(s.release.as_deref(), Some("1.0"));
            }
            Outcome::Bad(_) => panic!("should verify"),
        }
        assert!(
            matches!(verify(env.as_bytes(), &[&other]).unwrap(), Outcome::Bad(ids) if ids == ["k"])
        );
        // The same envelope inside a Sigstore bundle, as cosign writes it.
        let bundle = format!(
            r#"{{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json","dsseEnvelope":{env}}}"#
        );
        assert!(matches!(
            verify(bundle.as_bytes(), &[&pk]).unwrap(),
            Outcome::Good(_)
        ));
        // Any change to the payload breaks the signature.
        let mut e: Envelope = serde_json::from_str(&env).unwrap();
        let mut p = STANDARD.decode(&e.payload).unwrap();
        p[10] ^= 1;
        e.payload = STANDARD.encode(p);
        let tampered = serde_json::to_vec(&e).unwrap();
        assert!(matches!(
            verify(&tampered, &[&pk]).unwrap(),
            Outcome::Bad(_)
        ));
    }
}