🏑 index : quine-global/quorum.git

//! OpenPGP certificates of builders, through GnuPG (see `gpg_path`): which
//! keys may sign, and until when.
//!
//! Each call runs gpg in a fresh, empty home directory holding only the
//! certificate in question, so nothing in the user's own keyring counts.
//! GnuPG does the checking that matters: self-signatures, subkey binding and
//! cross-certification, revocations, expiry. quorum reads its machine
//! output (`--with-colons`, `--status-fd`).

use std::path::PathBuf;
use std::process::{Command, Output};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};

/// A builder's certificate, as GnuPG reads it.
pub struct Cert {
    /// The key file it came from (perhaps holding other certificates too).
    data: Vec<u8>,
    pub fingerprint: String,
    pub user_ids: Vec<String>,
    /// Revoked: nothing it signed counts.
    pub revoked: bool,
    pub expires: Option<SystemTime>,
    /// The primary key and its subkeys: fingerprint and expiry.
    keys: Vec<(String, Option<SystemTime>)>,
}

/// How a data signature checked out against a certificate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SigStatus {
    Good {
        created: Option<SystemTime>,
    },
    /// Cryptographically good, but made by a key that has since expired.
    /// `made_while_valid`: the signature predates the expiry.
    Expired {
        created: Option<SystemTime>,
        made_while_valid: bool,
    },
    Revoked,
    Bad,
}

/// $QUORUM_GPG, else gpg on PATH; on Windows, else Gpg4win's or Git for
/// Windows' (which most machines with Git have, off PATH).
fn gpg_path() -> PathBuf {
    if let Some(p) = std::env::var_os("QUORUM_GPG") {
        return p.into();
    }
    #[cfg(windows)]
    {
        let on_path = std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
            .any(|d| d.join("gpg.exe").is_file());
        if !on_path {
            for p in [
                r"C:\Program Files (x86)\GnuPG\bin\gpg.exe",
                r"C:\Program Files\GnuPG\bin\gpg.exe",
                r"C:\Program Files\Git\usr\bin\gpg.exe",
            ] {
                if std::path::Path::new(p).is_file() {
                    return p.into();
                }
            }
        }
    }
    PathBuf::from("gpg")
}

/// A throwaway GnuPG home directory.
struct Home(PathBuf);

