garage44.eu/jeroen/pinnacle

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

.. /pkg/src/lib.rs

raw

//! Packages: what the Store installs, and what `cargo xtask` builds.
//!
//! A package is a `PPAK` archive of named entries (`manifest`, `files`),
//! then its publisher's signature over the whole archive: `PSIG` and 64
//! bytes of Ed25519. The Store installs a package only when a key it
//! trusts (`/settings/trusted-keys` on the system disk, a hex key a line)
//! made that signature, so neither the package source nor anything between
//! it and the device can change what gets installed.
//!
//! The app's own files (its `program`, and whatever it reads beside it) are
//! not in the package: `files` lists them, each with its size and SHA-256,
//! and the Store fetches each from the package source's `blobs/<sha256>`,
//! checking it against the list as it writes it to disk. So the package
//! stays a few kilobytes whatever the app weighs (Cartopolis is hundreds of
//! megabytes), nothing is held in memory whole, and an update fetches only
//! the files whose hash changed. Signing the list signs the files.

#![no_std]

extern crate alloc;

pub mod system;
pub mod trust;

use alloc::vec::Vec;
use pinnacle_crypto::ed25519;
/// What a fetched file is checked against its [`File::sha256`] with.
pub use pinnacle_crypto::sha2::Sha256;

const ARCHIVE: &[u8; 4] = b"PPAK";
const SIGNATURE: &[u8; 4] = b"PSIG";
/// The signature block at a package's end.
const SIGNED_TAIL: usize = 4 + 64;

/// Why a package is refused.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
    /// Not a package, or cut short.
    Damaged,
    /// No signature at its end.
    Unsigned,
    /// Signed, but by no key trusted here (or changed since).
    Untrusted,
    /// Signed by a key that was taken back (`trust`).
    Revoked,
}

impl Error {
    /// What a person reads.
    pub fn describe(self) -> &'static str {
        match self {
            Error::Damaged => "the package is damaged",
            Error::Unsigned => "the package is not signed",
            Error::Untrusted => "the package is not signed by a trusted publisher",
            Error::Revoked => "the package is signed by a key that was taken back",
        }
    }
}

/// An archive of `entries`.
pub fn pack(entries: &[(&str, &[u8])]) -> Vec<u8> {
    let mut out = ARCHIVE.to_vec();
    out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
    for (name, data) in entries {
        out.extend_from_slice(&(name.len() as u16).to_le_bytes());
        out.extend_from_slice(name.as_bytes());
        out.extend_from_slice(&(data.len() as u32).to_le_bytes());
        out.extend_from_slice(data);
    }
    out
}

/// A signed package: the archive of `entries`, signed with the publisher's
/// secret key.
pub fn pack_signed(entries: &[(&str, &[u8])], secret: &[u8; 32]) -> Vec<u8> {
    let mut out = pack(entries);
    let signature = ed25519::sign(secret, &out);
    out.extend_from_slice(SIGNATURE);
    out.extend_from_slice(&signature);
    out
}

/// The entries of an archive (unsigned: see [`open`]).
pub fn unpack(archive: &[u8]) -> Option<Vec<(&str, &[u8])>> {
    if archive.get(..4)? != ARCHIVE {
        return None;
    }
    let count = u32::from_le_bytes(archive.get(4..8)?.try_into().ok()?);
    let mut at = 8;
    let mut out = Vec::new();
    for _ in 0..count {
        let len = u16::from_le_bytes(archive.get(at..at + 2)?.try_into().ok()?) as usize;
        let name = core::str::from_utf8(archive.get(at + 2..at + 2 + len)?).ok()?;
        at += 2 + len;
        let size = u32::from_le_bytes(archive.get(at..at + 4)?.try_into().ok()?) as usize;
        out.push((name, archive.get(at + 4..at + 4 + size)?));
        at += 4 + size;
    }
    // Nothing may follow the entries: a signature covers all of it.
    (at == archive.len()).then_some(out)
}

