pub struct SignedData {
    pub version: CmsVersion,
    pub digest_algorithms: DigestAlgorithmIdentifiers,
    pub content_info: EncapsulatedContentInfo,
    pub certificates: Option<CertificateSet>,
    pub crls: Option<RevocationInfoChoices>,
    pub signer_infos: SignerInfos,
}
Expand description

Represents signed data.

ASN.1 type specification:

SignedData ::= SEQUENCE {
  version CMSVersion,
  digestAlgorithms DigestAlgorithmIdentifiers,
  encapContentInfo EncapsulatedContentInfo,
  certificates [0] IMPLICIT CertificateSet OPTIONAL,
  crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
  signerInfos SignerInfos }

Fields§

§version: CmsVersion§digest_algorithms: DigestAlgorithmIdentifiers§content_info: EncapsulatedContentInfo§certificates: Option<CertificateSet>§crls: Option<RevocationInfoChoices>§signer_infos: SignerInfos

Implementations§

Attempt to decode BER encoded bytes to a parsed data structure.

Examples found in repository?
src/lib.rs (line 327)
326
327
328
    pub fn parse_ber(data: &[u8]) -> Result<Self, CmsError> {
        Self::try_from(&crate::asn1::rfc5652::SignedData::decode_ber(data)?)
    }
Examples found in repository?
src/asn1/rfc5652.rs (line 162)
161
162
163
    pub fn decode_ber(data: &[u8]) -> Result<Self, DecodeError<std::convert::Infallible>> {
        Constructed::decode(data, bcder::Mode::Ber, |cons| Self::decode(cons))
    }
More examples
Hide additional examples
src/lib.rs (line 958)
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
    fn try_from(signer_info: &crate::asn1::rfc5652::SignerInfo) -> Result<Self, Self::Error> {
        let (issuer, serial_number) = match &signer_info.sid {
            SignerIdentifier::IssuerAndSerialNumber(issuer) => {
                (issuer.issuer.clone(), issuer.serial_number.clone())
            }
            SignerIdentifier::SubjectKeyIdentifier(_) => {
                return Err(CmsError::SubjectKeyIdentifierUnsupported);
            }
        };

        let digest_algorithm = DigestAlgorithm::try_from(&signer_info.digest_algorithm)?;

        // The "signature" algorithm can also be a key algorithm identifier. So we
        // attempt to resolve using the more robust mechanism.
        let signature_algorithm = SignatureAlgorithm::from_oid_and_digest_algorithm(
            &signer_info.signature_algorithm.algorithm,
            digest_algorithm,
        )?;

        let signature = signer_info.signature.to_bytes().to_vec();

        let signed_attributes = if let Some(attributes) = &signer_info.signed_attributes {
            // Content type attribute MUST be present.
            let content_type = attributes
                .iter()
                .find(|attr| attr.typ == OID_CONTENT_TYPE)
                .ok_or(CmsError::MissingSignedAttributeContentType)?;

            // Content type attribute MUST have exactly 1 value.
            if content_type.values.len() != 1 {
                return Err(CmsError::MalformedSignedAttributeContentType);
            }

            let content_type = content_type
                .values
                .get(0)
                .unwrap()
                .deref()
                .clone()
                .decode(|cons| Oid::take_from(cons))
                .map_err(|_| CmsError::MalformedSignedAttributeContentType)?;

            // Message digest attribute MUST be present.
            let message_digest = attributes
                .iter()
                .find(|attr| attr.typ == OID_MESSAGE_DIGEST)
                .ok_or(CmsError::MissingSignedAttributeMessageDigest)?;

            // Message digest attribute MUST have exactly 1 value.
            if message_digest.values.len() != 1 {
                return Err(CmsError::MalformedSignedAttributeMessageDigest);
            }

            let message_digest = message_digest
                .values
                .get(0)
                .unwrap()
                .deref()
                .clone()
                .decode(|cons| OctetString::take_from(cons))
                .map_err(|_| CmsError::MalformedSignedAttributeMessageDigest)?
                .to_bytes()
                .to_vec();

            // Signing time is optional, but common. So we pull it out for convenience.
            let signing_time = attributes
                .iter()
                .find(|attr| attr.typ == OID_SIGNING_TIME)
                .map(|attr| {
                    if attr.values.len() != 1 {
                        Err(CmsError::MalformedSignedAttributeSigningTime)
                    } else {
                        let time = attr
                            .values
                            .get(0)
                            .unwrap()
                            .deref()
                            .clone()
                            .decode(|cons| Time::take_from(cons))?;

                        let time = chrono::DateTime::from(time);

                        Ok(time)
                    }
                })
                .transpose()?;

            Some(SignedAttributes {
                content_type,
                message_digest,
                signing_time,
                raw: attributes.clone(),
            })
        } else {
            None
        };

        let digested_signed_attributes_data = signer_info.signed_attributes_digested_content()?;

        let unsigned_attributes =
            if let Some(attributes) = &signer_info.unsigned_attributes {
                let time_stamp_token =
                    attributes
                        .iter()
                        .find(|attr| attr.typ == OID_TIME_STAMP_TOKEN)
                        .map(|attr| {
                            if attr.values.len() != 1 {
                                Err(CmsError::MalformedUnsignedAttributeTimeStampToken)
                            } else {
                                Ok(attr.values.get(0).unwrap().deref().clone().decode(|cons| {
                                    crate::asn1::rfc5652::SignedData::decode(cons)
                                })?)
                            }
                        })
                        .transpose()?;

                Some(UnsignedAttributes { time_stamp_token })
            } else {
                None
            };

        Ok(SignerInfo {
            issuer,
            serial_number,
            digest_algorithm,
            signature_algorithm,
            signature,
            signed_attributes,
            digested_signed_attributes_data,
            unsigned_attributes,
        })
    }