impl Home {
    fn new() -> Result<Self> {
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let dir = std::env::temp_dir().join(format!(
            "quorum-gpg-{}-{}",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
        }
        Ok(Home(dir))
    }

    /// Writes a file into the home; gpg gets its bare name.
    fn file(&self, name: &'static str, data: &[u8]) -> Result<&'static str> {
        std::fs::write(self.0.join(name), data)?;
        Ok(name)
    }

    /// Runs gpg inside the home, with relative paths only: Git for Windows'
    /// gpg (MSYS2) misreads `C:\…` paths, and native ones `/c/…`.
    fn gpg(&self, args: &[&str], files: &[&str]) -> Result<Output> {
        Command::new(gpg_path())
            .current_dir(&self.0)
            .args(["--homedir", "."])
            .args(["--batch", "--no-tty", "--no-autostart", "--status-fd", "1"])
            .args(args)
            .args(files)
            .output()
            .context(
                "running gpg: OpenPGP feeds (guix.sigs) need GnuPG (gpg on PATH, or $QUORUM_GPG)",
            )
    }
}

impl Drop for Home {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn epoch(s: &str) -> Option<SystemTime> {
    s.parse::<u64>()
        .ok()
        .filter(|&t| t != 0)
        .map(|t| UNIX_EPOCH + Duration::from_secs(t))
}

/// Status lines (`[GNUPG:] KEYWORD args…`), split into words.
fn status(out: &Output) -> Vec<Vec<String>> {
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter_map(|l| l.strip_prefix("[GNUPG:] "))
        .map(|l| l.split(' ').map(String::from).collect())
        .collect()
}

/// Parses every certificate in an armored (or binary) key file.
pub fn parse_certs(data: &[u8]) -> Result<Vec<Cert>> {
    let home = Home::new()?;
    let f = home.file("key", data)?;
    let out = home.gpg(
        &[
            "--show-keys",
            "--with-colons",
            "--with-subkey-fingerprints",
            "--fixed-list-mode",
        ],
        &[f],
    )?;
    let mut certs: Vec<Cert> = Vec::new();
    // The record a following fpr line belongs to: Some(true) for a primary key.
    let mut pending: Option<(bool, Option<SystemTime>)> = None;
    for line in String::from_utf8_lossy(&out.stdout).lines() {
        let f: Vec<&str> = line.split(':').collect();
        let field = |i: usize| f.get(i).copied().unwrap_or("");
        match field(0) {
            "pub" => {
                certs.push(Cert {
                    data: data.to_vec(),
                    fingerprint: String::new(),
                    user_ids: vec![],
                    revoked: field(1) == "r",
                    expires: epoch(field(6)),
                    keys: vec![],
                });
                pending = Some((true, epoch(field(6))));
            }
            "sub" => pending = Some((false, epoch(field(6)))),
            "fpr" => {
                if let (Some((primary, exp)), Some(c)) = (pending.take(), certs.last_mut()) {
                    let fpr = field(9).to_ascii_uppercase();
                    if primary {
                        c.fingerprint = fpr.clone();
                    }
                    c.keys.push((fpr, exp));
                }
            }
            "uid" if field(1) != "r" => {
                if let Some(c) = certs.last_mut() {
                    c.user_ids.push(unescape(field(9)));
                }
            }
            _ => {}
        }
    }
    if certs.is_empty() {
        bail!(
            "no OpenPGP certificate found{}",
            match String::from_utf8_lossy(&out.stderr).trim() {
                "" => String::new(),
                e => format!(" (gpg: {e})"),
            }
        );
    }
    Ok(certs)
}

/// `--with-colons` escapes `:` and control characters as `\xNN`.
fn unescape(s: &str) -> String {
    let mut out = Vec::new();
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'\\'
            && b.get(i + 1) == Some(&b'x')
            && let Some(v) = s
                .get(i + 2..i + 4)
                .and_then(|h| u8::from_str_radix(h, 16).ok())
        {
            out.push(v);
            i += 4;
            continue;
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Who a signature says made it (fingerprints, else 16-hex key IDs), unverified:
/// only for messages.
pub fn claimed_issuers(armored_sig: &[u8]) -> Vec<String> {
    let Ok(home) = Home::new() else {
        return vec![];
    };
    let (Ok(sig), Ok(data)) = (home.file("sig", armored_sig), home.file("data", b"")) else {
        return vec![];
    };
    let Ok(out) = home.gpg(&["--verify"], &[sig, data]) else {
        return vec![];
    };
    // ERRSIG <keyid> <pkalgo> <hashalgo> <class> <time> <rc> [<fpr>]
    let mut ids: Vec<String> = status(&out)
        .iter()
        .filter(|w| w[0] == "ERRSIG")
        .filter_map(|w| match w.get(7).filter(|f| f.len() == 40) {
            Some(fpr) => Some(fpr.to_ascii_uppercase()),
            None => w.get(1).map(|k| k.to_ascii_uppercase()),
        })
        .collect();
    ids.dedup();
    ids
}

impl Cert {
    /// The primary key's and every subkey's fingerprint.
    pub fn all_fingerprints(&self) -> Vec<String> {
        self.keys.iter().map(|(f, _)| f.clone()).collect()
    }

    /// Checks a detached, armored signature over `content`. A .asc may hold
    /// several signatures; the best one by this certificate wins.
    pub fn check(&self, armored_sig: &[u8], content: &[u8], _now: SystemTime) -> Result<SigStatus> {
        let home = Home::new()?;
        let key = home.file("key", &self.data)?;
        let imported = home.gpg(&["--import"], &[key])?;
        if !imported.status.success() {
            bail!(
                "gpg couldn't import {}: {}",
                self.fingerprint,
                String::from_utf8_lossy(&imported.stderr).trim()
            );
        }
        let sig = home.file("sig", armored_sig)?;
        let data = home.file("data", content)?;
        let out = home.gpg(&["--verify"], &[sig, data])?;
        let mut best = SigStatus::Bad;
        // One NEWSIG group per signature.
        let lines = status(&out);
        for group in lines.split(|w| w[0] == "NEWSIG") {
            let s = self.judge(group);
            if crate::rank(&s) > crate::rank(&best) {
                best = s;
            }
        }
        Ok(best)
    }

    fn judge(&self, group: &[Vec<String>]) -> SigStatus {
        // VALIDSIG <fpr> <date> <created> <expires> <ver> <reserved>
        //          <pkalgo> <hashalgo> <class> <primary fpr>
        let Some(valid) = group.iter().find(|w| w[0] == "VALIDSIG") else {
            return SigStatus::Bad;
        };
        let arg = |i: usize| valid.get(i).map(String::as_str).unwrap_or("");
        // Signed by this certificate, and a data signature (binary or text),
        // not, say, a key certification.
        if !arg(10).eq_ignore_ascii_case(&self.fingerprint) || !matches!(arg(9), "00" | "01") {
            return SigStatus::Bad;
        }
        let created = epoch(arg(3));
        let has = |k: &str| group.iter().any(|w| w[0] == k);
        if has("REVKEYSIG") {
            SigStatus::Revoked
        } else if has("GOODSIG") {
            SigStatus::Good { created }
        } else if has("EXPKEYSIG") {
            // A subkey can't outlive its primary key.
            let signer = arg(1).to_ascii_uppercase();
            let exp = [self.expires]
                .into_iter()
                .chain(
                    self.keys
                        .iter()
                        .filter(|(f, _)| *f == signer)
                        .map(|(_, e)| *e),
                )
                .flatten()
                .min();
            SigStatus::Expired {
                created,
                made_while_valid: matches!((created, exp), (Some(c), Some(e)) if c < e),
            }
        } else {
            SigStatus::Bad
        }
    }
}