Skip to main content

openszigno_verify/
lib.rs

1//! XMLDSig verification for Microsec e-Szignó dossiers.
2//!
3//! # What this phase can and cannot say
4//!
5//! This is phase 3 of the `verify` milestone. It validates the XMLDSig core
6//! (canonicalization, reference digests, the signature value), enforces the
7//! e-dossier reference-scope rules, binds the signing certificate through the
8//! signed XAdES `SigningCertificate` property, verifies RFC 3161 signature
9//! timestamps, validates the certification path against a caller-supplied
10//! trust store and ETSI TS 119 612 trusted lists at a validation time a
11//! verified timestamp may move, and checks revocation offline from the
12//! signature's own `xades:RevocationValues` and a caller-supplied store.
13//!
14//! With revocation implemented, `valid` is reachable — and only reachable when
15//! every emitted check passed. A caller that sees `indeterminate` has learned
16//! that nothing failed, not that anything is trustworthy.
17//!
18//! # Structure
19//!
20//! The crate owns the whole pipeline: reference resolution, the transform and
21//! algorithm allowlists, canonicalization, and path validation. Nothing is
22//! delegated to a general-purpose XMLDSig library, because those libraries do
23//! not know the e-dossier placement rules and would own exactly the decisions
24//! this project has stricter rules about.
25//!
26//! All I/O arrives through the injected [`Clock`], [`TrustSource`], and
27//! [`RevocationSource`] traits. The crate itself opens no file and no socket.
28
29#![forbid(unsafe_code)]
30
31pub mod c14n;
32pub mod certs;
33pub mod codes;
34pub mod countersign;
35pub mod coverage;
36pub mod dsig;
37pub mod embedded;
38pub mod estimestamp;
39pub mod policy;
40pub mod references;
41pub mod report;
42pub mod revocation;
43pub mod scope;
44pub mod signature;
45pub mod trust;
46pub mod trustlist;
47pub mod tsa;
48pub mod xades;
49
50use openszigno_core::{Error as CoreError, Limits, ParseOptions, XmlSource, id_map};
51
52pub use c14n::{C14nAlgorithm, C14nBackend, C14nError, NodeSet, RoxmltreeC14n};
53pub use codes::{Check, CheckCode, CheckStatus, Verdict};
54pub use embedded::{EmbeddedRevocationValues, embedded_certificates, embedded_revocation_values};
55pub use policy::{MAX_REVOCATION_ITEM_BYTES, PolicyReport, TrustListSnapshot, VerifyLimits};
56pub use report::{
57    CoverageState, CoverageVia, CoveringSignature, DocumentCoverage, SignatureReport,
58    SignatureRole, SignatureScope, SigningCertificateBinding, ValidationTimeSource, VerifyReport,
59    XadesReport,
60};
61pub use revocation::{CertificateRevocation, RevocationOrigin, RevocationStatus};
62pub use trust::{
63    Clock, FixedClock, MemoryRevocationStore, MemoryTrustStore, NoRevocation, NoTrust,
64    RevocationPolicy, RevocationSource, ServiceIdentity, SystemClock, TrustAnchor,
65    TrustAnchorOrigin, TrustServiceIdentity, TrustSource, format_rfc3339, parse_rfc3339,
66};
67pub use trustlist::{ServiceRecord, ServiceType, TrustList};
68pub use tsa::{TimestampKind, TimestampReport};
69
70use crate::certs::{CertificateSource, ParsedCertificate, dedup};
71use crate::report::{Counts, VerificationTime};
72use crate::trust::TimeSource;
73use crate::tsa::{TokenInput, verify_token_at};
74
75/// How one dossier is verified.
76pub struct VerifyOptions<'a> {
77    pub parse: ParseOptions,
78    pub limits: VerifyLimits,
79    pub clock: &'a dyn Clock,
80    /// The `--at` value as the caller wrote it, for the report only.
81    pub requested_time: Option<String>,
82    pub trust: &'a dyn TrustSource,
83    /// Admit SHA-1 digests and RSA-SHA1 signature methods for diagnosis only.
84    /// A legacy algorithm never yields a `passed` check, so this flag can only
85    /// lower a verdict, never raise one. MD5, HMAC, DSA, and RSA keys below
86    /// 2048 bits stay refused whatever it is set to.
87    pub allow_legacy_algorithms: bool,
88    pub revocation: &'a dyn RevocationSource,
89    pub backend: &'a dyn C14nBackend,
90}
91
92impl<'a> VerifyOptions<'a> {
93    /// Offline defaults: the system clock, no trust anchors, no revocation
94    /// data, and the in-tree canonicalization backend.
95    pub fn new(
96        clock: &'a dyn Clock,
97        trust: &'a dyn TrustSource,
98        revocation: &'a dyn RevocationSource,
99        backend: &'a dyn C14nBackend,
100    ) -> Self {
101        Self {
102            parse: ParseOptions::default(),
103            limits: VerifyLimits::default(),
104            clock,
105            requested_time: None,
106            trust,
107            allow_legacy_algorithms: false,
108            revocation,
109            backend,
110        }
111    }
112
113    fn core_limits(&self) -> &Limits {
114        &self.parse.limits
115    }
116}
117
118/// Everything the stages of one run share, gathered once before the first
119/// signature is examined.
120///
121/// Stages A to C need only the XMLDSig [`dsig::Context`]; stages D to F also
122/// need the trust material, the revocation policy and the clock reading, so
123/// all of it is threaded through this one struct.
124pub(crate) struct Context<'a, 'input, 's, 'o> {
125    pub(crate) options: &'o VerifyOptions<'o>,
126    /// The XMLDSig context stages A to C are driven from.
127    pub(crate) dsig: dsig::Context<'a, 'input, 's>,
128    /// The trust anchors: self-signed entries only, from either source.
129    /// Nothing found in the dossier is ever one.
130    pub(crate) anchors: Vec<ParsedCertificate>,
131    /// Which [`trust::TrustAnchor`] each anchor's DER came from, so a
132    /// validated path can be asked which anchor ended it.
133    pub(crate) anchor_provenance: Vec<(Vec<u8>, &'o trust::TrustAnchor)>,
134    /// Untrusted extra path candidates: every non-self-signed trust entry and
135    /// every intermediate the trust source offered.
136    pub(crate) store_intermediates: Vec<ParsedCertificate>,
137    /// Every trusted-list service identity, whether or not it is also a
138    /// self-signed anchor. They decide qualified status, and — through
139    /// [`certs::AnchorStatus::terminates`] — where a path may end: a listed
140    /// issuing CA is a trust anchor for the paths that reach it.
141    pub(crate) services: &'o [trust::TrustServiceIdentity],
142    pub(crate) revocation_policy: trust::RevocationPolicy,
143    /// The clock reading for this run.
144    pub(crate) time: trust::UnixTime,
145}
146
147impl Context<'_, '_, '_, '_> {
148    /// Everything a path search needs to know about where it may end and
149    /// whether it may end there: the anchors' provenance, and the trusted-list
150    /// service identities, which terminate a path wherever the list speaks —
151    /// at a listed issuing CA as readily as at a self-signed root.
152    pub(crate) fn anchor_status(&self) -> certs::AnchorStatus<'_> {
153        certs::AnchorStatus::new(&self.anchor_provenance).with_services(self.services)
154    }
155}
156
157/// Verify every `ds:Signature` in a dossier.
158///
159/// A structural failure is returned as a core [`CoreError`] and aborts before
160/// any signature is examined, so a caller can still tell "this is not a
161/// dossier" apart from "this dossier's signatures do not verify".
162pub fn verify(bytes: &[u8], options: &VerifyOptions<'_>) -> Result<VerifyReport, CoreError> {
163    // The structural rules run first and unchanged: they are what guarantees a
164    // unique ID space, resolvable OBJREFs, and a bounded document.
165    let dossier = openszigno_core::parse_with_options(bytes, &options.parse)?;
166
167    let source = XmlSource::decode(bytes, options.core_limits())?;
168    let tree = source.parse_tree(options.core_limits())?;
169    let root = tree.root();
170    let root_element = tree.root_element();
171    let namespace = root_element.tag_name().namespace().unwrap_or_default();
172    let ids = id_map(root_element)?;
173
174    let time = options.clock.unix_time();
175    let mut dossier_checks: Vec<Check> = Vec::new();
176
177    let signature_nodes: Vec<_> = root_element
178        .descendants()
179        .filter(|node| {
180            node.is_element()
181                && node.tag_name().namespace() == Some(openszigno_core::XMLDSIG_NAMESPACE)
182                && node.tag_name().name() == "Signature"
183        })
184        .collect();
185
186    if signature_nodes.len() > options.limits.max_signatures {
187        dossier_checks.push(Check::failed(
188            CheckCode::SignatureLimitExceeded,
189            format!(
190                "the dossier holds more than {} signatures",
191                options.limits.max_signatures
192            ),
193        ));
194    } else {
195        dossier_checks.push(Check::passed(
196            CheckCode::SignatureCountWithinLimits,
197            "the number of signatures is within the verification limits",
198        ));
199    }
200
201    // The trust store supplies both roles: a self-signed entry is an anchor, a
202    // non-self-signed one is an extra untrusted intermediate. Nothing found in
203    // the dossier is ever an anchor.
204    //
205    // A trusted list's anchors join the same set, keeping their provenance, so
206    // that a path can later be asked *which* anchor ended it and whether that
207    // anchor's service was granted at the validation time.
208    let mut anchors: Vec<ParsedCertificate> = Vec::new();
209    let mut anchor_provenance: Vec<(Vec<u8>, &trust::TrustAnchor)> = Vec::new();
210    let mut store_certificates: Vec<ParsedCertificate> = Vec::new();
211    // Every trusted-list service identity, whether or not it is also an anchor.
212    // The identities that decide qualified status are usually the *issuing*
213    // CAs, which are intermediates: a list that names them says nothing about
214    // the root, and asking only the anchor would report `null` for exactly the
215    // chains a trusted list exists to describe.
216    let services = options.trust.services();
217    for anchor in options.trust.anchors() {
218        let source = match anchor.origin {
219            trust::TrustAnchorOrigin::TrustList => CertificateSource::TrustList,
220            trust::TrustAnchorOrigin::TrustStore => CertificateSource::TrustStore,
221        };
222        let Some(parsed) = ParsedCertificate::from_der(&anchor.der, source) else {
223            continue;
224        };
225        if parsed.is_self_signed() {
226            anchor_provenance.push((anchor.der.clone(), anchor));
227            anchors.push(parsed);
228        } else {
229            // A non-self-signed entry is an extra path candidate, never an
230            // anchor, whichever source offered it.
231            store_certificates.push(parsed);
232        }
233    }
234    let anchors = dedup(anchors);
235    for der in options.trust.intermediates() {
236        if let Some(parsed) = ParsedCertificate::from_der(der, CertificateSource::TrustStore) {
237            store_certificates.push(parsed);
238        }
239    }
240    let store_intermediates = dedup(store_certificates);
241    dossier_checks.extend(options.trust.checks().iter().cloned());
242
243    let revocation_policy = options.revocation.policy();
244    dossier_checks.push(revocation::policy_check(revocation_policy));
245
246    let context = Context {
247        options,
248        dsig: dsig::Context {
249            source: source.text(),
250            root,
251            ids: &ids,
252            namespace,
253            allowed_namespaces: &options.parse.allowed_namespaces,
254            signatures: &signature_nodes,
255            backend: options.backend,
256            limits: &options.limits,
257            allow_legacy_algorithms: options.allow_legacy_algorithms,
258        },
259        anchors,
260        anchor_provenance,
261        store_intermediates,
262        services,
263        revocation_policy,
264        time,
265    };
266
267    let mut signatures = Vec::new();
268    let mut nested_unsupported: Vec<(usize, usize)> = Vec::new();
269    let mut dossier_crls: Vec<Vec<u8>> = Vec::new();
270    let mut dossier_ocsp: Vec<Vec<u8>> = Vec::new();
271    let mut dossier_certificates: Vec<ParsedCertificate> = Vec::new();
272    let over_limit = signature_nodes.len() > options.limits.max_signatures;
273    for (index, node) in signature_nodes.iter().enumerate() {
274        if over_limit && index >= options.limits.max_signatures {
275            break;
276        }
277        let outcome = dsig::verify_signature(&context.dsig, *node, index);
278        let mut report = outcome.report;
279
280        // The signature's own revocation material. Untrusted like every other
281        // thing a signer supplies: each item is signature-checked against the
282        // path before it is believed.
283        let (embedded_crls, embedded_ocsp) = xades::revocation_values(*node);
284        // The container timestamps below are verified against everything the
285        // dossier carries, not against one signature's share of it: an
286        // `es:TimeStamp` is not owned by any signature, and a TSA's issuing CA
287        // may sit in any signature's `CertificateValues`.
288        for item in &embedded_crls {
289            if !dossier_crls.contains(item) {
290                dossier_crls.push(item.clone());
291            }
292        }
293        for item in &embedded_ocsp {
294            if !dossier_ocsp.contains(item) {
295                dossier_ocsp.push(item.clone());
296            }
297        }
298        dossier_certificates.extend(outcome.extra_certificates.iter().cloned());
299        let revocation_data = revocation::RevocationData {
300            embedded_crls: &embedded_crls,
301            embedded_ocsp: &embedded_ocsp,
302            store_crls: options.revocation.crls(),
303            store_ocsp: options.revocation.ocsp_responses(),
304            online_crls: options.revocation.online_crls(),
305            online_ocsp: options.revocation.online_ocsp_responses(),
306        };
307
308        // --- Stage F: signature timestamps ----------------------------------
309        // Timestamps are verified before the signer's own path, because a
310        // verified token is what may move the validation time that path uses.
311        let verified_gen_times = tsa::verify_signature_timestamps(
312            &context,
313            &outcome.timestamps,
314            &outcome.extra_certificates,
315            outcome.claimed_signing_time,
316            revocation_data,
317            &mut report,
318        );
319
320        // --- The validation time for this signature -------------------------
321        // Precedence: an explicit `--at` always wins, then the earliest fully
322        // verified timestamp's genTime, then the clock.
323        let (signature_time, source) =
324            match (&options.requested_time, verified_gen_times.iter().min()) {
325                (Some(_), _) => (context.time, ValidationTimeSource::AtFlag),
326                (None, Some(gen_time)) => (*gen_time, ValidationTimeSource::Timestamp),
327                (None, None) => (context.time, ValidationTimeSource::CurrentTime),
328            };
329        report.validation_time = format_rfc3339(signature_time);
330        report.validation_time_source = source;
331
332        // --- Stage D: certificate path -------------------------------------
333        if let Some(signer) = &outcome.signer {
334            let signer_path = certs::verify_signer_path(
335                &context,
336                signer,
337                &outcome.extra_certificates,
338                signature_time,
339                &mut report,
340            );
341
342            // --- Stage E: revocation ----------------------------------------
343            revocation::check_signer_chain(
344                &context,
345                signer_path,
346                &revocation_data,
347                signature_time,
348                source == ValidationTimeSource::Timestamp,
349                &mut report,
350            );
351        } else {
352            report.checks.push(Check::unknown(
353                CheckCode::RevocationStatusUnknown,
354                "no signing certificate was identified, so revocation could not be checked",
355            ));
356        }
357
358        report.verdict = dsig::signature_verdict(&report.checks);
359        if let Some(parent) = outcome.unsupported_nesting_parent {
360            nested_unsupported.push((parent, index));
361        }
362        signatures.push(report);
363    }
364
365    // A nested signature this build does not support says nothing whatever
366    // about the signature it was dropped into: the enclosing signature does
367    // not cover its own unsigned properties, so nothing there can change what
368    // it says. The parent is told, informationally, and keeps its verdict.
369    for (parent, nested) in &nested_unsupported {
370        if let Some(report) = signatures.get_mut(*parent) {
371            report.checks.push(Check::info(
372                CheckCode::NestedSignaturesUnsupported,
373                format!(
374                    "signature {nested} is nested inside this one in a shape this build does not support; it is reported on its own and does not affect this signature's verdict"
375                ),
376            ));
377        }
378    }
379
380    // --- Stage G: container timestamps ------------------------------------
381    // An `es:TimeStamp` protects the elements its `xades:Include` children
382    // name, so verifying one needs the reference resolution, scope rule and
383    // canonicalization a signature gets. It decides nothing about any
384    // signature: it is a statement about the container.
385    let document_nodes: Vec<_> = dsig::direct_children(root_element, namespace, "Documents")
386        .next()
387        .map(|documents| {
388            dsig::direct_children(documents, namespace, "Document")
389                .filter(|document| {
390                    dsig::direct_children(*document, namespace, "DocumentProfile")
391                        .next()
392                        .is_some()
393                })
394                .collect()
395        })
396        .unwrap_or_default();
397    let container_candidates = dedup({
398        let mut candidates = dossier_certificates;
399        candidates.extend(context.store_intermediates.iter().cloned());
400        candidates
401    });
402    let container_revocation = revocation::RevocationData {
403        embedded_crls: &dossier_crls,
404        embedded_ocsp: &dossier_ocsp,
405        store_crls: options.revocation.crls(),
406        store_ocsp: options.revocation.ocsp_responses(),
407        online_crls: options.revocation.online_crls(),
408        online_ocsp: options.revocation.online_ocsp_responses(),
409    };
410    let mut container_timestamps: Vec<tsa::TimestampReport> = Vec::new();
411    for source in estimestamp::collect(&context.dsig, root_element, &document_nodes) {
412        if let Some(reason) = &source.unsupported {
413            let check = estimestamp::unsupported_check(source.scope, reason);
414            dossier_checks.push(check.clone());
415            container_timestamps.push(tsa::TimestampReport {
416                kind: source.kind(),
417                document_index: source.document_index(),
418                gen_time: None,
419                accuracy_seconds: None,
420                serial_hex: None,
421                imprint_algorithm: None,
422                tsa_certificate: None,
423                chain: Vec::new(),
424                verified: false,
425                checks: vec![check],
426            });
427            continue;
428        }
429        let token = verify_token_at(
430            &TokenInput {
431                kind: source.kind(),
432                document_index: source.document_index(),
433                token: source.token.clone(),
434                imprint_input: source.imprint_input.clone(),
435                anchors: &context.anchors,
436                extra_certificates: &container_candidates,
437                limits: &options.limits,
438                allow_legacy_algorithms: options.allow_legacy_algorithms,
439                revocation: container_revocation,
440                revocation_policy,
441                // A container timestamp is not attached to any claimed signing
442                // time, so there is no ordering claim to contradict.
443                claimed_signing_time: None,
444            },
445            context.anchor_status(),
446        );
447        dossier_checks.push(estimestamp::summarise(
448            source.scope,
449            &token.report.checks,
450            token.report.verified,
451        ));
452        container_timestamps.push(token.report);
453    }
454    let timestamps_verified = container_timestamps
455        .iter()
456        .filter(|report| report.verified)
457        .count();
458
459    if signatures.is_empty() {
460        dossier_checks.push(Check::unknown(
461            CheckCode::NoSignatures,
462            "the dossier carries no ds:Signature, so there is nothing that could be valid",
463        ));
464    }
465
466    // Incomplete support is not invalidity. A signature at a placement this
467    // build does not describe cannot be judged, so it blocks the dossier with
468    // `unknown` instead of sinking it with the `failed` placement check it
469    // carries in its own right.
470    let unsupported: Vec<String> = signatures
471        .iter()
472        .filter(|signature| unsupported_placement_only(signature))
473        .map(|signature| signature.index.to_string())
474        .collect();
475    if !unsupported.is_empty() {
476        dossier_checks.push(Check::unknown(
477            CheckCode::SignaturesUnsupported,
478            format!(
479                "{} signature(s) sit at a placement this build does not support and could not be judged; indexes: {}",
480                unsupported.len(),
481                unsupported.join(", ")
482            ),
483        ));
484    }
485
486    // --- Stage H: document coverage ---------------------------------------
487    // Which modelled documents the signatures actually cover. This is a
488    // statement about the container, not about any signature: it changes no
489    // signature's checks or verdict, and no signature's verdict changes it.
490    let documents = coverage::document_coverage(
491        &context.dsig,
492        root_element,
493        namespace,
494        &dossier,
495        &signature_nodes,
496        &signatures,
497    );
498    dossier_checks.extend(coverage::coverage_checks(&documents));
499
500    let counts = Counts {
501        signatures: signatures.len(),
502        signatures_valid: count(&signatures, Verdict::Valid),
503        signatures_invalid: count(&signatures, Verdict::Invalid),
504        signatures_indeterminate: count(&signatures, Verdict::Indeterminate),
505        timestamps: dossier.timestamps_present,
506        timestamps_verified,
507        documents_covered: coverage::coverage_count(&documents, CoverageState::Covered),
508        documents_uncovered: coverage::coverage_count(&documents, CoverageState::Uncovered),
509        documents_undetermined: coverage::coverage_count(&documents, CoverageState::Undetermined),
510    };
511
512    let mut verdict = codes::verdict_of(&dossier_checks);
513    for signature in &signatures {
514        if unsupported_placement_only(signature) {
515            continue;
516        }
517        verdict = verdict.worst(signature.verdict);
518    }
519
520    Ok(VerifyReport {
521        verdict,
522        verification_time: VerificationTime {
523            requested: options.requested_time.clone(),
524            effective: format_rfc3339(context.time),
525            source: if options.requested_time.is_some() {
526                TimeSource::Requested
527            } else {
528                TimeSource::SystemClock
529            },
530        },
531        policy: PolicyReport::new(
532            options.trust.configured(),
533            options.allow_legacy_algorithms,
534            revocation_policy,
535        ),
536        limits: options.limits.clone(),
537        counts,
538        checks: dossier_checks,
539        timestamps: container_timestamps,
540        documents,
541        signatures,
542    })
543}
544
545/// Whether a signature is one this build could not judge at all *because of
546/// its placement*, and for no other reason.
547///
548/// Such a signature is left out of the dossier verdict: it carries a `failed`
549/// `sig_placement_invalid` so a caller reading its own entry sees exactly what
550/// happened, but a nesting this build does not implement is missing support,
551/// not evidence of forgery, and under ETSI EN 319 102-1 that is INDETERMINATE.
552/// The dossier is capped through the `signatures_unsupported` check instead. A
553/// signature that failed anything *else* is folded in as usual: a binding or a
554/// digest that actually fails is a finding whatever the placement.
555fn unsupported_placement_only(signature: &SignatureReport) -> bool {
556    signature.placement == SignatureScope::Unknown
557        && signature
558            .checks
559            .iter()
560            .filter(|check| check.status == CheckStatus::Failed)
561            .all(|check| check.code == CheckCode::SigPlacementInvalid)
562}
563
564fn count(signatures: &[SignatureReport], verdict: Verdict) -> usize {
565    signatures
566        .iter()
567        .filter(|signature| signature.verdict == verdict)
568        .count()
569}