use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use sha2::{Digest, Sha256, Sha512};
use crate::base::{
base_for, brief, canonical, canonical_request, check_covered, check_label, component,
components, identity, lines_for, req, shown, spec_of, Asked, Message, Request, SignatureParams,
CONTENT_DIGEST, DEFAULT_COVERED, MAX_FIELD_BYTES,
};
use crate::errors::{Error, Kind, Result};
use crate::keys::{aid_of, b64std, public_key, raw_keyid, verifying_key, well_formed_aid, Key};
use crate::sfv::{parse_dictionary, serialize_inner_list, InnerList, Item, Member, Value};
pub const ALG: &str = "ed25519";
pub const DEFAULT_SKEW: i64 = 5;
pub const REQUEST_MINIMUM: [&str; 3] = ["@method", "@path", "@query"];
pub const RESPONSE_MINIMUM: [&str; 4] = [
"@status",
"\"@method\";req",
"\"@path\";req",
"\"@query\";req",
];
pub const DEFAULT_MINIMUM: [&str; 4] = ["@method", "@authority", "@path", "@query"];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Minimum {
#[default]
Default,
Off,
Of(Vec<String>),
}
impl Minimum {
pub fn of<I, S>(components: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Minimum::Of(components.into_iter().map(Into::into).collect())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MaxAge {
#[default]
Unstated,
Unchecked,
Seconds(i64),
}
impl MaxAge {
pub fn seconds(seconds: i64) -> Self {
MaxAge::Seconds(seconds)
}
fn seconds_or_none(self) -> Option<i64> {
match self {
MaxAge::Seconds(seconds) => Some(seconds),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Authorities {
#[default]
Unstated,
Unchecked,
Served(BTreeSet<String>),
}
impl Authorities {
pub fn served<I, S>(hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Authorities::Served(hosts.into_iter().map(Into::into).collect())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ExpectedKeyid {
#[default]
Unstated,
Unchecked,
Is(String),
}
impl ExpectedKeyid {
pub fn is(keyid: impl Into<String>) -> Self {
ExpectedKeyid::Is(keyid.into())
}
}
const SIGNATURE_LENGTH: usize = 64;
pub const MAX_DICTIONARY_MEMBERS: usize = 16;
pub const MAX_INNER_LIST_ITEMS: usize = 64;
pub const MAX_PARAMETERS: usize = 16;
pub type Resolver = Arc<dyn Fn(&str) -> Result<Option<[u8; 32]>> + Send + Sync>;
pub fn content_digest(body: &[u8]) -> String {
format!("sha-256=:{}:", b64std(&Sha256::digest(body)))
}
fn now_or(now: Option<i64>) -> i64 {
now.unwrap_or_else(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
})
}
fn has_content(body: Option<&[u8]>) -> bool {
body.is_some_and(|b| !b.is_empty())
}
#[derive(Debug, Default, Clone)]
pub struct SignOptions {
pub body: Option<Vec<u8>>,
pub covered: Option<Vec<String>>,
pub created: Option<i64>,
pub label: Option<String>,
pub expires: Option<i64>,
pub nonce: Option<String>,
pub tag: Option<String>,
pub keyid: Option<String>,
pub minimum: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verdict {
pub aid: String,
pub covered: Vec<String>,
pub keyid: Option<String>,
}
#[derive(Default, Clone)]
pub struct VerifyOptions {
pub max_age: MaxAge,
pub body: Option<Vec<u8>>,
pub expected_aid: Option<String>,
pub skew: Option<i64>,
pub now: Option<i64>,
pub resolve: Option<Resolver>,
pub minimum: Minimum,
pub expected_keyid: ExpectedKeyid,
pub authorities: Authorities,
}
impl fmt::Debug for VerifyOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VerifyOptions")
.field("max_age", &self.max_age)
.field("body", &self.body)
.field("expected_aid", &self.expected_aid)
.field("skew", &self.skew)
.field("now", &self.now)
.field("resolve", &self.resolve.as_ref().map(|_| "<resolver>"))
.field("minimum", &self.minimum)
.field("expected_keyid", &self.expected_keyid)
.field("authorities", &self.authorities)
.finish()
}
}
fn stated(
minimum: &Minimum,
default: Option<&[&str]>,
floor: &[&str],
) -> Result<Option<Vec<Item>>> {
match minimum {
Minimum::Default => {
let default = default.map(|d| d.iter().map(|s| s.to_string()).collect::<Vec<_>>());
floored(default.as_deref(), floor)
}
Minimum::Off => Ok(None),
Minimum::Of(given) => floored(Some(given), floor),
}
}
fn check_expected_keyid(expected: &ExpectedKeyid, required: bool) -> Result<()> {
match expected {
ExpectedKeyid::Unstated if required => Err(Error::new(
Kind::InvalidArgument,
"expected_keyid is a required decision: state the AID this client is talking to, \
such as ExpectedKeyid::is(aid), or ExpectedKeyid::Unchecked to accept any signer and \
read it from the verdict.",
)),
ExpectedKeyid::Is(keyid) if keyid.is_empty() => Err(Error::new(
Kind::InvalidArgument,
"expected_keyid is empty, which names no AID; pass ExpectedKeyid::Unchecked to accept \
any signer and read it from the verdict.",
)),
_ => Ok(()),
}
}
fn check_authorities(authorities: &Authorities) -> Result<()> {
match authorities {
Authorities::Unstated => Err(Error::new(
Kind::InvalidArgument,
"authorities is a required decision: state the hosts this verifier serves, such as \
Authorities::served([\"api.example.com\"]), or Authorities::Unchecked to decline the \
check.",
)),
Authorities::Served(hosts) if hosts.is_empty() => Err(Error::new(
Kind::InvalidArgument,
"authorities is empty, which serves no host at all; pass Authorities::Unchecked to \
decline the check.",
)),
_ => Ok(()),
}
}
fn floored(minimum: Option<&[String]>, floor: &[&str]) -> Result<Option<Vec<Item>>> {
let Some(minimum) = minimum else {
return Ok(None);
};
let given = components(minimum)?;
let have: Vec<_> = given.iter().map(identity).collect();
let mut missing = Vec::new();
for spec in floor {
if !have.contains(&identity(&component(spec)?)) {
missing.push(*spec);
}
}
if !missing.is_empty() {
return Err(Error::new(
Kind::InvalidArgument,
format!(
"A minimum covered set must include the profile's own, {}; this one leaves out {}. \
State no minimum to take the default, or opt out of any.",
floor.join(", "),
missing.join(", ")
),
));
}
Ok(Some(given))
}
fn binds_request_digest(items: &[Item]) -> bool {
items
.iter()
.any(|item| identity(item) == (CONTENT_DIGEST.to_string(), ";req".to_string()))
}
fn covers_body(items: &[Item]) -> bool {
items.iter().any(|item| {
let (name, params) = identity(item);
name == CONTENT_DIGEST && params.is_empty()
})
}
fn cover_body(
items: &mut Vec<Item>,
sending: &mut BTreeMap<String, String>,
body: Option<&[u8]>,
chosen: bool,
) -> Result<()> {
let Some(body) = body else {
return Ok(());
};
if let Some(given) = sending.get(CONTENT_DIGEST) {
read_digest(Some(given))
.and_then(|recognized| compare_digest(&recognized, Some(body)))
.map_err(|refused| {
Error::new(
Kind::InvalidArgument,
format!(
"The Content-Digest supplied with this body is not one a verifier would \
accept for it: {refused} Omit it and fiki computes one, or supply the \
body it describes."
),
)
})?;
}
if !covers_body(items) {
if chosen {
return Err(Error::new(
Kind::UncoveredBody,
"This message carries a body, but the covered components do not include \
\"content-digest\", so the signature would not bind the body. Add it to the \
covered set, or omit the body if it is genuinely not part of what you are signing.",
));
}
items.push(component(CONTENT_DIGEST)?);
}
sending
.entry(CONTENT_DIGEST.into())
.or_insert_with(|| content_digest(body));
Ok(())
}
fn label_of(opts: &SignOptions) -> &str {
opts.label.as_deref().unwrap_or("sig")
}
fn params_for(key: &Key, opts: &SignOptions) -> SignatureParams {
SignatureParams {
created: Some(opts.created.unwrap_or_else(|| now_or(None))),
keyid: Some(opts.keyid.clone().unwrap_or_else(|| key.keyid())),
alg: Some(ALG.into()),
expires: opts.expires,
nonce: opts.nonce.clone(),
tag: opts.tag.clone(),
}
}
fn signed(
key: &Key,
base: &[u8],
opts: &SignOptions,
sending: &BTreeMap<String, String>,
given: &BTreeMap<String, String>,
) -> BTreeMap<String, String> {
let signature = key.sign(base);
let text = String::from_utf8_lossy(base);
let marker = "\"@signature-params\": ";
let rendered = &text[text.rfind(marker).map(|at| at + marker.len()).unwrap_or(0)..];
let label = label_of(opts);
let mut out = BTreeMap::new();
out.insert("Signature-Input".into(), format!("{label}={rendered}"));
out.insert(
"Signature".into(),
format!("{label}=:{}:", b64std(&signature)),
);
if let Some(made) = sending.get(CONTENT_DIGEST) {
if !given.contains_key(CONTENT_DIGEST) {
out.insert("Content-Digest".into(), made.clone());
}
}
out
}
pub fn sign_request(
key: &Key,
method: &str,
url: &str,
headers: &BTreeMap<String, String>,
opts: &SignOptions,
) -> Result<BTreeMap<String, String>> {
check_label(label_of(opts))?;
let minimum = floored(opts.minimum.as_deref(), &REQUEST_MINIMUM)?;
let headers = &canonical(headers)?;
let mut sending = headers.clone();
let chosen = opts.covered.is_some();
let mut items = match &opts.covered {
Some(covered) => components(covered)?,
None => components(&DEFAULT_COVERED.map(String::from))?,
};
cover_body(&mut items, &mut sending, opts.body.as_deref(), chosen)?;
if let Some(minimum) = &minimum {
let has_body = request_has_body(&sending, opts.body.as_deref());
check_minimum(&items, minimum, has_body, false)?;
}
let base = base_for(
&items,
&Message::request(method, url, &sending, false)?,
false,
¶ms_for(key, opts),
)?;
Ok(signed(key, &base, opts, &sending, headers))
}
pub fn sign_response(
key: &Key,
status: u16,
request: Option<&Request>,
headers: &BTreeMap<String, String>,
opts: &SignOptions,
) -> Result<BTreeMap<String, String>> {
check_label(label_of(opts))?;
let minimum = floored(opts.minimum.as_deref(), &RESPONSE_MINIMUM)?;
let headers = &canonical(headers)?;
let asked = canonical_request(request)?;
let request = asked.as_ref();
check_announced_body(request)?;
let mut sending = headers.clone();
let chosen = opts.covered.is_some();
let had_body = request.is_some_and(|r| has_content(r.body));
let covered = opts.covered.clone().unwrap_or_else(|| {
let mut covered = vec!["@status".to_string()];
if request.is_some() {
covered.extend(["@method", "@path", "@query"].map(req));
}
covered
});
let mut items = components(&covered)?;
cover_body(&mut items, &mut sending, opts.body.as_deref(), chosen)?;
if let (false, true, Some(request)) = (chosen, had_body, request) {
if !request.headers.contains_key(CONTENT_DIGEST) {
return Err(Error::new(
Kind::UncoveredBody,
"The request this response answers carried a body and no Content-Digest, so the \
response has nothing to bind that body with. Sign the request with a digest \
first, or name the covered components yourself.",
));
}
items.push(component(&req(CONTENT_DIGEST))?);
}
if let Some(minimum) = &minimum {
check_minimum(&items, minimum, has_content(opts.body.as_deref()), had_body)?;
}
if let Some(Asked {
headers: asked,
body: Some(content),
..
}) = request
{
if binds_request_digest(&items) {
let recognized = read_digest(asked.get(CONTENT_DIGEST))?;
compare_digest(&recognized, Some(content))?;
}
}
let base = base_for(
&items,
&Message::response(status, &sending, request, false)?,
true,
¶ms_for(key, opts),
)?;
Ok(signed(key, &base, opts, &sending, headers))
}
pub fn verify_request(
method: &str,
url: &str,
headers: &BTreeMap<String, String>,
opts: &VerifyOptions,
) -> Result<Verdict> {
check_window(opts)?;
check_expected_keyid(&opts.expected_keyid, false)?;
check_authorities(&opts.authorities)?;
let minimum = stated(&opts.minimum, Some(&DEFAULT_MINIMUM), &REQUEST_MINIMUM)?;
let headers = &canonical(headers)?;
verify(
&Message::request(method, url, headers, true)?,
headers,
None,
opts,
minimum,
)
}
pub fn verify_response(
status: u16,
headers: &BTreeMap<String, String>,
request: Option<&Request>,
opts: &VerifyOptions,
) -> Result<Verdict> {
check_window(opts)?;
check_expected_keyid(&opts.expected_keyid, true)?;
let minimum = stated(&opts.minimum, Some(&RESPONSE_MINIMUM), &RESPONSE_MINIMUM)?;
if matches!(opts.authorities, Authorities::Served(_)) {
return Err(Error::new(
Kind::InvalidArgument,
"A response has no @authority of its own, so served authorities do not apply to one; \
pass authorities when verifying the request.",
));
}
let headers = &canonical(headers)?;
let asked = canonical_request(request)?;
let request = asked.as_ref();
check_announced_body(request)?;
if status == 401 && headers.get("signature").map_or(true, String::is_empty) {
return Err(Error::new(
Kind::Unauthenticated,
"The server answered 401 without signing the answer, so the request was not \
authenticated and the body of the refusal cannot be trusted.",
));
}
verify(
&Message::response(status, headers, request, true)?,
headers,
Some(request),
opts,
minimum,
)
}
fn verify(
message: &Message,
headers: &BTreeMap<String, String>,
response: Option<Option<&Asked>>,
opts: &VerifyOptions,
minimum: Option<Vec<Item>>,
) -> Result<Verdict> {
if opts.expected_aid.is_some() && opts.resolve.is_some() {
return Err(Error::new(
Kind::InvalidArgument,
"Pass expected_aid or resolve, not both; each decides the key alone.",
));
}
let request = response.flatten();
let found = headers;
let (inner, signature) = read(found, opts.expected_aid.is_none(), minimum.is_some())?;
let items = &inner.items;
check_covered(items, response.is_some())?;
if let Some(minimum) = &minimum {
let has_body = match response {
Some(_) => has_content(opts.body.as_deref()),
None => request_has_body(found, opts.body.as_deref()),
};
let request_had_body = request.is_some_and(|r| has_content(r.body));
check_minimum(items, minimum, has_body, request_had_body)?;
}
if matches!(opts.authorities, Authorities::Served(_)) {
check_minimum(items, &[component("@authority")?], false, false)?;
}
let keyid = match inner.param("keyid") {
Some(Value::Text(keyid)) => Some(keyid.clone()),
_ => None,
};
let local = local_key(opts, keyid.as_deref())?;
if let ExpectedKeyid::Is(expected) = &opts.expected_keyid {
if keyid.as_ref() != Some(expected) {
let signer = keyid.clone().unwrap_or_default();
return Err(Error::detailed(
Kind::UnknownKey,
format!(
"This message is signed by {}, and the one expected is {}.",
shown(&signer),
shown(expected)
),
signer,
));
}
}
let (public, aid) = match local {
Local::Found(public, aid) => (public, aid),
Local::Resolve(resolver, keyid) => resolved(resolver, keyid)?,
};
if let Some(Value::Text(alg)) = inner.param("alg") {
if alg != ALG {
return Err(Error::detailed(
Kind::UnsupportedAlgorithm,
format!(
"This signature is made with {}, and fiki verifies only {ALG}.",
shown(alg)
),
alg,
));
}
}
let mut lines = lines_for(items, message)?;
lines.push(format!(
"\"@signature-params\": {}",
serialize_inner_list(&inner)
));
public
.verify(
lines.join("\n").as_bytes(),
&Signature::from_bytes(&signature),
)
.map_err(|_| {
Error::new(
Kind::SignatureMismatch,
"The signature does not match this message under the signer's key, so the \
message cannot be treated as authentic.",
)
})?;
if let Authorities::Served(served) = &opts.authorities {
for item in items.iter().filter(|i| i.text() == Some("@authority")) {
let value = crate::base::value_of(item, message)?;
if !served.contains(&value) {
return Err(Error::detailed(
Kind::SignatureMismatch,
format!(
"The signature covers the authority {}, which this verifier does not \
serve, so it was signed for somebody else.",
shown(&value)
),
value,
));
}
}
}
check_freshness(&inner, opts)?;
let mut digests = Vec::new();
if covers_body(items) {
digests.push((found.get(CONTENT_DIGEST), opts.body.as_deref()));
}
let asked = request.map(|r| &r.headers);
if let (Some(request), Some(asked)) = (request, &asked) {
if binds_request_digest(items) {
let Some(content) = request.body else {
return Err(Error::new(
Kind::InvalidArgument,
"The response covers \"content-digest\";req, so the request body it binds \
must be supplied in Request::body to be checked; it was not.",
));
};
digests.push((asked.get(CONTENT_DIGEST), Some(content)));
}
}
let parsed = digests
.into_iter()
.map(|(header, content)| Ok((read_digest(header)?, content)))
.collect::<Result<Vec<_>>>()?;
for (recognized, content) in &parsed {
compare_digest(recognized, *content)?;
}
Ok(Verdict {
aid,
covered: items.iter().map(spec_of).collect(),
keyid,
})
}
fn check_announced_body(request: Option<&Asked>) -> Result<()> {
let Some(r) = request else { return Ok(()) };
let announced = match r.body {
None => request_has_body(&r.headers, None),
Some([]) => {
let mut lengths = r.headers.clone();
lengths.remove("transfer-encoding");
request_has_body(&lengths, None)
}
Some(_) => false,
};
if announced {
return Err(Error::new(
Kind::InvalidArgument,
"The request this response answers announces a body in its headers, by its \
Content-Length or Transfer-Encoding, and Request.body does not carry it, so whether \
the response must bind that body cannot be decided. Pass the request body, or a \
Request without those headers.",
));
}
Ok(())
}
fn request_has_body(found: &BTreeMap<String, String>, body: Option<&[u8]>) -> bool {
if has_content(body) || found.contains_key("transfer-encoding") {
return true;
}
match found
.get("content-length")
.map(|l| l.trim_matches([' ', '\t']))
{
None => false,
Some(length) => {
length.is_empty()
|| !length.bytes().all(|b| b.is_ascii_digit())
|| length.bytes().any(|b| b != b'0')
}
}
}
fn check_minimum(
items: &[Item],
minimum: &[Item],
has_body: bool,
request_had_body: bool,
) -> Result<()> {
let have: Vec<_> = items.iter().map(identity).collect();
let mut required = minimum.to_vec();
if has_body {
required.push(component(CONTENT_DIGEST)?);
}
if request_had_body {
required.push(component(&req(CONTENT_DIGEST))?);
}
match required.iter().find(|item| !have.contains(&identity(item))) {
None => Ok(()),
Some(item) => Err(Error::detailed(
Kind::InsufficientCoverage,
format!(
"The signature does not cover {}, which this verifier requires, so it is refused \
even though it may be valid: a signature over too little is a signature over what \
an intermediary is free to change.",
brief(&spec_of(item))
),
spec_of(item),
)),
}
}
fn read(
found: &BTreeMap<String, String>,
require_keyid: bool,
require_created: bool,
) -> Result<(InnerList, [u8; SIGNATURE_LENGTH])> {
let present = |name: &str| found.get(name).filter(|v| !v.is_empty());
let raw_signature = present("signature").ok_or_else(|| {
Error::new(
Kind::MissingSignature,
"This message has no Signature header, so there is nothing to verify.",
)
})?;
let raw_input = present("signature-input").ok_or_else(|| {
Error::new(
Kind::MissingSignatureInput,
"This message has no Signature-Input header, so there is no way to know which \
components a signature would cover.",
)
})?;
let signatures = parse_bounded(raw_signature, "Signature", Kind::MalformedSignature)?;
let mut values = Vec::new();
for (label, member) in &signatures {
match member {
Member::Item(Item {
value: Value::Bytes(raw),
..
}) => values.push((label, raw)),
_ => {
return Err(Error::new(
Kind::MalformedSignature,
"RFC 9421 carries a signature as an RFC 8941 byte sequence, wrapped in \
colons; this Signature header carries something else.",
))
}
}
}
let inputs = parse_bounded(raw_input, "Signature-Input", Kind::MalformedSignatureInput)?;
let mut lists = Vec::new();
for (label, member) in &inputs {
lists.push((label, check_input(member, require_keyid, require_created)?));
}
if lists.len() != 1 || values.len() != 1 {
return Err(Error::new(
Kind::MalformedSignatureLabel,
format!(
"fiki verifies a message carrying exactly one signature; this one declares {} in \
Signature-Input and {} in Signature.",
lists.len(),
values.len()
),
));
}
let (label, list) = lists.remove(0);
let Some((_, value)) = values.into_iter().find(|(name, _)| *name == label) else {
return Err(Error::detailed(
Kind::MissingSignatureLabel,
format!(
"The Signature header carries no entry labelled {}, so the covered components \
describe a signature that is not here.",
shown(label)
),
label,
));
};
let value: [u8; SIGNATURE_LENGTH] = value.as_slice().try_into().map_err(|_| {
Error::new(
Kind::MalformedSignatureValue,
"RFC 9421 carries an Ed25519 signature as a 64-byte RFC 8941 byte sequence, wrapped in \
colons; this one is something else.",
)
})?;
Ok((list.clone(), value))
}
pub(crate) fn parse_bounded(raw: &str, name: &str, kind: Kind) -> Result<Vec<(String, Member)>> {
check_size(raw, name, kind)?;
let parsed = parse_dictionary(raw).map_err(|_| {
Error::new(
kind,
format!(
"I could not parse the {name} header; it is spelled as an RFC 8941 dictionary."
),
)
})?;
if parsed.is_empty() {
return Err(Error::new(
kind,
format!("The {name} header holds no members, so there is nothing in it to read."),
));
}
check_counts(parsed.iter().map(|(_, member)| member), name, kind)?;
Ok(parsed)
}
pub(crate) fn check_size(raw: &str, name: &str, kind: Kind) -> Result<()> {
if raw.len() > MAX_FIELD_BYTES {
return Err(Error::new(
kind,
format!(
"The {name} header is {} bytes, and fiki reads one of at most {MAX_FIELD_BYTES}.",
raw.len()
),
));
}
Ok(())
}
pub(crate) fn check_counts<'a>(
members: impl ExactSizeIterator<Item = &'a Member>,
name: &str,
kind: Kind,
) -> Result<()> {
let too_many = |what: &str, limit: usize| {
Err(Error::new(
kind,
format!(
"The {name} header has more than {limit} {what}, which is more than fiki reads \
from any honest signer."
),
))
};
if members.len() > MAX_DICTIONARY_MEMBERS {
return too_many("members", MAX_DICTIONARY_MEMBERS);
}
for member in members {
let (items, params) = match member {
Member::Item(item) => (&[][..], &item.params),
Member::List(list) => (&list.items[..], &list.params),
};
if items.len() > MAX_INNER_LIST_ITEMS {
return too_many("items in one inner list", MAX_INNER_LIST_ITEMS);
}
let most = items
.iter()
.map(|item| item.params.len())
.max()
.unwrap_or(0);
if params.len().max(most) > MAX_PARAMETERS {
return too_many("parameters on one item", MAX_PARAMETERS);
}
}
Ok(())
}
fn check_input(member: &Member, require_keyid: bool, require_created: bool) -> Result<&InnerList> {
let malformed = |why: String| Err(Error::new(Kind::MalformedSignatureInput, why));
let Member::List(list) = member else {
return malformed(
"A Signature-Input member is a parenthesized list of covered components; this one is \
a single value."
.into(),
);
};
for item in &list.items {
let Some(name) = item.text() else {
return malformed(format!(
"Every covered component is named by a quoted string; {} is not one.",
brief(&crate::sfv::serialize_item(item))
));
};
if !name.starts_with('@') && name != name.to_ascii_lowercase() {
return malformed(format!(
"The covered field {} is not lowercase, and RFC 9421 section 2.1 requires field \
names in the covered list to be lowercased by the signer.",
shown(name)
));
}
}
if require_keyid && list.param("keyid").is_none() {
return Err(Error::new(
Kind::MissingKey,
"This signature carries no keyid and no expected_aid was supplied, so there is no key \
to verify it against.",
));
}
if require_created && list.param("keyid").is_none() {
return Err(Error::new(
Kind::MissingKey,
"This signature carries no keyid, which the verifier's policy requires even though \
the key was named.",
));
}
if require_created && list.param("created").is_none() {
return malformed(
"This signature carries no created timestamp, which the verifier's policy requires."
.into(),
);
}
for (name, value) in &list.params {
let integer = match name.as_str() {
"created" | "expires" => true,
"nonce" | "alg" | "keyid" | "tag" => false,
_ => {
return malformed(format!(
"The signature parameter {} is not one fiki understands; it accepts created, \
expires, nonce, alg, keyid, tag.",
shown(name)
))
}
};
let fits = match value {
Value::Integer(_) => integer,
Value::Text(_) => !integer,
_ => false,
};
if !fits {
return malformed(format!(
"The signature parameter \"{name}\" must be {}.",
if integer {
"an integer"
} else {
"a quoted string"
}
));
}
if let Value::Integer(time @ ..=-1) = value {
return malformed(format!(
"The signature parameter \"{name}\" is {time}, and a UNIX time is not negative."
));
}
}
Ok(list)
}
fn local_key<'a>(opts: &'a VerifyOptions, keyid: Option<&'a str>) -> Result<Local<'a>> {
if let Some(aid) = &opts.expected_aid {
let public = verifying_key(aid)?;
return Ok(Local::Found(public, aid_of(public.as_bytes())));
}
let keyid = keyid.filter(|k| !k.is_empty()).ok_or_else(|| {
Error::new(
Kind::MissingKey,
"This signature carries no keyid and no expected_aid was supplied, so there is no key \
to verify it against.",
)
})?;
let malformed = |why: String| Error::detailed(Kind::MalformedKey, why, keyid);
if let Some(resolver) = &opts.resolve {
if !well_formed_aid(keyid) {
return Err(malformed(format!(
"The keyid {} is not a well-formed AID: 44 characters, B, D or E, then the \
canonical base64url spelling of 32 bytes. A resolver is asked only about an AID.",
shown(keyid)
)));
}
return Ok(Local::Resolve(resolver, keyid));
}
let raw = raw_keyid(keyid).ok_or_else(|| {
malformed(format!(
"The keyid {} is not a base64url-encoded 32-byte Ed25519 public key: that is exactly \
43 characters from the base64url alphabet, unpadded, in the key's own spelling.",
shown(keyid)
))
})?;
let public = public_key(&raw).ok_or_else(|| {
malformed(format!(
"The keyid {} is not a usable Ed25519 public key: it is not a point on the curve, or it \
is a small-order point, under which a signature proves nothing.",
shown(keyid)
))
})?;
Ok(Local::Found(public, aid_of(&raw)))
}
enum Local<'a> {
Found(VerifyingKey, String),
Resolve(&'a Resolver, &'a str),
}
fn resolved(resolver: &Resolver, keyid: &str) -> Result<(VerifyingKey, String)> {
let raw = resolver(keyid)?.ok_or_else(|| {
Error::detailed(
Kind::UnknownKey,
format!(
"No key is known for the keyid {}, so the signature cannot be checked.",
shown(keyid)
),
keyid,
)
})?;
let public = public_key(&raw).ok_or_else(|| {
Error::detailed(
Kind::MalformedKey,
format!(
"The key resolved for {} is not a usable Ed25519 public key: it is not a point on \
the curve, or it is a small-order point, under which a signature proves nothing.",
shown(keyid)
),
keyid,
)
})?;
Ok((public, keyid.to_string()))
}
fn check_window(opts: &VerifyOptions) -> Result<()> {
if opts.max_age == MaxAge::Unstated {
return Err(Error::new(
Kind::InvalidArgument,
"max_age is a required decision: state the age this verifier tolerates, such as \
MaxAge::seconds(300), or MaxAge::Unchecked to decline the check. The signer's expires \
is enforced either way.",
));
}
let max_age = opts.max_age.seconds_or_none();
for (name, value) in [("max_age", max_age), ("skew", opts.skew)] {
if let Some(value) = value.filter(|v| *v <= 0) {
return Err(Error::detailed(
Kind::InvalidArgument,
format!(
"{name} is {value}, and a freshness window is a positive number of seconds."
),
value.to_string(),
));
}
}
Ok(())
}
fn check_freshness(list: &InnerList, opts: &VerifyOptions) -> Result<()> {
let expires = match list.param("expires") {
Some(Value::Integer(n)) => Some(*n),
_ => None,
};
let max_age = opts.max_age.seconds_or_none();
if expires.is_none() && max_age.is_none() {
return Ok(());
}
let skew = opts.skew.unwrap_or(DEFAULT_SKEW);
let stamp = now_or(opts.now);
let wide = |n: i64| i128::from(n);
if let Some(max_age) = max_age {
let too_old = |why: String| Err(Error::new(Kind::SignatureTooOld, why));
let Some(Value::Integer(created)) = list.param("created") else {
return too_old(format!(
"This signature carries no created timestamp, so its age cannot be checked against \
the {max_age}-second limit you asked for."
));
};
if wide(stamp) - wide(*created) > wide(max_age) + wide(skew) {
return too_old(format!(
"This signature was created at {created}, which is more than {max_age} seconds \
before {stamp}, so it is too old to accept."
));
}
if wide(*created) - wide(stamp) > wide(skew) {
return too_old(format!(
"This signature claims to have been created at {created}, which is in the future \
relative to {stamp} by more than the {skew}-second skew allowance."
));
}
}
match expires {
Some(expires) if wide(stamp) > wide(expires) + wide(skew) => Err(Error::new(
Kind::SignatureExpired,
format!(
"This signature expired at {expires} and it is now {stamp}, so the signer has \
already declared it should not be accepted."
),
)),
_ => Ok(()),
}
}
type Recognized = Vec<(&'static str, Vec<u8>)>;
fn read_digest(header: Option<&String>) -> Result<Recognized> {
let malformed = |why: &str| Error::new(Kind::MalformedDigest, why.to_string());
let header = header.ok_or_else(|| {
malformed(
"The signature covers content-digest and the message carries no Content-Digest \
header, so there is no digest to read.",
)
})?;
let parsed = parse_bounded(header, "Content-Digest", Kind::MalformedDigest)?;
let mut recognized = Vec::new();
for (name, member) in &parsed {
let algorithm = match name.as_str() {
"sha-256" => "sha-256",
"sha-512" => "sha-512",
_ => continue,
};
let Member::Item(Item {
value: Value::Bytes(expected),
..
}) = member
else {
return Err(malformed(&format!(
"The {name} Content-Digest is not an RFC 8941 byte sequence, so it cannot be \
compared with anything."
)));
};
recognized.push((algorithm, expected.clone()));
}
if recognized.is_empty() {
return Err(malformed(
"The Content-Digest header names no algorithm fiki computes; it computes sha-256 and \
sha-512.",
));
}
Ok(recognized)
}
fn compare_digest(recognized: &Recognized, body: Option<&[u8]>) -> Result<()> {
let Some(body) = body else {
return Err(Error::new(
Kind::DigestMismatch,
"The signature covers content-digest, but no body was supplied to check it against, \
so the body is unverified.",
));
};
for (name, expected) in recognized {
let computed = match *name {
"sha-256" => Sha256::digest(body).to_vec(),
_ => Sha512::digest(body).to_vec(),
};
if &computed != expected {
return Err(Error::new(
Kind::DigestMismatch,
format!(
"The body does not match its {name} Content-Digest, so the body is not the one \
that was signed."
),
));
}
}
Ok(())
}