Examples found in repository?
src/time_stamp_protocol.rs (line 117)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    pub fn signed_data(&self) -> Result<Option<SignedData>, DecodeError<Infallible>> {
        if let Some(token) = &self.0.time_stamp_token {
            let source = token.content.clone();

            if token.content_type == OID_ID_SIGNED_DATA {
                Ok(Some(source.decode(|cons| SignedData::take_from(cons))?))
            } else {
                Err(source
                    .into_source()
                    .content_err("invalid OID on signed data"))
            }
        } else {
            Ok(None)
        }
    }
Examples found in repository?
src/signing.rs (line 389)
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    pub fn build_der(&self) -> Result<Vec<u8>, CmsError> {
        let mut signer_infos = SignerInfos::default();
        let mut seen_digest_algorithms = HashSet::new();
        let mut seen_certificates = self.certificates.clone();

        for signer in &self.signers {
            seen_digest_algorithms.insert(signer.digest_algorithm);

            if !seen_certificates
                .iter()
                .any(|x| x == &signer.signing_certificate)
            {
                seen_certificates.push(signer.signing_certificate.clone());
            }

            let version = CmsVersion::V1;
            let digest_algorithm = DigestAlgorithmIdentifier {
                algorithm: signer.digest_algorithm.into(),
                parameters: None,
            };

            let sid = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
                issuer: signer.signing_certificate.issuer_name().clone(),
                serial_number: signer.signing_certificate.serial_number_asn1().clone(),
            });

            // The message digest attribute is mandatory.
            //
            // Message digest is computed from override content on the signer
            // or the encapsulated content if present. The "empty" hash is a
            // valid value if no content (only signed attributes) are being signed.
            let mut hasher = signer.digest_algorithm.digester();
            if let Some(content) = &signer.message_id_content {
                hasher.update(content);
            } else {
                match &self.signed_content {
                    SignedContent::None => {}
                    SignedContent::Inline(content) | SignedContent::External(content) => {
                        hasher.update(content)
                    }
                }
            }
            let digest = hasher.finish();

            let mut signed_attributes = SignedAttributes::default();

            // The content-type field is mandatory.
            signed_attributes.push(Attribute {
                typ: Oid(Bytes::copy_from_slice(OID_CONTENT_TYPE.as_ref())),
                values: vec![AttributeValue::new(Captured::from_values(
                    Mode::Der,
                    signer.content_type.encode_ref(),
                ))],
            });

            // Set `messageDigest` field
            signed_attributes.push(Attribute {
                typ: Oid(Bytes::copy_from_slice(OID_MESSAGE_DIGEST.as_ref())),
                values: vec![AttributeValue::new(Captured::from_values(
                    Mode::Der,
                    digest.as_ref().encode(),
                ))],
            });

            // Add signing time because it is common to include.
            signed_attributes.push(Attribute {
                typ: Oid(Bytes::copy_from_slice(OID_SIGNING_TIME.as_ref())),
                values: vec![AttributeValue::new(Captured::from_values(
                    Mode::Der,
                    UtcTime::now().encode(),
                ))],
            });

            signed_attributes.extend(signer.extra_signed_attributes.iter().cloned());

            // According to RFC 5652, signed attributes are DER encoded. This means a SET
            // (which SignedAttributes is) should be sorted. But bcder doesn't appear to do
            // this. So we manually sort here.
            let signed_attributes = signed_attributes.as_sorted()?;

            let signed_attributes = Some(signed_attributes);

            let signature_algorithm = signer.signature_algorithm()?.into();

            // The function for computing the signed attributes digested content
            // is on SignerInfo. So construct an instance so we can compute the
            // signature.
            let mut signer_info = SignerInfo {
                version,
                sid,
                digest_algorithm,
                signed_attributes,
                signature_algorithm,
                signature: SignatureValue::new(Bytes::copy_from_slice(&[])),
                unsigned_attributes: None,
                signed_attributes_data: None,
            };

            // The content being signed is the DER encoded signed attributes, if present, or the
            // encapsulated content. Since we always create signed attributes above, it *must* be
            // the DER encoded signed attributes.
            let signed_content = signer_info
                .signed_attributes_digested_content()?
                .expect("presence of signed attributes should ensure this is Some(T)");

            let signature = signer.signing_key.try_sign(&signed_content)?;
            let signature_algorithm = signer.signing_key.signature_algorithm()?;

            signer_info.signature = SignatureValue::new(Bytes::from(signature.clone()));
            signer_info.signature_algorithm = signature_algorithm.into();

            if let Some(url) = &signer.time_stamp_url {
                // The message sent to the TSA (via a digest) is the signature of the signed data.
                let res = time_stamp_message_http(
                    url.clone(),
                    signature.as_ref(),
                    signer.digest_algorithm,
                )?;

                if !res.is_success() {
                    return Err(TimeStampError::Unsuccessful(res.clone()).into());
                }

                let signed_data = res
                    .signed_data()?
                    .ok_or(CmsError::TimeStampProtocol(TimeStampError::BadResponse))?;

                let mut unsigned_attributes = UnsignedAttributes::default();
                unsigned_attributes.push(Attribute {
                    typ: Oid(Bytes::copy_from_slice(OID_TIME_STAMP_TOKEN.as_ref())),
                    values: vec![AttributeValue::new(Captured::from_values(
                        Mode::Der,
                        signed_data.encode_ref(),
                    ))],
                });

                signer_info.unsigned_attributes = Some(unsigned_attributes);
            }

            signer_infos.push(signer_info);
        }

        let mut digest_algorithms = DigestAlgorithmIdentifiers::default();
        digest_algorithms.extend(seen_digest_algorithms.into_iter().map(|alg| {
            DigestAlgorithmIdentifier {
                algorithm: alg.into(),
                parameters: None,
            }
        }));

        // Many consumers prefer the issuing certificate to come before the issued
        // certificate. So we explicitly sort all the seen certificates in this order,
        // attempting for all issuing certificates to come before the issued.
        seen_certificates.sort_by(|a, b| a.compare_issuer(b));

        let mut certificates = CertificateSet::default();
        certificates.extend(
            seen_certificates
                .into_iter()
                .map(|cert| CertificateChoices::Certificate(Box::new(cert.into()))),
        );

        // The certificates could have been encountered in any order. For best results,
        // we want issuer certificates before their "children." So we apply sorting here.

        let signed_data = SignedData {
            version: CmsVersion::V1,
            digest_algorithms,
            content_info: EncapsulatedContentInfo {
                content_type: self.content_type.clone(),
                content: match &self.signed_content {
                    SignedContent::None | SignedContent::External(_) => None,
                    SignedContent::Inline(content) => {
                        Some(OctetString::new(Bytes::copy_from_slice(content)))
                    }
                },
            },
            certificates: if certificates.is_empty() {
                None
            } else {
                Some(certificates)
            },
            crls: None,
            signer_infos,
        };

        let mut ber = Vec::new();
        signed_data
            .encode_ref()
            .write_encoded(Mode::Der, &mut ber)?;

        Ok(ber)
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
The type returned in the event of a conversion error.
Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more