garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /pkg/src/trust.rs

raw

//! Whose packages a system installs: a key for each publisher, the
//! publisher each installed app came from, and keys taken back.
//!
//! The system trusts some keys itself (`/settings/trusted-keys`, a line a
//! key: `<64 hex digits> <publisher>`, and `registry` after it for a key
//! that may vouch for other publishers). A **registry** is such a key's
//! signed list of other publishers' keys, and of keys taken back (revoked):
//! the hosted Store's, at `<source>packages/publishers.ppk`, is how a
//! publisher other than this repository is admitted, and how a key that
//! leaked stops working on every system that reads it. Each package then
//! opens as its publisher's, and an installed app is only ever replaced by
//! a package of the publisher it came from ([`may_replace`]), so one
//! publisher's key cannot take over another's apps.
//!
//! A key once revoked stays revoked (`/settings/revoked-keys`), whatever
//! list comes later: an old list served again cannot bring it back.

use crate::{Error, key_hex, pack, parse_keys, verify};
use alloc::string::String;
use alloc::vec::Vec;

/// A package's entries: name and contents.
pub type Entries<'a> = Vec<(&'a str, &'a [u8])>;

/// A key and the publisher it signs for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Key {
    pub key: [u8; 32],
    pub publisher: String,
    /// It may vouch for other publishers' keys (only a key the system
    /// trusts itself).
    pub registry: bool,
    /// The registry that vouched for it; None for a key the system trusts
    /// itself.
    pub from: Option<String>,
}

/// The keys a system installs from, and those taken back.
#[derive(Clone, Debug, Default)]
pub struct Trust {
    keys: Vec<Key>,
    revoked: Vec<[u8; 32]>,
}

/// A publisher's name: 1 to 32 of `a`–`z`, `0`–`9` and `-`.
pub fn valid_publisher(name: &str) -> bool {
    (1..=32).contains(&name.len())
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

impl Trust {
    /// From `/settings/trusted-keys` and `/settings/revoked-keys`. A key
    /// alone on its line (as systems wrote them before publishers had
    /// names) is its own publisher, named by its first eight hex digits.
    pub fn parse(trusted: &str, revoked: &str) -> Trust {
        let mut keys: Vec<Key> = Vec::new();
        for line in trusted.lines().map(str::trim) {
            let mut words = line.split_whitespace();
            let Some(key) = words.next().and_then(|w| parse_keys(w).pop()) else {
                continue;
            };
            let publisher = match words.next() {
                Some(name) if valid_publisher(name) => String::from(name),
                Some(_) => continue,
                None => String::from(&key_hex(&key)[..8]),
            };
            let registry = words.next() == Some("registry");
            if !keys.iter().any(|k| k.key == key) {
                keys.push(Key {
                    key,
                    publisher,
                    registry,
                    from: None,
                });
            }
        }
        Trust {
            keys,
            revoked: parse_keys(revoked),
        }
    }

    /// The keys taken back, as `/settings/revoked-keys` keeps them.
    pub fn revoked_text(&self) -> String {
        self.revoked.iter().map(|k| key_hex(k) + "\n").collect()
    }

    pub fn is_revoked(&self, key: &[u8; 32]) -> bool {
        self.revoked.contains(key)
    }

    /// The publisher `key` signs for, unless it was taken back.
    pub fn publisher(&self, key: &[u8; 32]) -> Option<&str> {
        if self.is_revoked(key) {
            return None;
        }
        self.keys
            .iter()
            .find(|k| k.key == *key)
            .map(|k| k.publisher.as_str())
    }

    /// Takes in what a registry says: the keys it vouches for, each its
    /// publisher's, and the keys it takes back. A name the system already
    /// gives a key of its own is not the registry's to hand out (but its
    /// own name is: that is how it moves to a new key).
    pub fn admit(&mut self, registry: &Registry) {
        for key in &registry.revoked {
            if !self.revoked.contains(key) {
                self.revoked.push(*key);
            }
        }
        for (key, name) in &registry.keys {
            let mine = Some(registry.publisher.as_str());
            let taken = self.keys.iter().any(|k| {
                let owner = if k.registry {
                    Some(k.publisher.as_str())
                } else {
                    k.from.as_deref()
                };
                k.publisher == *name && owner != mine
            });
            if taken || self.keys.iter().any(|k| k.key == *key) {
                continue;
            }
            self.keys.push(Key {
                key: *key,
                publisher: name.clone(),
                registry: false,
                from: Some(registry.publisher.clone()),
            });
        }
    }

    /// A signed package's entries and its publisher, if a key of this
    /// trust signed it.
    pub fn open<'a>(&self, package: &'a [u8]) -> Result<(Entries<'a>, &str), Error> {
        let all: Vec<[u8; 32]> = self
            .keys
            .iter()
            .map(|k| k.key)
            .chain(self.revoked.iter().copied())
            .collect();
        let (signer, archive) = verify(package, &all)?;
        let publisher = self.publisher(&all[signer]).ok_or(Error::Revoked)?;
        let entries = crate::unpack(archive).ok_or(Error::Damaged)?;
        Ok((entries, publisher))
    }
}