/// The entries of a signed package, once its signature is checked against
/// the `trusted` keys.
pub fn open<'a>(package: &'a [u8], trusted: &[[u8; 32]]) -> Result<Vec<(&'a str, &'a [u8])>, Error> {
    let (_, archive) = verify(package, trusted)?;
    unpack(archive).ok_or(Error::Damaged)
}

/// Which of `keys` signed `package`, and the archive it signed.
fn verify<'a>(package: &'a [u8], keys: &[[u8; 32]]) -> Result<(usize, &'a [u8]), Error> {
    let Some(split) = package.len().checked_sub(SIGNED_TAIL) else {
        return Err(Error::Damaged);
    };
    let (archive, tail) = package.split_at(split);
    if &tail[..4] != SIGNATURE {
        return Err(if package.starts_with(ARCHIVE) {
            Error::Unsigned
        } else {
            Error::Damaged
        });
    }
    let signature: &[u8; 64] = tail[4..].try_into().unwrap();
    let signer = keys
        .iter()
        .position(|key| ed25519::verify(key, archive, signature))
        .ok_or(Error::Untrusted)?;
    Ok((signer, archive))
}

/// Keys from `/settings/trusted-keys`: 64 hex digits a line; other lines
/// are skipped.
pub fn parse_keys(text: &str) -> Vec<[u8; 32]> {
    text.lines()
        .filter_map(|line| {
            let line = line.trim().as_bytes();
            if line.len() != 64 {
                return None;
            }
            let mut key = [0u8; 32];
            for (i, pair) in line.chunks(2).enumerate() {
                let digit = |c: u8| (c as char).to_digit(16);
                key[i] = (digit(pair[0])? * 16 + digit(pair[1])?) as u8;
            }
            Some(key)
        })
        .collect()
}

/// A key as `parse_keys` reads it.
pub fn key_hex(key: &[u8; 32]) -> alloc::string::String {
    key.iter().map(|b| alloc::format!("{b:02x}")).collect()
}

/// One of an app's files, as its package's `files` entry lists it: a line
/// `<sha256 in hex> <size> <path>`, the path within the app's folder.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct File<'a> {
    pub sha256: [u8; 32],
    pub size: u64,
    pub path: &'a str,
}

impl File<'_> {
    /// Its name in the package source's `blobs/`.
    pub fn blob(&self) -> alloc::string::String {
        key_hex(&self.sha256)
    }
}

/// What the Store writes beside an app's files itself (`publisher`: whose
/// app it is, `trust::may_replace`): never one of them.
pub const RESERVED: [&str; 3] = ["manifest", "files", "publisher"];

/// The files a `files` entry lists; None when a line is not one, a path
/// could leave the app's folder or names what the Store writes itself
/// ([`RESERVED`]), or a path comes twice.
pub fn files(text: &str) -> Option<Vec<File<'_>>> {
    let mut out: Vec<File> = Vec::new();
    for line in text.lines().filter(|l| !l.trim().is_empty()) {
        let mut fields = line.splitn(3, ' ');
        let sha256 = parse_keys(fields.next()?).pop()?;
        let size = fields.next()?.parse().ok()?;
        let path = fields.next()?;
        if !safe_path(path) || RESERVED.contains(&path) || out.iter().any(|f| f.path == path) {
            return None;
        }
        out.push(File { sha256, size, path });
    }
    Some(out)
}

/// A `files` entry for these files, as [`files`] reads it.
pub fn files_text(files: &[File]) -> alloc::string::String {
    files
        .iter()
        .map(|f| alloc::format!("{} {} {}\n", f.blob(), f.size, f.path))
        .collect()
}

/// A path within an app's folder: relative, `/` between its parts, none of
/// them empty, `.` or `..`, and nothing that would end a line.
fn safe_path(path: &str) -> bool {
    !path.is_empty()
        && path.len() <= 255
        && !path.contains(['\\', '\n', '\r', '\0'])
        && path
            .split('/')
            .all(|part| !part.is_empty() && part != "." && part != "..")
}

