use std::path::PathBuf;
use std::process::{Command, Output};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
pub struct Cert {
data: Vec<u8>,
pub fingerprint: String,
pub user_ids: Vec<String>,
pub revoked: bool,
pub expires: Option<SystemTime>,
keys: Vec<(String, Option<SystemTime>)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SigStatus {
Good {
created: Option<SystemTime>,
},
Expired {
created: Option<SystemTime>,
made_while_valid: bool,
},
Revoked,
Bad,
}
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")
}
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))
}
fn file(&self, name: &'static str, data: &[u8]) -> Result<&'static str> {
std::fs::write(self.0.join(name), data)?;
Ok(name)
}
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))
}
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()
}
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();
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)
}
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()
}
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![];
};
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 {
pub fn all_fingerprints(&self) -> Vec<String> {
self.keys.iter().map(|(f, _)| f.clone()).collect()
}
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;
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 {
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("");
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") {
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
}
}
}