/// Whether a package from `signer` may replace an app installed from
/// `installed` (None: installed before apps kept their publisher, so any
/// trusted publisher may, once; it is that publisher's from then on).
pub fn may_replace(installed: Option<&str>, signer: &str) -> bool {
    installed.is_none_or(|p| p == signer)
}

/// A registry's list, its signature checked.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Registry {
    /// When it was made: a list is only taken in over one older than it.
    pub issued: u64,
    /// Whose list it is: the publisher of the key that signed it.
    pub publisher: String,
    pub keys: Vec<([u8; 32], String)>,
    pub revoked: Vec<[u8; 32]>,
}

/// The entry a registry's package holds its list in.
const LIST: &str = "publishers";

impl Registry {
    /// A registry's package (`publishers.ppk`), if one of `trust`'s
    /// registry keys signed it and it is a list.
    pub fn open(package: &[u8], trust: &Trust) -> Result<Registry, Error> {
        let registries: Vec<&Key> = trust
            .keys
            .iter()
            .filter(|k| k.registry && !trust.is_revoked(&k.key))
            .collect();
        let keys: Vec<[u8; 32]> = registries.iter().map(|k| k.key).collect();
        let (signer, archive) = verify(package, &keys)?;
        let entries = crate::unpack(archive).ok_or(Error::Damaged)?;
        let text = entries
            .iter()
            .find(|(n, _)| *n == LIST)
            .and_then(|(_, data)| core::str::from_utf8(data).ok())
            .ok_or(Error::Damaged)?;
        let mut list = Registry::parse(text).ok_or(Error::Damaged)?;
        list.publisher = registries[signer].publisher.clone();
        Ok(list)
    }

    /// The list's text: `issued <n>`, then `key <hex> <publisher>` and
    /// `revoked <hex>` lines; `#` begins a comment.
    pub fn parse(text: &str) -> Option<Registry> {
        let mut list = Registry {
            issued: 0,
            publisher: String::new(),
            keys: Vec::new(),
            revoked: Vec::new(),
        };
        for line in text.lines().map(str::trim) {
            let words: Vec<&str> = line.split_whitespace().collect();
            match words[..] {
                [] => {}
                [first, ..] if first.starts_with('#') => {}
                ["issued", n] => list.issued = n.parse().ok()?,
                ["key", key, name] if valid_publisher(name) => {
                    list.keys.push((parse_keys(key).pop()?, String::from(name)));
                }
                ["revoked", key] => list.revoked.push(parse_keys(key).pop()?),
                _ => return None,
            }
        }
        Some(list)
    }