/// What an app may do beyond its own folder, as its manifest says:
/// `network=yes`, `gpu=yes`, and `effects=` the most any of its verbs does
/// (`reads`, `own`, `shared`, `out`, `final`; `docs/agent-environment.md`).
/// The Store shows them before it installs, from the catalog, and refuses a
/// package whose signed manifest asks for more than the catalog said.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rights {
    pub network: bool,
    pub gpu: bool,
    /// Index into [`EFFECTS`]; 0 (only reads) when the manifest says none.
    pub effects: usize,
}

/// The effect classes, least first.
pub const EFFECTS: [&str; 5] = ["reads", "own", "shared", "out", "final"];

impl Rights {
    /// From a manifest's `key=value` lines; None for an effect class that
    /// is not one.
    pub fn of_manifest(text: &str) -> Option<Rights> {
        let field = |key: &str| {
            text.lines()
                .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
                .map(str::trim)
        };
        Some(Rights {
            network: field("network") == Some("yes"),
            gpu: field("gpu") == Some("yes"),
            effects: match field("effects") {
                None => 0,
                Some(e) => EFFECTS.iter().position(|n| *n == e)?,
            },
        })
    }

    /// As a catalog writes them: `network,gpu,out`, empty for none.
    pub fn to_catalog(self) -> alloc::string::String {
        let mut parts = Vec::new();
        if self.network {
            parts.push("network");
        }
        if self.gpu {
            parts.push("gpu");
        }
        if self.effects > 0 {
            parts.push(EFFECTS[self.effects]);
        }
        parts.join(",")
    }

