//! 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, pub fingerprint: String, pub user_ids: Vec, /// Revoked: nothing it signed counts. pub revoked: bool, pub expires: Option, /// The primary key and its subkeys: fingerprint and expiry. keys: Vec<(String, Option)>, } /// How a data signature checked out against a certificate. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SigStatus { Good { created: Option, }, /// Cryptographically good, but made by a key that has since expired. /// `made_while_valid`: the signature predates the expiry. Expired { created: Option, 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 { 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 { 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 { s.parse::() .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> { 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> { 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 = Vec::new(); // The record a following fpr line belongs to: Some(true) for a primary key. let mut pending: Option<(bool, Option)> = 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 { 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