#[cfg(feature = "verify-gpg")]
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::Arc;
use ostrya_core::{Checksum, Value, base64};
use rustix::fs::{Mode, OFlags};
#[cfg(feature = "verify-gpg")]
use rustix::io::Errno;
use crate::config::{Remote, SignVerify};
use crate::error::{Error, Result};
#[cfg(feature = "verify-gpg")]
use crate::gpg::read_keyring_fd;
use crate::repo::Repo;
use crate::sign::{
Ed25519Verifier, MAX_KEY_FILE, SignKeys, Verifier, key_text, load_sign_keys, read_key_source,
signatures_for,
};
use super::PullVerify;
const ALL_ENGINES: &[&str] = &[
"ed25519",
#[cfg(feature = "sign-spki")]
"spki",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Defaults {
Config,
Off,
}
pub(crate) struct Verification {
commit: Policy,
summary: Policy,
}
#[derive(Default)]
struct Policy {
gpg: Option<Arc<dyn Verifier>>,
sign: Option<Vec<Arc<dyn Verifier>>>,
}
impl Policy {
fn applies(&self) -> bool {
self.gpg.is_some() || self.sign.is_some()
}
async fn check(&self, subject: &str, payload: &[u8], signatures: Option<&Value>) -> Result<()> {
if let Some(gpg) = &self.gpg {
check_axis(
subject,
"GPG",
std::slice::from_ref(gpg),
payload,
signatures,
)
.await?;
}
if let Some(engines) = &self.sign {
check_axis(subject, "sign-api", engines, payload, signatures).await?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Found {
Valid,
Untrusted,
Nothing,
}
async fn examine(
verifiers: &[Arc<dyn Verifier>],
payload: &[u8],
signatures: Option<&Value>,
) -> Result<Found> {
let mut found = Found::Nothing;
for verifier in verifiers {
let blobs = match signatures {
Some(dict) => signatures_for(dict, verifier.metadata_key()),
None => Vec::new(),
};
if blobs.is_empty() {
continue;
}
found = Found::Untrusted;
if verifier.verify(payload, &blobs).await?.valid {
return Ok(Found::Valid);
}
}
Ok(found)
}
async fn check_axis(
subject: &str,
axis: &str,
verifiers: &[Arc<dyn Verifier>],
payload: &[u8],
signatures: Option<&Value>,
) -> Result<()> {
match examine(verifiers, payload, signatures).await? {
Found::Valid => Ok(()),
Found::Untrusted => Err(Error::Signature(format!(
"{subject}: no {axis} signature is from a trusted key"
))),
Found::Nothing => Err(Error::Signature(format!(
"{subject}: {axis} verification is enabled, but it carries no signature"
))),
}
}
impl Verification {
pub(crate) async fn build(
repo: &Repo,
remote: Option<&str>,
verify: &PullVerify,
defaults: Defaults,
) -> Result<Verification> {
let section = remote.and_then(|name| repo.config().remote(name));
let configured = defaults == Defaults::Config;
let gpg_commit = switch(verify.gpg, || match §ion {
Some(section) if configured => section.gpg_verify(),
None if configured => Ok(true),
_ => Ok(false),
})?;
let gpg_summary = switch(verify.gpg_summary, || match §ion {
Some(section) if configured => section.gpg_verify_summary(),
_ => Ok(false),
})?;
let sign_commit = engines(verify.sign, || match §ion {
Some(section) if configured => section.sign_verify(),
_ => Ok(SignVerify::Off),
})?;
let sign_summary = engines(verify.sign_summary, || match §ion {
Some(section) if configured => section.sign_verify_summary(),
_ => Ok(SignVerify::Off),
})?;
let asks_for_a_check = gpg_commit
|| gpg_summary
|| sign_commit != SignVerify::Off
|| sign_summary != SignVerify::Off;
let Some(name) = remote else {
if asks_for_a_check {
return Err(Error::Pull(
"a signature check takes its keys from a remote's configuration, \
so the pull has to name a remote"
.into(),
));
}
return Ok(Verification {
commit: Policy::default(),
summary: Policy::default(),
});
};
let mut cache = Verifiers::default();
let commit = build_policy(
repo,
name,
section.as_ref(),
&mut cache,
gpg_commit,
&sign_commit,
)
.await?;
let summary = build_policy(
repo,
name,
section.as_ref(),
&mut cache,
gpg_summary,
&sign_summary,
)
.await?;
Ok(Verification { commit, summary })
}
pub(crate) fn checks_commits(&self) -> bool {
self.commit.applies()
}
pub(crate) fn checks_summary(&self) -> bool {
self.summary.applies()
}
pub(crate) async fn check_commit(
&self,
checksum: &Checksum,
bytes: &[u8],
detached: Option<&Value>,
) -> Result<()> {
if !self.commit.applies() {
return Ok(());
}
self.commit
.check(&format!("commit {checksum}"), bytes, detached)
.await
}
pub(crate) async fn check_summary(
&self,
summary: Option<&[u8]>,
signature: Option<&[u8]>,
) -> Result<()> {
if !self.summary.applies() {
return Ok(());
}
let Some(summary) = summary else {
return Err(Error::Signature(
"summary verification is enabled, but no summary is published".into(),
));
};
let Some(signature) = signature else {
return Err(Error::Signature(
"summary verification is enabled, but no summary.sig is published".into(),
));
};
let dict = crate::summary::parse_signature_dict(signature)?;
self.summary
.check("the summary", summary, dict.as_ref())
.await
}
pub(crate) async fn check_delta(
&self,
name: &str,
superblock: &[u8],
signatures: Option<&Value>,
) -> Result<()> {
let Some(engines) = &self.commit.sign else {
return Ok(());
};
match examine(engines, superblock, signatures).await? {
Found::Valid | Found::Nothing => Ok(()),
Found::Untrusted => Err(Error::Signature(format!(
"static delta {name}: no signature is from a trusted key"
))),
}
}
}
fn switch(override_: Option<bool>, configured: impl FnOnce() -> Result<bool>) -> Result<bool> {
match override_ {
Some(value) => Ok(value),
None => configured(),
}
}
fn engines(
override_: Option<bool>,
configured: impl FnOnce() -> Result<SignVerify>,
) -> Result<SignVerify> {
match override_ {
Some(true) => Ok(SignVerify::All),
Some(false) => Ok(SignVerify::Off),
None => configured(),
}
}
#[derive(Default)]
struct Verifiers {
gpg: Option<Arc<dyn Verifier>>,
sign: Vec<(String, Option<Arc<dyn Verifier>>)>,
}
impl Verifiers {
async fn gpg(
&mut self,
repo: &Repo,
remote: &str,
section: Option<&Remote<'_>>,
) -> Result<Arc<dyn Verifier>> {
match &self.gpg {
Some(verifier) => Ok(Arc::clone(verifier)),
None => {
let verifier = gpg_verifier(repo, remote, section).await?;
self.gpg = Some(Arc::clone(&verifier));
Ok(verifier)
}
}
}
async fn sign(
&mut self,
engine: &str,
section: Option<&Remote<'_>>,
) -> Result<Option<Arc<dyn Verifier>>> {
if let Some((_, verifier)) = self.sign.iter().find(|(name, _)| name == engine) {
return Ok(verifier.clone());
}
let verifier = sign_verifier(engine, section).await?;
self.sign.push((engine.to_owned(), verifier.clone()));
Ok(verifier)
}
}
async fn build_policy(
repo: &Repo,
remote: &str,
section: Option<&Remote<'_>>,
cache: &mut Verifiers,
gpg: bool,
sign: &SignVerify,
) -> Result<Policy> {
let mut policy = Policy::default();
if gpg {
policy.gpg = Some(cache.gpg(repo, remote, section).await?);
}
let (names, required): (Vec<String>, bool) = match sign {
SignVerify::Off => (Vec::new(), false),
SignVerify::All => (
ALL_ENGINES.iter().map(|name| (*name).to_owned()).collect(),
false,
),
SignVerify::Engines(names) => (each_engine_once(names), true),
};
if !names.is_empty() {
let mut verifiers: Vec<Arc<dyn Verifier>> = Vec::with_capacity(names.len());
for name in &names {
match cache.sign(name, section).await? {
Some(verifier) => verifiers.push(verifier),
None if required => {
return Err(Error::Signature(format!(
"no trusted key for signature engine '{name}'"
)));
}
None => {}
}
}
if verifiers.is_empty() {
return Err(Error::Signature(
"signature verification is enabled, but no engine of this build \
has a trusted key"
.into(),
));
}
policy.sign = Some(verifiers);
}
Ok(policy)
}
fn each_engine_once(names: &[String]) -> Vec<String> {
let mut kept: Vec<String> = Vec::with_capacity(names.len());
for name in names {
if !kept.iter().any(|held| held == name) {
kept.push(name.clone());
}
}
kept
}
#[cfg(feature = "verify-gpg")]
async fn gpg_verifier(
repo: &Repo,
remote: &str,
section: Option<&Remote<'_>>,
) -> Result<Arc<dyn Verifier>> {
let keyring = read_repo_keyring(repo, remote).await?;
let keypath = match section {
Some(section) => section.gpgkeypath()?,
None => Vec::new(),
};
let remote = remote.to_owned();
let verifier = ostrya_rt::unblock(move || {
crate::gpg::GpgVerifier::for_remote_keyrings(keyring, &remote, &keypath)
})
.await?;
Ok(Arc::new(verifier))
}
#[cfg(not(feature = "verify-gpg"))]
async fn gpg_verifier(
_repo: &Repo,
remote: &str,
_section: Option<&Remote<'_>>,
) -> Result<Arc<dyn Verifier>> {
Err(Error::Unsupported(format!(
"remote '{remote}' asks for GPG verification, which this build has no \
engine for; build with the verify-gpg feature or set gpg-verify=false"
)))
}
enum Engine {
Ed25519,
#[cfg(feature = "sign-spki")]
Spki,
}
async fn sign_verifier(
engine: &str,
section: Option<&Remote<'_>>,
) -> Result<Option<Arc<dyn Verifier>>> {
let kind = match engine {
"ed25519" => Engine::Ed25519,
#[cfg(feature = "sign-spki")]
"spki" => Engine::Spki,
_ => {
return Err(Error::Unsupported(format!(
"signature engine '{engine}' is not one this build verifies with"
)));
}
};
let Some(keys) = sign_keys(engine, section).await? else {
return Ok(None);
};
build_verifier(kind, keys)
}
fn build_verifier(kind: Engine, keys: SignKeys) -> Result<Option<Arc<dyn Verifier>>> {
Ok(match kind {
Engine::Ed25519 => {
let verifier = Ed25519Verifier::from_sign_keys(keys)?;
(!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
}
#[cfg(feature = "sign-spki")]
Engine::Spki => {
let verifier = crate::spki::SpkiVerifier::from_sign_keys(keys)?;
(!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
}
})
}
async fn sign_keys(engine: &str, section: Option<&Remote<'_>>) -> Result<Option<SignKeys>> {
let (inline, path) = match section {
Some(section) => (
section.verification_key(engine)?,
section.verification_file(engine)?,
),
None => (None, None),
};
let engine = engine.to_owned();
ostrya_rt::unblock(move || read_sign_keys(&engine, inline, path)).await
}
fn read_sign_keys(
engine: &str,
inline: Option<String>,
path: Option<String>,
) -> Result<Option<SignKeys>> {
let mut keys = SignKeys::default();
if let Some(inline) = inline {
keys.trusted.push(base64::decode(inline.trim())?);
}
if let Some(path) = path {
for line in read_verification_file(engine, &path)?.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
keys.trusted.push(base64::decode(line)?);
}
}
let system = load_sign_keys(engine)?;
keys.trusted.extend(system.trusted);
keys.revoked.extend(system.revoked);
if keys.trusted.is_empty() {
return Ok(None);
}
Ok(Some(keys))
}
#[cfg(feature = "verify-gpg")]
async fn read_repo_keyring(repo: &Repo, remote: &str) -> Result<Option<Vec<u8>>> {
let repo_fd = repo.repo_fd().try_clone_to_owned()?;
let name = format!("{remote}.trustedkeys.gpg");
ostrya_rt::unblock(move || read_keyring_blocking(repo_fd.as_fd(), &name)).await
}
#[cfg(feature = "verify-gpg")]
fn read_keyring_blocking(repo_fd: BorrowedFd<'_>, name: &str) -> Result<Option<Vec<u8>>> {
let fd = match rustix::fs::openat(
repo_fd,
name,
OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(None),
Err(e) => {
return Err(Error::Signature(format!(
"the keyring '{name}' cannot be opened: {e}"
)));
}
};
read_keyring_fd(fd, name).map(Some)
}
fn read_verification_file(engine: &str, path: &str) -> Result<String> {
let subject = format!("the '{engine}' key file '{path}'");
let fd = rustix::fs::open(
path,
OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|e| Error::Signature(format!("{subject} cannot be read: {e}")))?;
key_text(read_key_source(fd, &subject, MAX_KEY_FILE)?, &subject)
}
#[cfg(test)]
mod tests {
use rustix::fs::FileType;
use super::*;
#[test]
fn all_engines_excludes_the_dummy_engine() {
assert!(ALL_ENGINES.contains(&"ed25519"));
assert!(!ALL_ENGINES.contains(&"dummy"));
}
#[test]
fn switches_resolve_the_override_first() {
assert!(switch(Some(true), || Ok(false)).unwrap());
assert!(!switch(Some(false), || Ok(true)).unwrap());
assert!(switch(None, || Ok(true)).unwrap());
assert_eq!(
engines(Some(true), || Ok(SignVerify::Off)).unwrap(),
SignVerify::All
);
assert_eq!(
engines(Some(false), || Ok(SignVerify::All)).unwrap(),
SignVerify::Off
);
assert_eq!(
engines(None, || Ok(SignVerify::Engines(vec!["ed25519".to_owned()]))).unwrap(),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
}
#[test]
fn unknown_engines_and_empty_key_sets_are_told_apart() {
ostrya_rt::block_on(async {
let Err(err) = sign_verifier("nosuchengine", None).await else {
panic!("an engine this build has no verifier for is refused");
};
assert!(
err.to_string().contains("not one this build verifies with"),
"{err}"
);
if load_sign_keys("ed25519").unwrap().trusted.is_empty() {
assert!(sign_verifier("ed25519", None).await.unwrap().is_none());
}
});
}
#[test]
fn the_dummy_engine_is_refused_by_name() {
ostrya_rt::block_on(async {
let Err(err) = sign_verifier("dummy", None).await else {
panic!("a configuration naming the dummy engine is refused");
};
assert!(
err.to_string().contains("not one this build verifies with"),
"{err}"
);
});
}
#[test]
fn a_revoked_key_leaves_the_engine_without_a_key() {
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let key = base64::decode(PUBLIC_B64).unwrap();
let held = SignKeys {
trusted: vec![key.clone()],
revoked: Vec::new(),
};
assert!(
build_verifier(Engine::Ed25519, held).unwrap().is_some(),
"a key no source revokes builds a verifier"
);
let revoked = SignKeys {
trusted: vec![key.clone()],
revoked: vec![key],
};
assert!(
build_verifier(Engine::Ed25519, revoked).unwrap().is_none(),
"the engine's only key is revoked, so the engine has no key"
);
}
#[test]
fn a_repeated_engine_name_builds_one_verifier() {
use crate::{CreateOptions, RepoMode};
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let config = crate::config::RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=archive\n\
[remote \"origin\"]\nurl=http://localhost/\n\
sign-verify=ed25519,ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
))
.unwrap();
let section = config.remote("origin");
let sign = section.as_ref().unwrap().sign_verify().unwrap();
assert_eq!(
sign,
SignVerify::Engines(vec!["ed25519".to_owned(), "ed25519".to_owned()]),
"the configured value names the engine twice"
);
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-repeat-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let mut cache = Verifiers::default();
build_policy(&repo, "origin", section.as_ref(), &mut cache, false, &sign).await
});
std::fs::remove_dir_all(&dir).unwrap();
let policy = outcome.expect("the configured key builds a policy");
let verifiers = policy.sign.expect("the sign-api axis applies");
assert_eq!(verifiers.len(), 1, "the repeated name holds one verifier");
}
#[test]
fn an_engine_is_read_once_for_both_targets() {
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let config = crate::config::RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=archive\n\
[remote \"origin\"]\nurl=http://localhost/\n\
verification-ed25519-key={PUBLIC_B64}\n"
))
.unwrap();
let section = config.remote("origin");
ostrya_rt::block_on(async {
let mut cache = Verifiers::default();
let first = cache.sign("ed25519", section.as_ref()).await.unwrap();
let second = cache.sign("ed25519", section.as_ref()).await.unwrap();
let (Some(first), Some(second)) = (first, second) else {
panic!("the configured key builds a verifier");
};
assert!(Arc::ptr_eq(&first, &second));
assert_eq!(cache.sign.len(), 1);
});
}
#[test]
fn an_oversized_key_file_is_refused_by_name() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfile-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("keys.ed25519");
std::fs::File::create(&path)
.unwrap()
.set_len(MAX_KEY_FILE + 1)
.unwrap();
let outcome = read_verification_file("ed25519", &path.display().to_string());
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a key file over the ceiling has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("keys.ed25519") && m.contains("ceiling")),
"{err}"
);
}
#[cfg(feature = "verify-gpg")]
#[test]
fn an_oversized_repository_keyring_is_refused_by_name() {
use crate::gpg::MAX_KEYRING;
use crate::{CreateOptions, RepoMode};
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyring-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
std::fs::File::create(root.join("origin.trustedkeys.gpg"))
.unwrap()
.set_len(MAX_KEYRING + 1)
.unwrap();
gpg_verifier(&repo, "origin", None).await.map(|_| ())
});
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a keyring over the ceiling has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
&& m.contains("ceiling")),
"{err}"
);
}
#[cfg(feature = "verify-gpg")]
#[test]
fn a_fifo_repository_keyring_is_refused_by_name() {
use crate::{CreateOptions, RepoMode};
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfifo-repo-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
root.join("origin.trustedkeys.gpg"),
FileType::Fifo,
Mode::from_raw_mode(0o600),
0,
)
.unwrap();
gpg_verifier(&repo, "origin", None).await.map(|_| ())
});
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a fifo at a keyring's name has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
&& m.contains("regular file")),
"{err}"
);
}
#[test]
fn a_fifo_key_file_is_refused_by_name() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfifo-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("keys.ed25519");
rustix::fs::mknodat(
rustix::fs::CWD,
&path,
FileType::Fifo,
Mode::from_raw_mode(0o600),
0,
)
.unwrap();
let outcome = read_verification_file("ed25519", &path.display().to_string());
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a fifo at a key file's name has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("keys.ed25519")
&& m.contains("regular file")),
"{err}"
);
}
}