    pub fn of_catalog(text: &str) -> Option<Rights> {
        let mut rights = Rights::default();
        for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) {
            match part {
                "network" => rights.network = true,
                "gpu" => rights.gpu = true,
                e => rights.effects = EFFECTS.iter().position(|n| *n == e)?,
            }
        }
        Some(rights)
    }

    /// Whether these ask for nothing `shown` did not.
    pub fn within(self, shown: Rights) -> bool {
        (!self.network || shown.network) && (!self.gpu || shown.gpu) && self.effects <= shown.effects
    }

    /// What the person reads before installing.
    pub fn describe(self) -> alloc::string::String {
        let mut parts = Vec::new();
        if self.network {
            parts.push("the network");
        }
        if self.gpu {
            parts.push("the GPU");
        }
        parts.push(
            [
                "",
                "changes its own data",
                "changes what others see",
                "sends out of the device",
                "does what cannot be undone",
            ][self.effects],
        );
        let parts: Vec<&str> = parts.into_iter().filter(|p| !p.is_empty()).collect();
        if parts.is_empty() {
            "Only its own folder".into()
        } else {
            let mut text = alloc::string::String::from("Uses ");
            text += &parts.join(", ");
            text
        }
    }
}

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

    const PUBLISHER: [u8; 32] = [7; 32];
    const STRANGER: [u8; 32] = [9; 32];

    fn package() -> Vec<u8> {
        pack_signed(
            &[("manifest", b"title=Paint\n"), ("program", &[1, 2, 3, 4])],
            &PUBLISHER,
        )
    }

    #[test]
    fn a_signed_package_opens_with_its_publishers_key() {
        let trusted = [ed25519::public(&PUBLISHER)];
        let package = package();
        let entries = open(&package, &trusted).unwrap();
        assert_eq!(
            entries,
            [
                ("manifest", &b"title=Paint\n"[..]),
                ("program", &[1, 2, 3, 4][..])
            ]
        );
    }

    #[test]
    fn a_changed_byte_is_refused() {
        let trusted = [ed25519::public(&PUBLISHER)];
        let mut package = package();
        let program = package.len() - SIGNED_TAIL - 2;
        package[program] ^= 1;
        assert_eq!(open(&package, &trusted), Err(Error::Untrusted));
    }

    #[test]
    fn another_publishers_package_is_refused() {
        let trusted = [ed25519::public(&PUBLISHER)];
        let forged = pack_signed(&[("manifest", b"title=Paint\n")], &STRANGER);
        assert_eq!(open(&forged, &trusted), Err(Error::Untrusted));
        assert_eq!(open(&forged, &[]), Err(Error::Untrusted));
    }

    #[test]
    fn unsigned_and_damaged_packages_are_refused() {
        let trusted = [ed25519::public(&PUBLISHER)];
        let unsigned = pack(&[("manifest", b"title=Paint\n"), ("program", &[0; 80])]);
        assert_eq!(open(&unsigned, &trusted), Err(Error::Unsigned));
        assert_eq!(open(b"PPAK", &trusted), Err(Error::Damaged));
        assert_eq!(open(&[0; 100], &trusted), Err(Error::Damaged));
    }

    /// The hosted package sources are signed on the server with OpenSSL
    /// (`openssl pkeyutl -sign -rawin`), not with this crate: the same
    /// signature, Ed25519 being deterministic. Made with OpenSSL 3 from
    /// this archive and the key's 32-byte seed.
    #[test]
    fn a_package_signed_by_openssl_opens() {
        const SEED: &str = "41589310fb98aac06e571a7805ba9806716da08e6cb645650f9bde934578b4a5";
        const SIGNATURE: &str = "fa8be6a556a7f473ab7aab8972ce01bff693e94b542f2ce49d44bdc0a0f00e78\
                                 90ca7725ae38dc6a16d275b06ed9c511ab4daede712ce1316334eb675a1f700c";
        let seed = parse_keys(SEED)[0];
        let archive = pack(&[("manifest", b"title=Paint\n")]);
        let mut signed = archive.clone();
        signed.extend_from_slice(b"PSIG");
        for pair in SIGNATURE.as_bytes().chunks(2) {
            signed.push(u8::from_str_radix(core::str::from_utf8(pair).unwrap(), 16).unwrap());
        }
        assert_eq!(signed, pack_signed(&[("manifest", b"title=Paint\n")], &seed));
        let trusted = [ed25519::public(&seed)];
        assert_eq!(
            open(&signed, &trusted).unwrap(),
            [("manifest", &b"title=Paint\n"[..])]
        );
    }

    #[test]
    fn files_read_back_and_stay_in_the_apps_folder() {
        let listed = [
            File {
                sha256: [1; 32],
                size: 141 << 20,
                path: "program",
            },
            File {
                sha256: [2; 32],
                size: 0,
                path: "assets/shaders/sky.wesl",
            },
        ];
        let text = files_text(&listed);
        assert_eq!(files(&text).unwrap(), listed);
        assert_eq!(listed[0].blob(), "01".repeat(32));
        let line = |path: &str| alloc::format!("{} 1 {path}\n", "ab".repeat(32));
        for bad in ["../x", "/etc/x", "a//b", "a/./b", "manifest", "files", "a\\b"] {
            assert_eq!(files(&line(bad)), None, "{bad}");
        }
        assert_eq!(files(&(line("a") + &line("a"))), None);
        assert_eq!(files("abc 1 program\n"), None);
        assert!(files(&line("program with a space")).is_some());
    }

    #[test]
    fn keys_read_back() {
        let key = ed25519::public(&PUBLISHER);
        let text = alloc::format!("# the publisher\n{}\nnot a key\n", key_hex(&key));
        assert_eq!(parse_keys(&text), [key]);
    }

    #[test]
    fn rights_from_a_manifest_and_a_catalog() {
        let r = Rights::of_manifest("name=x\nnetwork=yes\neffects=out\n").unwrap();
        assert_eq!(
            r,
            Rights {
                network: true,
                gpu: false,
                effects: 3
            }
        );
        assert_eq!(r.to_catalog(), "network,out");
        assert_eq!(Rights::of_catalog("network,out"), Some(r));
        assert_eq!(Rights::of_catalog(""), Some(Rights::default()));
        assert_eq!(Rights::of_manifest("effects=everything"), None);
        assert_eq!(r.describe(), "Uses the network, sends out of the device");
        assert_eq!(Rights::default().describe(), "Only its own folder");
        assert!(Rights::default().within(r));
        assert!(!r.within(Rights::default()));
        let gpu = Rights { gpu: true, ..r };
        assert!(!gpu.within(r));
    }
}