use crate::errors::{AuthError, Result};
use base64::Engine;
use bergshamra::{DsigContext, Key, KeyData, KeysManager, VerifyResult, verify};
use quick_xml::Reader;
use quick_xml::events::Event;
use std::collections::{BTreeMap, BTreeSet};
fn invalid(message: impl Into<String>) -> AuthError {
AuthError::validation(message.into())
}
#[derive(Clone, Default)]
pub struct SamlTrustAnchors {
by_issuer: BTreeMap<String, Vec<Vec<u8>>>,
}
impl std::fmt::Debug for SamlTrustAnchors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SamlTrustAnchors")
.field("issuers", &self.by_issuer.keys().collect::<Vec<_>>())
.finish()
}
}
impl SamlTrustAnchors {
pub fn new() -> Self {
Self::default()
}
pub fn trust(&mut self, issuer: impl Into<String>, certificate_der: Vec<u8>) -> Result<()> {
let issuer = issuer.into();
key_from_x509_der(&certificate_der).map_err(|e| {
invalid(format!(
"The certificate configured for SAML issuer '{issuer}' is unusable: {e}"
))
})?;
self.by_issuer
.entry(issuer)
.or_default()
.push(certificate_der);
Ok(())
}
pub fn trust_pem(&mut self, issuer: impl Into<String>, certificate: &str) -> Result<()> {
let b64: String = certificate
.lines()
.filter(|l| !l.starts_with("-----") && !l.trim().is_empty())
.map(str::trim)
.collect();
let der = base64::engine::general_purpose::STANDARD
.decode(b64)
.map_err(|e| invalid(format!("Invalid certificate encoding: {e}")))?;
self.trust(issuer, der)
}
pub fn extend(&mut self, other: SamlTrustAnchors) {
for (issuer, certificates) in other.by_issuer {
self.by_issuer
.entry(issuer)
.or_default()
.extend(certificates);
}
}
pub fn is_empty(&self) -> bool {
self.by_issuer.is_empty()
}
fn certificates(&self, issuer: &str) -> Option<&[Vec<u8>]> {
self.by_issuer.get(issuer).map(Vec::as_slice)
}
fn issuers(&self) -> impl Iterator<Item = &str> {
self.by_issuer.keys().map(String::as_str)
}
}
#[derive(Clone)]
pub struct VerifiedAssertion {
pub issuer: String,
pub signed_id: String,
pub assertion_xml: String,
pub response_signed: bool,
}
impl std::fmt::Debug for VerifiedAssertion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VerifiedAssertion")
.field("issuer", &self.issuer)
.finish_non_exhaustive()
}
}
pub(crate) fn key_from_x509_der(der: &[u8]) -> std::result::Result<Key, String> {
use x509_parser::prelude::*;
let (_, cert) = X509Certificate::from_der(der)
.map_err(|e| format!("Failed to parse X.509 certificate: {}", e))?;
let spki = cert.public_key();
let spki_der = spki.raw;
let mut last_err = None;
for algorithm in [
kryptering::KeyAlgorithm::Rsa,
kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P256),
kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P384),
] {
match KeyData::from_spki_der(algorithm, spki_der) {
Ok(key_data) => return Ok(Key::new(key_data, bergshamra::KeyUsage::Verify)),
Err(e) => last_err = Some(e),
}
}
Err(format!(
"Unsupported IdP signing key algorithm (OID: {}). RSA, P-256, and P-384 are supported.{}",
cert.public_key().algorithm.oid(),
last_err
.map(|e| format!(" Last error: {e}"))
.unwrap_or_default()
))
}
fn bytes_of<T: AsRef<[u8]> + ?Sized>(value: &T) -> &[u8] {
value.as_ref()
}
struct Element {
local: String,
id: Option<String>,
start: usize,
end: usize,
parent: Option<usize>,
text: Option<String>,
issuer_attr: Option<String>,
}
fn unescaped(raw: &[u8]) -> Result<String> {
let s = std::str::from_utf8(raw).map_err(|_| invalid("SAML text is not UTF-8"))?;
quick_xml::escape::unescape(s)
.map(|c| c.into_owned())
.map_err(|e| invalid(format!("Invalid entity in SAML text: {e}")))
}
fn element_of(
start: &quick_xml::events::BytesStart<'_>,
begin: usize,
parent: Option<usize>,
) -> Result<Element> {
let local = String::from_utf8_lossy(bytes_of(start.local_name().into_inner())).into_owned();
let mut id = None;
let mut issuer_attr = None;
for attr in start.attributes() {
let attr = attr.map_err(|e| invalid(format!("XML attribute error: {e}")))?;
let key = String::from_utf8_lossy(bytes_of(attr.key.local_name().into_inner()));
if bytes_of(attr.key.as_ref()) != key.as_bytes() {
continue;
}
if matches!(key.as_ref(), "ID" | "Id" | "id" | "AssertionID") {
id = Some(unescaped(bytes_of(&*attr.value))?);
} else if key.as_ref() == "Issuer" {
issuer_attr = Some(unescaped(bytes_of(&*attr.value))?);
}
}
Ok(Element {
local,
id,
start: begin,
end: begin,
parent,
text: None,
issuer_attr,
})
}
fn scan(xml: &str) -> Result<Vec<Element>> {
let mut reader = Reader::from_str(xml);
let mut elements: Vec<Element> = Vec::new();
let mut stack: Vec<usize> = Vec::new();
loop {
let begin = reader.buffer_position() as usize;
match reader.read_event() {
Ok(Event::Start(e)) => {
let parent = stack.last().copied();
elements.push(element_of(&e, begin, parent)?);
stack.push(elements.len() - 1);
}
Ok(Event::Empty(e)) => {
let parent = stack.last().copied();
let mut element = element_of(&e, begin, parent)?;
element.end = reader.buffer_position() as usize;
elements.push(element);
}
Ok(Event::End(_)) => {
let index = stack
.pop()
.ok_or_else(|| invalid("Unbalanced XML in SAML document"))?;
elements[index].end = reader.buffer_position() as usize;
}
Ok(Event::Text(t)) => {
if let Some(&index) = stack.last()
&& matches!(elements[index].local.as_str(), "Issuer" | "X509Certificate")
&& elements[index].text.is_none()
{
elements[index].text = Some(unescaped(bytes_of(&*t))?.trim().to_string());
}
}
Ok(Event::DocType(_)) => {
return Err(invalid("A SAML document may not carry a DOCTYPE"));
}
Ok(Event::Eof) => break,
Ok(_) => {}
Err(e) => return Err(invalid(format!("XML parsing error: {e}"))),
}
}
if !stack.is_empty() {
return Err(invalid("Unbalanced XML in SAML document"));
}
Ok(elements)
}
fn direct_children<'a>(
elements: &'a [Element],
parent: usize,
local: &'a str,
) -> impl Iterator<Item = usize> + 'a {
elements
.iter()
.enumerate()
.filter(move |(_, e)| e.parent == Some(parent) && e.local == local)
.map(|(i, _)| i)
}
pub fn verify_signed_assertion(xml: &str, anchors: &SamlTrustAnchors) -> Result<VerifiedAssertion> {
if anchors.is_empty() {
return Err(invalid(
"No trusted SAML issuer is configured, so no assertion can be accepted",
));
}
let elements = scan(xml)?;
let named: BTreeSet<&str> = elements
.iter()
.flat_map(|e| {
let element_text = (e.local == "Issuer").then_some(e.text.as_deref()).flatten();
let attribute = (e.local == "Assertion")
.then_some(e.issuer_attr.as_deref())
.flatten();
element_text.into_iter().chain(attribute)
})
.collect();
let candidates: Vec<&str> = anchors.issuers().filter(|i| named.contains(i)).collect();
if candidates.is_empty() {
return Err(invalid(
"The SAML document names no issuer that is configured as trusted",
));
}
let mut last_reason = String::from("no signature");
for issuer in candidates {
let Some(certificates) = anchors.certificates(issuer) else {
continue;
};
for der in certificates {
match verify_under(xml, der) {
Ok(references) => {
return covered_assertion(xml, &elements, issuer, &references);
}
Err(reason) => last_reason = reason,
}
}
}
Err(invalid(format!(
"XML signature verification failed: {last_reason}"
)))
}
pub(crate) fn verify_under(xml: &str, der: &[u8]) -> std::result::Result<Vec<String>, String> {
let key = key_from_x509_der(der)?;
let mut keys = KeysManager::new();
keys.add_key(key);
keys.add_trusted_cert(der.to_vec());
let ctx = DsigContext::new(keys)
.with_trusted_keys_only(true)
.with_strict_verification(true)
.with_verify_keys(true);
match verify(&ctx, xml).map_err(|e| format!("XML-DSig verification error: {e}"))? {
result @ VerifyResult::Valid { .. } => {
if !result.all_reference_digests_verified() {
return Err("a reference digest was not verified, or none was signed".to_string());
}
let VerifyResult::Valid { references, .. } = result else {
unreachable!("matched Valid above")
};
Ok(references.into_iter().map(|r| r.uri).collect())
}
VerifyResult::Invalid { reason } => Err(format!("Signature invalid: {reason}")),
}
}
fn covered_assertion(
xml: &str,
elements: &[Element],
issuer: &str,
reference_uris: &[String],
) -> Result<VerifiedAssertion> {
let root = elements
.iter()
.position(|e| e.parent.is_none())
.ok_or_else(|| invalid("SAML document has no root element"))?;
let mut found: BTreeSet<usize> = BTreeSet::new();
let mut signed_id = String::new();
let mut response_signed = false;
for uri in reference_uris {
let signed = if uri.is_empty() {
root
} else if let Some(id) = uri.strip_prefix('#') {
let mut holders = elements
.iter()
.enumerate()
.filter(|(_, e)| e.id.as_deref() == Some(id))
.map(|(i, _)| i);
let (Some(first), None) = (holders.next(), holders.next()) else {
return Err(invalid(format!(
"Signed reference '{uri}' does not name exactly one element"
)));
};
signed_id = id.to_string();
first
} else {
return Err(invalid(format!("Unsupported signature reference '{uri}'")));
};
match elements[signed].local.as_str() {
"Assertion" => {
found.insert(signed);
}
"Response" => {
response_signed = true;
found.extend(direct_children(elements, signed, "Assertion"));
}
_ => {}
}
}
let mut found = found.into_iter();
let (Some(assertion), None) = (found.next(), found.next()) else {
return Err(invalid(
"The signature must cover exactly one SAML assertion",
));
};
let assertion_issuer = direct_children(elements, assertion, "Issuer")
.next()
.and_then(|i| elements[i].text.as_deref())
.or(elements[assertion].issuer_attr.as_deref())
.ok_or_else(|| invalid("The signed assertion names no issuer"))?;
if assertion_issuer != issuer {
return Err(invalid(format!(
"The signed assertion's issuer '{assertion_issuer}' is not the issuer the signing certificate is pinned for"
)));
}
let e = &elements[assertion];
Ok(VerifiedAssertion {
issuer: issuer.to_string(),
signed_id,
assertion_xml: xml[e.start..e.end].to_string(),
response_signed,
})
}
pub fn anchors_for_thumbprints(
xml: &str,
issuers: &[String],
thumbprints: &[String],
) -> Result<SamlTrustAnchors> {
use sha2::{Digest, Sha256};
let pinned: BTreeSet<String> = thumbprints
.iter()
.map(|t| {
t.chars()
.filter(|c| c.is_ascii_hexdigit())
.collect::<String>()
.to_ascii_lowercase()
})
.filter(|t| !t.is_empty())
.collect();
let mut anchors = SamlTrustAnchors::new();
if pinned.is_empty() {
return Ok(anchors);
}
let elements = scan(xml)?;
let named: BTreeSet<String> = if issuers.is_empty() {
elements
.iter()
.flat_map(|e| {
let element_text = (e.local == "Issuer").then_some(e.text.as_deref()).flatten();
let attribute = (e.local == "Assertion")
.then_some(e.issuer_attr.as_deref())
.flatten();
element_text.into_iter().chain(attribute)
})
.map(str::to_string)
.collect()
} else {
issuers.iter().cloned().collect()
};
for text in elements
.iter()
.filter(|e| e.local == "X509Certificate")
.filter_map(|e| e.text.as_deref())
{
let b64: String = text.chars().filter(|c| !c.is_whitespace()).collect();
let Ok(der) = base64::engine::general_purpose::STANDARD.decode(b64) else {
continue;
};
if pinned.contains(&hex::encode(Sha256::digest(&der))) {
for issuer in &named {
anchors.trust(issuer.clone(), der.clone())?;
}
}
}
Ok(anchors)
}