    /// The archive a registry signs: its list as [`Registry::parse`] reads it.
    pub fn archive(text: &str) -> Option<Vec<u8>> {
        Registry::parse(text)?;
        Some(pack(&[(LIST, text.as_bytes())]))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pack_signed;
    use alloc::format;
    use pinnacle_crypto::ed25519::public;

    const CHECKOUT: [u8; 32] = [1; 32];
    const STORE: [u8; 32] = [2; 32];
    const FRIEND: [u8; 32] = [3; 32];
    const LEAKED: [u8; 32] = [4; 32];

    fn hex(secret: &[u8; 32]) -> String {
        key_hex(&public(secret))
    }

    fn trust() -> Trust {
        let trusted = format!(
            "# keys\n{} this-checkout\n{} pinnacle registry\n",
            hex(&CHECKOUT),
            hex(&STORE)
        );
        Trust::parse(&trusted, "")
    }

    fn app(secret: &[u8; 32]) -> Vec<u8> {
        pack_signed(&[("manifest", b"name=notes\n")], secret)
    }

    fn registry(text: &str, secret: &[u8; 32]) -> Vec<u8> {
        let archive = Registry::archive(text).unwrap();
        let mut signed = archive.clone();
        signed.extend_from_slice(b"PSIG");
        signed.extend_from_slice(&pinnacle_crypto::ed25519::sign(secret, &archive));
        signed
    }

    #[test]
    fn a_package_opens_as_its_publisher_s() {
        let t = trust();
        assert_eq!(t.open(&app(&CHECKOUT)).map(|(_, p)| p), Ok("this-checkout"));
        assert_eq!(t.open(&app(&STORE)).map(|(_, p)| p), Ok("pinnacle"));
        assert_eq!(t.open(&app(&FRIEND)).map(|(_, p)| p), Err(Error::Untrusted));
    }

    #[test]
    fn a_key_alone_on_its_line_is_its_own_publisher() {
        let t = Trust::parse(&hex(&FRIEND), "");
        assert_eq!(t.open(&app(&FRIEND)).unwrap().1, &hex(&FRIEND)[..8]);
    }

    #[test]
    fn a_registry_admits_publishers_and_takes_keys_back() {
        let mut t = trust();
        let list = format!(
            "issued 7\nkey {} friend\nkey {} leaky\nrevoked {}\n",
            hex(&FRIEND),
            hex(&LEAKED),
            hex(&LEAKED)
        );
        let r = Registry::open(&registry(&list, &STORE), &t).unwrap();
        assert_eq!((r.issued, r.publisher.as_str()), (7, "pinnacle"));
        t.admit(&r);
        assert_eq!(t.open(&app(&FRIEND)).unwrap().1, "friend");
        assert_eq!(t.open(&app(&LEAKED)).map(|(_, p)| p), Err(Error::Revoked));
        assert_eq!(t.revoked_text(), hex(&LEAKED) + "\n");
        // Kept apart, revoked stays revoked: a later list leaving it out
        // does not bring it back.
        let again = Trust::parse(
            &format!("{} pinnacle registry\n{} leaky\n", hex(&STORE), hex(&LEAKED)),
            &t.revoked_text(),
        );
        assert_eq!(again.open(&app(&LEAKED)).map(|(_, p)| p), Err(Error::Revoked));
    }

    #[test]
    fn only_a_registry_key_signs_a_list_and_a_name_the_system_gave_stays_its() {
        let t = trust();
        let list = format!("issued 1\nkey {} friend\n", hex(&FRIEND));
        // The checkout's key is trusted, but not as a registry.
        assert_eq!(
            Registry::open(&registry(&list, &CHECKOUT), &t),
            Err(Error::Untrusted)
        );
        let mut t = t;
        let grab = format!(
            "issued 2\nkey {} this-checkout\nkey {} pinnacle\n",
            hex(&FRIEND),
            hex(&LEAKED)
        );
        t.admit(&Registry::open(&registry(&grab, &STORE), &t).unwrap());
        assert_eq!(
            t.open(&app(&FRIEND)).map(|(_, p)| p),
            Err(Error::Untrusted),
            "not the checkout's name"
        );
        assert_eq!(
            t.open(&app(&LEAKED)).unwrap().1,
            "pinnacle",
            "its own name, for a new key"
        );
        // A registry key taken back signs no list.
        let mut t = trust();
        t.admit(&Registry::parse(&format!("revoked {}", hex(&STORE))).unwrap());
        assert_eq!(
            Registry::open(&registry(&list, &STORE), &t),
            Err(Error::Untrusted)
        );
    }

    #[test]
    fn an_app_stays_with_its_publisher() {
        assert!(may_replace(Some("friend"), "friend"));
        assert!(!may_replace(Some("friend"), "pinnacle"));
        assert!(may_replace(None, "pinnacle"), "installed before apps kept theirs");
    }

    #[test]
    fn lists_that_are_not_ones_are_refused() {
        assert!(Registry::parse("issued x").is_none());
        assert!(Registry::parse("key abc friend").is_none());
        assert!(Registry::parse(&format!("key {} Not-A-Name", hex(&FRIEND))).is_none());
        assert!(Registry::parse("grant everything").is_none());
        assert_eq!(Registry::parse("# nothing yet\n").map(|r| r.issued), Some(0));
        assert!(!valid_publisher("") && !valid_publisher("a b") && valid_publisher("pinnacle-os"));
    }
}