ribergshamra_dsig/lib.rs
1#![forbid(unsafe_code)]
2
3//! XML Digital Signature (XML-DSig) implementation.
4//!
5//! Provides signature verification and creation per the W3C XML-DSig spec.
6//!
7//! # Security Hardening
8//!
9//! XML Digital Signatures are a frequent target of attack. ribergshamra provides
10//! several layered protections that you should understand and enable as
11//! appropriate for your application.
12//!
13//! ## Duplicate ID Rejection (always on)
14//!
15//! XML Signature Wrapping (XSW) attacks often rely on injecting a second
16//! element with the same `Id` attribute so that the signature verifies against
17//! one element while the application processes another.
18//!
19//! ribergshamra **always** rejects documents that contain duplicate ID values
20//! across any registered ID attribute (`Id`, `ID`, `id`, `AssertionID`,
21//! `xml:id`, and any names added via [`DsigContext::add_id_attr`]). Both
22//! [`verify::verify`] and [`sign::sign`] return
23//! `Err(Error::XmlStructure("duplicate ID: …"))` if a duplicate is found.
24//!
25//! No opt-in is required — this protection is unconditional.
26//!
27//! ## Inspecting What Was Signed (`VerifyResult` metadata)
28//!
29//! A successful verification returns [`VerifyResult::Valid`] which carries:
30//!
31//! - **`signature_node`** — the [`NodeId`](uppsala::NodeId) of the
32//! `<Signature>` element that was verified.
33//! - **`references`** — a `Vec<`[`VerifiedReference`]`>`, one per
34//! `<Reference>` in `<SignedInfo>`. Each entry contains the `uri` string and
35//! the `resolved_node` (an `Option<NodeId>`) that the URI resolved to, plus
36//! `digest_verified` to report whether ribergshamra locally computed and
37//! checked that reference digest.
38//!
39//! If `digest_verified` is `false`, the reference is currently a `cid:`
40//! attachment reference: its URI, transforms, and declared digest are
41//! integrity-protected by the signed `<SignedInfo>`, but the external
42//! attachment bytes were not hashed by ribergshamra. When local digest coverage is
43//! explicitly disabled for detached-content workflows, use
44//! [`VerifyResult::all_reference_digests_verified`] or
45//! [`VerifyResult::has_unverified_references`] to check whether all reference
46//! digests were verified locally or whether any were not. Match on
47//! [`VerifyResult::Valid`] and inspect `references` when you need
48//! per-reference detail.
49//!
50//! By default, verification requires local digest coverage: an otherwise valid
51//! `SignatureValue` is reported invalid when `<SignedInfo>` has no
52//! `<Reference>` elements or when any reference digest was not computed locally.
53//! Detached-content profiles that validate attachment bytes out-of-band can opt
54//! out by calling [`DsigContext::with_require_reference_digests`] with `false`.
55//!
56//! ## Trust Anchors and Inline Keys
57//!
58//! When trusted certificates are configured, raw inline keys from `<KeyValue>`
59//! or `<DEREncodedKeyValue>` are rejected because they have no certificate chain
60//! to validate against those anchors. Inline `<X509Data>` remains supported, but
61//! its chain must validate to a configured trust anchor.
62//!
63//! Library callers that must reproduce xmlsec compatibility behavior can opt
64//! back into raw inline keys with
65//! [`DsigContext::with_allow_raw_inline_keyinfo_with_trust_anchors`]. Do not
66//! enable that flag for normal verification of untrusted XML: it means a raw
67//! document-controlled key may verify even though trust anchors are configured.
68//! Use [`DsigContext::trusted_keys_only`] when the accepted signing keys are
69//! known ahead of time and all document-supplied keys should be ignored.
70//!
71//! **You should always check that the signature covers the element you intend
72//! to consume.** For example, a SAML Service Provider should verify that one
73//! of the references points to the `<Assertion>` it will process:
74//!
75//! ```rust,ignore
76//! use ribergshamra_dsig::VerifyResult;
77//!
78//! let result = ribergshamra_dsig::verify::verify(&ctx, &xml)?;
79//! match result {
80//! VerifyResult::Valid { references, .. } => {
81//! let covers_assertion = references.iter().any(|r| {
82//! r.resolved_node.is_some_and(|n| {
83//! doc.element(n).is_some_and(|e| {
84//! &*e.name.local_name == "Assertion"
85//! })
86//! })
87//! });
88//! assert!(covers_assertion, "signature must cover the Assertion");
89//! }
90//! VerifyResult::Invalid { reason } => panic!("invalid: {reason}"),
91//! }
92//! ```
93//!
94//! ## Strict Verification Mode (opt-in)
95//!
96//! Set [`DsigContext::strict_verification`] to `true` to enforce positional
97//! constraints on reference targets. In strict mode every same-document
98//! reference must resolve to a node that is:
99//!
100//! - the **document element** (root), or
101//! - an **ancestor** of the `<Signature>` (the signed element wraps the
102//! signature — the common enveloped pattern), or
103//! - a **sibling** of the `<Signature>` (both are children of the same parent).
104//!
105//! Any other position causes verification to fail with
106//! `Err(Error::XmlStructure("strict mode: …"))`.
107//!
108//! This is the strongest defence against XSW attacks and is recommended for
109//! SAML and WS-Security consumers where the document structure is well-known.
110//!
111//! ```rust,ignore
112//! let ctx = DsigContext::new(keys_manager); // secure defaults: strict + trusted_keys_only
113//! let result = ribergshamra_dsig::verify::verify(&ctx, &xml)?;
114//! ```
115//!
116//! The CLI exposes this as `ribergshamra verify --strict --trusted-keys-only`.
117//!
118//! ## Secure Defaults (`DsigContext::new`)
119//!
120//! [`DsigContext::new()`] enables secure defaults out of the box:
121//! - **`trusted_keys_only = true`** — ignores inline keys in `<KeyInfo>`
122//! (`<KeyValue>`, `<X509Certificate>`, etc.) and only uses keys from the
123//! [`KeysManager`](ribergshamra_keys::KeysManager). Without this, an attacker
124//! who controls the XML can embed their own key and forge a valid signature.
125//! - **`strict_verification = true`** — rejects references to nodes that are not
126//! ancestors, siblings, or the document element (XSW protection).
127//! - **`hmac_min_out_len = 160`** — enforces a minimum HMAC output length of
128//! 160 bits to prevent truncation attacks (CVE-2009-0217).
129//! - **`require_reference_digests = true`** — requires at least one
130//! `<Reference>` and requires every `<Reference>` digest to be locally
131//! verified before returning [`VerifyResult::Valid`].
132//!
133//! Use [`DsigContext::new_permissive()`] when you need inline-key and relaxed
134//! structural behavior for self-contained signatures. It still requires local
135//! reference-digest coverage unless you explicitly disable that policy.
136//!
137//! ## Recommended Configuration for SAML
138//!
139//! ```rust,ignore
140//! // DsigContext::new() already has secure defaults — just add cert validation:
141//! let mut ctx = DsigContext::new(keys_manager);
142//! ctx.verify_keys = true;
143//! ```
144
145pub mod context;
146pub mod sign;
147pub mod verify;
148
149pub use context::DsigContext;
150pub use verify::{VerifiedKeyInfo, VerifiedReference, VerifyResult};
151
152/// Convert a [`riptering::Error`] into a [`ribergshamra_core::Error`].
153fn map_riptering_err(e: riptering::Error) -> ribergshamra_core::Error {
154 match e {
155 riptering::Error::Crypto(s) => ribergshamra_core::Error::Crypto(s),
156 err @ riptering::Error::UnsupportedAlgorithm { .. } => {
157 ribergshamra_core::Error::UnsupportedAlgorithm(err.to_string())
158 }
159 riptering::Error::Key(s) => ribergshamra_core::Error::Key(s),
160 riptering::Error::Io(e) => ribergshamra_core::Error::Io(e),
161 // Handle additional error variants (e.g., Pkcs11) when the riptering
162 // crate is compiled with optional features.
163 #[allow(unreachable_patterns)]
164 other => ribergshamra_core::Error::Crypto(other.to_string()),
165 }
166}