-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpkcs7.rs
More file actions
2508 lines (2350 loc) · 105 KB
/
Copy pathpkcs7.rs
File metadata and controls
2508 lines (2350 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! PKCS#7 `SignedData` production for a standalone Rust signer (Tier 1a completion).
//!
//! Today, signing remains OS-delegated (`SignerSignEx3` / `mssign32` in `psign`). A future path may use
//! Windows `CryptMsgOpenToEncode` or the `cms` crate to assemble `SPC_INDIRECT_DATA` and embed `WIN_CERTIFICATE` entries.
//!
//! Format-specific **subject digests** feeding `SpcIndirectData` live elsewhere: [`crate::pe_digest`] (PE image hash),
//! [`crate::cab_digest`] (MSCF CAB layout), [`crate::msi_digest`] (OLE compound), [`crate::msix_digest`] (APPX AX\* blob under OID **`1.3.6.1.4.1.311.2.1.30`**), etc. Encoding those payloads into PKCS#7 is the missing producer piece; [`crate::pe_embed`] can append **`WIN_CERTIFICATE`** rows once PKCS#7 DER exists.
//!
//! **Milestone:** The **`authenticode`** crate publishes ASN.1 structs (`SpcIndirectDataContent`, `DigestInfo`, …) with `der` **Decode**/**Encode**.
//! [`parse_pe_pkcs7_spc_indirect_data_at`] / [`parse_pe_pkcs7_spc_indirect_data`] and [`spc_indirect_data_replace_message_digest`] support **Linux-side digest substitution** before a future **`SignedData`** signer assembles countersignatures / PKCS#9 attributes. [`cms_digest_encapsulated_econtent_bytes`] and [`signer_info_pkcs9_message_digest_octets`] pin **RFC 5652 §5.4** **`eContent`** hashing to PKCS#9 **`messageDigest`** on fixtures (RustCrypto **`cms` SignerInfoBuilder** semantics). [`signer_info_signed_attributes_sequence_der`] yields the **`SET OF Attribute`** octets for §5.4 authenticated-attribute signing; [`signed_attributes_replace_pkcs9_message_digest`] refreshes PKCS#9 **`messageDigest`** after **`encapContentInfo`** changes (**`encryptedDigest`** still requires re-sign). [`signer_info_sha256_digest_over_signed_attrs`] and [`signed_data_rsa_sha256_signer_prehash_digest`] **SHA-256**-hash **of** that **`SET`** (staging digest before PKCS#1 **DigestInfo** / **KV `RS256`** validation). [`signer_info_clone_with_signed_attrs`] / [`signer_info_clone_with_signature_octets`] patch **`SignerInfo`** after remote signing; [`signed_data_replace_signer_info_at`] / [`signed_data_replace_first_signer_info`] splice it back into **`SignedData.signerInfos`**. **`WIN_CERTIFICATE`** embedding remains [`crate::pe_embed`].
use anyhow::{Context as _, Result, anyhow};
pub use authenticode::SpcIndirectDataContent;
use authenticode::{DigestInfo, SpcAttributeTypeAndOptionalValue};
use base64::Engine as _;
use cms::builder::{SignedDataBuilder, SignerInfoBuilder};
use cms::cert::CertificateChoices;
use cms::cert::IssuerAndSerialNumber;
use cms::content_info::{CmsVersion, ContentInfo};
use cms::signed_data::{
CertificateSet, EncapsulatedContentInfo, SignatureValue, SignedAttributes, SignedData,
SignerIdentifier, SignerInfo, SignerInfos,
};
use der::asn1::{Any, AnyRef, ObjectIdentifier, OctetString, OctetStringRef, SetOfVec, UtcTime};
use der::{Decode, Encode, Reader, SliceReader, Tag, TagNumber};
use digest::Digest as _;
use rsa::RsaPrivateKey;
use sha2::{Sha256, Sha384, Sha512};
use x509_cert::Certificate;
use x509_cert::attr::Attribute;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage, SubjectKeyIdentifier};
use x509_cert::spki::AlgorithmIdentifierOwned;
/// CMS **`signedData`** content type OID (`id-signedData`).
const ID_SIGNED_DATA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2");
/// Authenticode PE image-data OID (`SPC_PE_IMAGE_DATA_OBJID`).
const SPC_PE_IMAGE_DATA_OBJID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.2.1.15");
/// CAB Authenticode data OID observed in Windows CAB signatures (`SPC_LINK_OBJID`).
const SPC_CAB_LINK_OBJID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.2.1.28");
/// Windows Installer Authenticode data OID observed in MSI signatures (`SPC_SIGINFO_OBJID`).
const SPC_MSI_SIGINFO_OBJID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.2.1.30");
/// Stable minimal `SpcPeImageData` body used by Windows SignTool for PE Authenticode.
///
/// This is the DER **value** of the `SEQUENCE`:
/// `BIT STRING ''`, followed by an obsolete `SpcLink` placeholder (`<<<Obsolete>>>`).
const SPC_PE_IMAGE_DATA_VALUE: &[u8] = &[
0x03, 0x01, 0x00, 0xa0, 0x20, 0xa2, 0x1e, 0x80, 0x1c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00,
0x4f, 0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x74, 0x00, 0x65, 0x00,
0x3e, 0x00, 0x3e, 0x00, 0x3e,
];
/// Stable CAB `SpcLink` value DER observed in Windows CAB Authenticode signatures.
const SPC_CAB_LINK_VALUE_DER: &[u8] = &[
0xa1, 0x48, 0x04, 0x10, 0xa6, 0xb5, 0x86, 0xd5, 0xb4, 0xa1, 0x24, 0x66, 0xae, 0x05, 0xa2, 0x17,
0xda, 0x8e, 0x60, 0xd6, 0x04, 0x34, 0x31, 0x32, 0x30, 0x30, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04,
0x01, 0x82, 0x37, 0x02, 0x05, 0x01, 0x31, 0x22, 0x04, 0x20, 0x1f, 0xa1, 0x2d, 0xdc, 0xd1, 0x11,
0x50, 0x32, 0xe8, 0x90, 0x3f, 0x91, 0x52, 0x54, 0xb2, 0x19, 0x3a, 0x87, 0x34, 0xb1, 0x7e, 0x92,
0x10, 0xd5, 0x52, 0x10, 0x8b, 0x77, 0x16, 0xee, 0x52, 0x9b,
];
/// Stable MSI `SpcSigInfo` value DER observed in Windows MSI/MSP Authenticode signatures.
const SPC_MSI_SIGINFO_VALUE_DER: &[u8] = &[
0x30, 0x24, 0x02, 0x01, 0x02, 0x04, 0x10, 0xf1, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00,
0x02, 0x01, 0x00, 0x02, 0x01, 0x00,
];
/// Stable PowerShell `SpcSigInfo` value DER observed in `signtool sign` script signatures.
const SPC_SCRIPT_SIGINFO_VALUE_DER: &[u8] = &[
0x30, 0x26, 0x02, 0x03, 0x01, 0x00, 0x00, 0x04, 0x10, 0x1f, 0xcc, 0x3b, 0x60, 0x59, 0x4b, 0x08,
0x4e, 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02,
0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00,
];
/// **`SignerInfo.digestAlgorithm`** / **`DigestInfo.digestAlgorithm`** SHA-1 OID.
const DIGEST_OID_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.26");
/// SHA-256 OID (**`id-sha256`**).
const DIGEST_OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
/// SHA-384 OID (**`id-sha384`**).
const DIGEST_OID_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
/// SHA-512 OID (**`id-sha512`**).
const DIGEST_OID_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");
/// PKCS#9 **`messageDigest`** authenticated-attribute type OID.
pub const PKCS9_MESSAGE_DIGEST_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.4");
/// PKCS#9 **`contentType`** authenticated-attribute type OID.
pub const PKCS9_CONTENT_TYPE_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.3");
/// PKCS#9 **`signingTime`** authenticated-attribute type OID.
pub const PKCS9_SIGNING_TIME_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.5");
/// Microsoft Authenticode RFC3161 timestamp-token unsigned attribute.
pub const MS_RFC3161_TIMESTAMP_TOKEN_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.3.3.1");
/// CMS/PKCS#9 RFC3161 timestamp-token unsigned attribute (`id-aa-timeStampToken`).
pub const PKCS9_RFC3161_TIMESTAMP_TOKEN_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.2.14");
/// CAdES commitment-type-indication signed attribute (`id-smime-aa-ets-commitmentType`).
pub const PKCS9_COMMITMENT_TYPE_INDICATION_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.2.16");
/// ESS signing-certificate-v2 signed attribute (`id-aa-signingCertificateV2`).
pub const PKCS9_SIGNING_CERTIFICATE_V2_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.2.47");
/// NuGet author signature commitment type (`id-smime-cti-ets-proofOfOrigin`).
pub const COMMITMENT_TYPE_IDENTIFIER_PROOF_OF_ORIGIN_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.6.1");
/// CMS **`data`** content type OID (`id-data`).
pub const PKCS7_ID_DATA_OID: &str = "1.2.840.113549.1.7.1";
/// CMS **`signedData`** content type OID (string form).
pub const PKCS7_ID_SIGNED_DATA_OID: &str = "1.2.840.113549.1.7.2";
/// Signed-attribute profile for generic CMS `SignedData` signatures.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Pkcs7SignedAttributeProfile {
/// RFC 5652 minimum attributes generated by RustCrypto CMS: `contentType` and `messageDigest`.
Basic,
/// NuGet author package signature attributes needed for NuGet tooling to classify the primary
/// package signature as a publisher/author signature.
NuGetAuthor,
/// NuGet author attributes that are stable across split prehash/from-signature CLI steps.
///
/// One-shot signing should prefer [`Self::NuGetAuthor`]. Split signing cannot safely include a
/// fresh `signingTime` unless the exact signed attributes are persisted between steps.
NuGetAuthorWithoutSigningTime,
}
impl Pkcs7SignedAttributeProfile {
pub fn requires_signer_certificate(self) -> bool {
matches!(
self,
Self::NuGetAuthor | Self::NuGetAuthorWithoutSigningTime
)
}
}
/// Whether CMS `SignedData.encapContentInfo` embeds the signed content.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Pkcs7ContentMode {
/// Include the encoded `eContent` in `SignedData`.
Attached,
/// Omit `eContent` while signing the same bytes.
Detached,
}
impl Pkcs7ContentMode {
fn embeds_content(self) -> bool {
matches!(self, Self::Attached)
}
}
/// Digest algorithms supported by the portable Authenticode CMS producer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AuthenticodeSigningDigest {
/// SHA-256 (`id-sha256`) with RSA PKCS#1 v1.5 `sha256WithRSAEncryption`.
Sha256,
/// SHA-384 (`id-sha384`) with RSA PKCS#1 v1.5 `sha384WithRSAEncryption`.
Sha384,
/// SHA-512 (`id-sha512`) with RSA PKCS#1 v1.5 `sha512WithRSAEncryption`.
Sha512,
}
impl AuthenticodeSigningDigest {
/// Matching PE image digest kind.
pub fn pe_hash_kind(self) -> crate::pe_digest::PeAuthenticodeHashKind {
match self {
Self::Sha256 => crate::pe_digest::PeAuthenticodeHashKind::Sha256,
Self::Sha384 => crate::pe_digest::PeAuthenticodeHashKind::Sha384,
Self::Sha512 => crate::pe_digest::PeAuthenticodeHashKind::Sha512,
}
}
fn digest_algorithm(self) -> AlgorithmIdentifierOwned {
AlgorithmIdentifierOwned {
oid: match self {
Self::Sha256 => DIGEST_OID_SHA256,
Self::Sha384 => DIGEST_OID_SHA384,
Self::Sha512 => DIGEST_OID_SHA512,
},
parameters: None,
}
}
fn rsa_signature_algorithm(self) -> AlgorithmIdentifierOwned {
AlgorithmIdentifierOwned {
oid: match self {
Self::Sha256 => ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11"),
Self::Sha384 => ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12"),
Self::Sha512 => ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13"),
},
parameters: Some(Any::from(AnyRef::NULL)),
}
}
fn digest_bytes(self, bytes: &[u8]) -> Vec<u8> {
match self {
Self::Sha256 => Sha256::digest(bytes).to_vec(),
Self::Sha384 => Sha384::digest(bytes).to_vec(),
Self::Sha512 => Sha512::digest(bytes).to_vec(),
}
}
}
/// Build the Authenticode `SpcIndirectDataContent` for a PE image digest.
pub fn pe_spc_indirect_data(
digest_algorithm: AuthenticodeSigningDigest,
pe_digest: &[u8],
) -> Result<SpcIndirectDataContent> {
spc_indirect_data(
digest_algorithm,
pe_digest,
SPC_PE_IMAGE_DATA_OBJID,
Any::new(Tag::Sequence, SPC_PE_IMAGE_DATA_VALUE)
.map_err(|e| anyhow!("SPC_PE_IMAGE_DATA Any: {e}"))?,
"PE",
)
}
/// Build the Authenticode `SpcIndirectDataContent` for a CAB file digest.
pub fn cab_spc_indirect_data(
digest_algorithm: AuthenticodeSigningDigest,
cab_digest: &[u8],
) -> Result<SpcIndirectDataContent> {
spc_indirect_data(
digest_algorithm,
cab_digest,
SPC_CAB_LINK_OBJID,
Any::from_der(SPC_CAB_LINK_VALUE_DER).map_err(|e| anyhow!("SPC_CAB_LINK Any: {e}"))?,
"CAB",
)
}
/// Build the Authenticode `SpcIndirectDataContent` for an MSI/MSP OLE package digest.
pub fn msi_spc_indirect_data(
digest_algorithm: AuthenticodeSigningDigest,
msi_digest: &[u8],
) -> Result<SpcIndirectDataContent> {
spc_indirect_data(
digest_algorithm,
msi_digest,
SPC_MSI_SIGINFO_OBJID,
Any::from_der(SPC_MSI_SIGINFO_VALUE_DER)
.map_err(|e| anyhow!("SPC_MSI_SIGINFO Any: {e}"))?,
"MSI",
)
}
/// Build the Authenticode `SpcIndirectDataContent` for a PowerShell-class script digest.
pub fn script_spc_indirect_data(
digest_algorithm: AuthenticodeSigningDigest,
script_digest: &[u8],
) -> Result<SpcIndirectDataContent> {
spc_indirect_data(
digest_algorithm,
script_digest,
SPC_MSI_SIGINFO_OBJID,
Any::from_der(SPC_SCRIPT_SIGINFO_VALUE_DER)
.map_err(|e| anyhow!("SPC_SCRIPT_SIGINFO Any: {e}"))?,
"script",
)
}
fn spc_indirect_data(
digest_algorithm: AuthenticodeSigningDigest,
subject_digest: &[u8],
value_type: ObjectIdentifier,
value: Any,
label: &str,
) -> Result<SpcIndirectDataContent> {
let expected = digest_algorithm.pe_hash_kind().digest_output_len();
if subject_digest.len() != expected {
return Err(anyhow!(
"{label} digest length {} does not match {:?} ({expected} octets)",
subject_digest.len(),
digest_algorithm
));
}
let digest = OctetString::new(subject_digest.to_vec())
.map_err(|e| anyhow!("SpcIndirectData digest OCTET STRING: {e}"))?;
Ok(SpcIndirectDataContent {
data: SpcAttributeTypeAndOptionalValue { value_type, value },
message_digest: DigestInfo {
digest_algorithm: digest_algorithm.digest_algorithm(),
digest,
},
})
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for a CAB Authenticode signature using an RSA private key.
pub fn create_cab_authenticode_pkcs7_der_rsa(
cab_image: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
let cab_digest = crate::cab_digest::cab_authenticode_digest_for_signing(
cab_image,
digest_algorithm.pe_hash_kind(),
)?;
let indirect = cab_spc_indirect_data(digest_algorithm, &cab_digest)?;
create_authenticode_pkcs7_der_rsa(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for an MSI/MSP Authenticode signature using an RSA private key.
pub fn create_msi_authenticode_pkcs7_der_rsa(
msi_image: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
let msi_digest = crate::msi_digest::compute_msi_authenticode_digest(
msi_image,
digest_algorithm.pe_hash_kind(),
)?;
let indirect = msi_spc_indirect_data(digest_algorithm, &msi_digest)?;
create_authenticode_pkcs7_der_rsa(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for a cleartext MSIX / APPX package.
///
/// `package_with_signature_part` must already contain the final `[Content_Types].xml`
/// declaration and an `AppxSignature.p7x` placeholder. The signature part bytes are
/// excluded from the APPX digest blob by the MSIX SIP hash routine.
pub fn create_msix_authenticode_pkcs7_der_rsa(
package_with_signature_part: &[u8],
extension: &str,
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
let indirect =
msix_spc_indirect_data(package_with_signature_part, extension, digest_algorithm)?;
create_authenticode_pkcs7_der_rsa(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Build the Authenticode `SpcIndirectDataContent` for a cleartext MSIX / APPX package.
pub fn msix_spc_indirect_data(
package_with_signature_part: &[u8],
extension: &str,
digest_algorithm: AuthenticodeSigningDigest,
) -> Result<SpcIndirectDataContent> {
let (kind, appx_blob) =
crate::msix_digest::msix_authenticode_digest_blob(package_with_signature_part, extension)?;
if kind != digest_algorithm.pe_hash_kind() {
return Err(anyhow!(
"MSIX AppxBlockMap HashMethod {:?} does not match requested signing digest {:?}",
kind,
digest_algorithm
));
}
Ok(SpcIndirectDataContent {
data: SpcAttributeTypeAndOptionalValue {
value_type: SPC_MSI_SIGINFO_OBJID,
value: Any::from_der(SPC_MSI_SIGINFO_VALUE_DER)
.map_err(|e| anyhow!("SPC_MSIX_SIGINFO Any: {e}"))?,
},
message_digest: DigestInfo {
digest_algorithm: digest_algorithm.digest_algorithm(),
digest: OctetString::new(appx_blob)
.map_err(|e| anyhow!("APPX SpcIndirectData digest OCTET STRING: {e}"))?,
},
})
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for a PE Authenticode signature using an RSA private key.
///
/// This is the portable CMS producer used before format-specific embedding (for PE, `pe_embed` wraps the
/// returned DER in a `WIN_CERTIFICATE`). It intentionally supports the modern RSA/SHA-2 subset first.
pub fn create_pe_authenticode_pkcs7_der_rsa(
pe_image: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
let pe_digest =
crate::pe_digest::pe_authenticode_digest(pe_image, digest_algorithm.pe_hash_kind())?;
let indirect = pe_spc_indirect_data(digest_algorithm, &pe_digest)?;
create_authenticode_pkcs7_der_rsa(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for a PowerShell-class Authenticode script.
pub fn create_script_authenticode_pkcs7_der_rsa(
script: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
let indirect = script_authenticode_spc_indirect_data(script, digest_algorithm)?;
create_authenticode_pkcs7_der_rsa(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Build the Authenticode `SpcIndirectDataContent` for a PowerShell-class script.
pub fn script_authenticode_spc_indirect_data(
script: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
) -> Result<SpcIndirectDataContent> {
let units = crate::ps_script::file_utf16_units(script);
let script_digest = crate::ps_script::hash_payload(
digest_algorithm.pe_hash_kind(),
&crate::ps_script::utf16le_bytes(&units),
)?;
script_spc_indirect_data(digest_algorithm, &script_digest)
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for an Authenticode `SpcIndirectDataContent`.
pub fn create_authenticode_pkcs7_der_rsa(
indirect: SpcIndirectDataContent,
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
match digest_algorithm {
AuthenticodeSigningDigest::Sha256 => {
create_authenticode_pkcs7_der_rsa_for_digest::<Sha256, rsa::pkcs1v15::Signature>(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
AuthenticodeSigningDigest::Sha384 => {
create_authenticode_pkcs7_der_rsa_for_digest::<Sha384, rsa::pkcs1v15::Signature>(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
AuthenticodeSigningDigest::Sha512 => {
create_authenticode_pkcs7_der_rsa_for_digest::<Sha512, rsa::pkcs1v15::Signature>(
indirect,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
}
}
/// Return the digest that a remote RSA PKCS#1 v1.5 signer must sign for this Authenticode payload.
///
/// The returned bytes are the SHA-2 digest of DER `SignedAttributes` (`SET OF Attribute`) per RFC 5652 §5.4.
/// Pass the corresponding raw signature to [`create_authenticode_pkcs7_der_with_rsa_signature`].
pub fn authenticode_remote_rsa_signed_attrs_digest(
indirect: &SpcIndirectDataContent,
digest_algorithm: AuthenticodeSigningDigest,
) -> Result<Vec<u8>> {
let attrs = authenticode_signed_attrs(indirect, digest_algorithm)?;
let der = signed_attributes_der(&attrs)?;
Ok(digest_algorithm.digest_bytes(&der))
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER from externally produced RSA PKCS#1 v1.5 signature bytes.
///
/// This supports remote signers such as Key Vault or Trusted Signing once the caller has signed
/// [`authenticode_remote_rsa_signed_attrs_digest`] with the matching RSA/SHA-2 algorithm.
pub fn create_authenticode_pkcs7_der_with_rsa_signature(
indirect: SpcIndirectDataContent,
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
encrypted_digest: &[u8],
) -> Result<Vec<u8>> {
let attrs = authenticode_signed_attrs(&indirect, digest_algorithm)?;
let signer_id = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
issuer: signer_cert.tbs_certificate.issuer.clone(),
serial_number: signer_cert.tbs_certificate.serial_number.clone(),
});
let signer_info = SignerInfo {
version: CmsVersion::V1,
sid: signer_id,
digest_alg: digest_algorithm.digest_algorithm(),
signed_attrs: Some(attrs),
signature_algorithm: digest_algorithm.rsa_signature_algorithm(),
signature: SignatureValue::new(encrypted_digest.to_vec())
.map_err(|e| anyhow!("SignerInfo.signature OCTET STRING: {e}"))?,
unsigned_attrs: None,
};
let indirect_der = encode_spc_indirect_data_der(&indirect)?;
let mut rd = SliceReader::new(indirect_der.as_slice())
.map_err(|e| anyhow!("indirect DER reader: {e}"))?;
let econtent = Any::decode(&mut rd).map_err(|e| anyhow!("SpcIndirectData as CMS Any: {e}"))?;
rd.finish(())
.map_err(|e| anyhow!("trailing octets after SpcIndirectDataContent DER: {e}"))?;
let digest_algorithms = SetOfVec::try_from(vec![digest_algorithm.digest_algorithm()])
.map_err(|e| anyhow!("DigestAlgorithmIdentifiers SET: {e}"))?;
let mut certs = Vec::with_capacity(chain_certs.len() + 1);
certs.push(CertificateChoices::Certificate(signer_cert));
certs.extend(chain_certs.into_iter().map(CertificateChoices::Certificate));
let certificates = Some(CertificateSet(
SetOfVec::try_from(certs).map_err(|e| anyhow!("CertificateSet SET: {e}"))?,
));
let signer_infos = SignerInfos(
SetOfVec::try_from(vec![signer_info]).map_err(|e| anyhow!("SignerInfos SET: {e}"))?,
);
let sd = SignedData {
version: CmsVersion::V1,
digest_algorithms,
encap_content_info: EncapsulatedContentInfo {
econtent_type: authenticode::SPC_INDIRECT_DATA_OBJID,
econtent: Some(econtent),
},
certificates,
crls: None,
signer_infos,
};
encode_pkcs7_content_info_signed_data_der(&sd)
}
/// Return the digest a remote RSA signer must sign for a generic CMS `SignedData` document.
///
/// The returned bytes are the SHA-2 digest of DER `SignedAttributes` (`SET OF Attribute`) per
/// RFC 5652 §5.4. Pass the raw RSA PKCS#1 v1.5 signature over this digest to
/// [`create_pkcs7_signed_data_der_with_rsa_signature`].
pub fn pkcs7_remote_rsa_signed_attrs_digest(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
) -> Result<Vec<u8>> {
pkcs7_remote_rsa_signed_attrs_digest_with_profile(
econtent_type,
econtent_der,
digest_algorithm,
Pkcs7SignedAttributeProfile::Basic,
None,
)
}
/// Return the digest a remote RSA signer must sign for a generic CMS `SignedData` profile.
pub fn pkcs7_remote_rsa_signed_attrs_digest_with_profile(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
profile: Pkcs7SignedAttributeProfile,
signer_cert: Option<&Certificate>,
) -> Result<Vec<u8>> {
let attrs = pkcs7_signed_attrs(
econtent_type,
econtent_der,
digest_algorithm,
profile,
signer_cert,
)?;
pkcs7_signed_attrs_digest(&attrs, digest_algorithm)
}
/// Return the digest a remote RSA signer must sign for already-built CMS signed attributes.
pub fn pkcs7_signed_attrs_digest(
attrs: &SignedAttributes,
digest_algorithm: AuthenticodeSigningDigest,
) -> Result<Vec<u8>> {
let der = signed_attributes_der(attrs)?;
Ok(digest_algorithm.digest_bytes(&der))
}
/// Create generic PKCS#7 `ContentInfo(SignedData)` DER from externally produced RSA signature bytes.
///
/// `econtent_der` must be one complete DER TLV for the value whose digest appears in PKCS#9
/// `messageDigest`. Set `detached` to omit the encapsulated content from the resulting CMS while
/// still signing the supplied `econtent_der`; this matches NuGet/App Installer companion flows.
pub fn create_pkcs7_signed_data_der_with_rsa_signature(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
encrypted_digest: &[u8],
content_mode: Pkcs7ContentMode,
) -> Result<Vec<u8>> {
let attrs = pkcs7_signed_attrs(
econtent_type,
econtent_der,
digest_algorithm,
Pkcs7SignedAttributeProfile::Basic,
None,
)?;
create_pkcs7_signed_data_der_with_signed_attrs_and_rsa_signature(Pkcs7SignedDataDerInput {
econtent_type,
econtent_der,
digest_algorithm,
signer_cert,
chain_certs,
encrypted_digest,
content_mode,
signed_attrs: attrs,
})
}
/// Create generic PKCS#7 `ContentInfo(SignedData)` DER from externally produced RSA signature bytes
/// and caller-supplied signed attributes. The caller must ensure `encrypted_digest` signs the DER
/// encoding of `signed_attrs`.
pub struct Pkcs7SignedDataDerInput<'a> {
pub econtent_type: ObjectIdentifier,
pub econtent_der: &'a [u8],
pub digest_algorithm: AuthenticodeSigningDigest,
pub signer_cert: Certificate,
pub chain_certs: Vec<Certificate>,
pub encrypted_digest: &'a [u8],
pub content_mode: Pkcs7ContentMode,
pub signed_attrs: SignedAttributes,
}
pub fn create_pkcs7_signed_data_der_with_signed_attrs_and_rsa_signature(
input: Pkcs7SignedDataDerInput<'_>,
) -> Result<Vec<u8>> {
let signer_id = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
issuer: input.signer_cert.tbs_certificate.issuer.clone(),
serial_number: input.signer_cert.tbs_certificate.serial_number.clone(),
});
let signer_info = SignerInfo {
version: CmsVersion::V1,
sid: signer_id,
digest_alg: input.digest_algorithm.digest_algorithm(),
signed_attrs: Some(input.signed_attrs),
signature_algorithm: input.digest_algorithm.rsa_signature_algorithm(),
signature: SignatureValue::new(input.encrypted_digest.to_vec())
.map_err(|e| anyhow!("SignerInfo.signature OCTET STRING: {e}"))?,
unsigned_attrs: None,
};
let mut rd = SliceReader::new(input.econtent_der)
.map_err(|e| anyhow!("encapsulated content DER reader: {e}"))?;
let econtent =
Any::decode(&mut rd).map_err(|e| anyhow!("encapsulated content as CMS Any: {e}"))?;
rd.finish(())
.map_err(|e| anyhow!("trailing octets after encapsulated content DER: {e}"))?;
let digest_algorithms = SetOfVec::try_from(vec![input.digest_algorithm.digest_algorithm()])
.map_err(|e| anyhow!("DigestAlgorithmIdentifiers SET: {e}"))?;
let mut certs = Vec::with_capacity(input.chain_certs.len() + 1);
certs.push(CertificateChoices::Certificate(input.signer_cert));
certs.extend(
input
.chain_certs
.into_iter()
.map(CertificateChoices::Certificate),
);
let certificates = Some(CertificateSet(
SetOfVec::try_from(certs).map_err(|e| anyhow!("CertificateSet SET: {e}"))?,
));
let signer_infos = SignerInfos(
SetOfVec::try_from(vec![signer_info]).map_err(|e| anyhow!("SignerInfos SET: {e}"))?,
);
let sd = SignedData {
version: CmsVersion::V1,
digest_algorithms,
encap_content_info: EncapsulatedContentInfo {
econtent_type: input.econtent_type,
econtent: input.content_mode.embeds_content().then_some(econtent),
},
certificates,
crls: None,
signer_infos,
};
encode_pkcs7_content_info_signed_data_der(&sd)
}
/// Create unsigned PKCS#7 `ContentInfo(SignedData)` DER for an arbitrary attached content type.
///
/// Windows file catalogs created for later signing are CMS `SignedData` documents that can carry
/// Microsoft CTL content before any `SignerInfo` has been added.
pub fn create_pkcs7_unsigned_signed_data_der(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AlgorithmIdentifierOwned,
) -> Result<Vec<u8>> {
let mut rd = SliceReader::new(econtent_der)
.map_err(|e| anyhow!("encapsulated content DER reader: {e}"))?;
let econtent =
Any::decode(&mut rd).map_err(|e| anyhow!("encapsulated content as CMS Any: {e}"))?;
rd.finish(())
.map_err(|e| anyhow!("trailing octets after encapsulated content DER: {e}"))?;
let digest_algorithms = SetOfVec::try_from(vec![digest_algorithm])
.map_err(|e| anyhow!("DigestAlgorithmIdentifiers SET: {e}"))?;
let sd = SignedData {
version: CmsVersion::V1,
digest_algorithms,
encap_content_info: EncapsulatedContentInfo {
econtent_type,
econtent: Some(econtent),
},
certificates: None,
crls: None,
signer_infos: SignerInfos(SetOfVec::new()),
};
encode_pkcs7_content_info_signed_data_der(&sd)
}
/// Attach a raw RFC3161 `timeStampToken` `ContentInfo` as a Microsoft Authenticode unsigned attribute.
pub fn signed_data_add_rfc3161_timestamp_token(
sd: &SignedData,
signer_index: usize,
timestamp_token_der: &[u8],
) -> Result<SignedData> {
signed_data_add_rfc3161_timestamp_token_with_oid(
sd,
signer_index,
timestamp_token_der,
MS_RFC3161_TIMESTAMP_TOKEN_OID,
)
}
/// Attach a raw RFC3161 `timeStampToken` `ContentInfo` as a CMS/PKCS#9 unsigned attribute.
pub fn signed_data_add_pkcs9_rfc3161_timestamp_token(
sd: &SignedData,
signer_index: usize,
timestamp_token_der: &[u8],
) -> Result<SignedData> {
signed_data_add_rfc3161_timestamp_token_with_oid(
sd,
signer_index,
timestamp_token_der,
PKCS9_RFC3161_TIMESTAMP_TOKEN_OID,
)
}
/// Attach a raw RFC3161 `timeStampToken` `ContentInfo` as an unsigned attribute with the supplied OID.
pub fn signed_data_add_rfc3161_timestamp_token_with_oid(
sd: &SignedData,
signer_index: usize,
timestamp_token_der: &[u8],
timestamp_attr_oid: ObjectIdentifier,
) -> Result<SignedData> {
let signers = sd.signer_infos.0.as_slice();
let si = signers.get(signer_index).ok_or_else(|| {
anyhow!(
"SignerInfo index {} out of range (len {})",
signer_index,
signers.len()
)
})?;
let token_der = crate::pkcs7_wire::pkcs7_outer_sequence_prefix(timestamp_token_der)
.unwrap_or(timestamp_token_der);
let mut rd =
SliceReader::new(token_der).map_err(|e| anyhow!("timestamp token DER reader: {e}"))?;
let token_any =
Any::decode(&mut rd).map_err(|e| anyhow!("timestamp token ContentInfo: {e}"))?;
rd.finish(())
.map_err(|e| anyhow!("trailing octets after timestamp token ContentInfo: {e}"))?;
let mut values = SetOfVec::new();
values
.insert(token_any)
.map_err(|e| anyhow!("timestamp AttributeValue SET: {e}"))?;
let timestamp_attr = Attribute {
oid: timestamp_attr_oid,
values,
};
let mut attrs: Vec<Attribute> = si
.unsigned_attrs
.as_ref()
.map(|attrs| attrs.iter().cloned().collect())
.unwrap_or_default();
attrs.retain(|attr| attr.oid != timestamp_attr_oid);
attrs.push(timestamp_attr);
let mut stamped = si.clone();
stamped.unsigned_attrs = Some(
SetOfVec::try_from(attrs)
.map_err(|e| anyhow!("UnsignedAttributes SET canonicalization: {e}"))?,
);
signed_data_replace_signer_info_at(sd, signer_index, stamped)
}
fn create_authenticode_pkcs7_der_rsa_for_digest<D, Sig>(
indirect: SpcIndirectDataContent,
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>>
where
D: digest::Digest + rsa::pkcs8::AssociatedOid + rsa::pkcs1v15::RsaSignatureAssociatedOid,
rsa::pkcs1v15::SigningKey<D>: rsa::signature::Keypair
+ rsa::signature::Signer<Sig>
+ x509_cert::spki::DynSignatureAlgorithmIdentifier,
Sig: x509_cert::spki::SignatureBitStringEncoding,
{
let indirect_der = encode_spc_indirect_data_der(&indirect)?;
create_pkcs7_signed_data_der_rsa_for_digest::<D, Sig>(
authenticode::SPC_INDIRECT_DATA_OBJID,
&indirect_der,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
/// Create PKCS#7 `ContentInfo(SignedData)` DER for an arbitrary encapsulated content type using an RSA private key.
///
/// This is shared by Authenticode `SpcIndirectDataContent` producers and Microsoft CTL/catalog
/// authoring. `econtent_der` must be one complete DER TLV for the value placed inside
/// `EncapsulatedContentInfo.eContent`.
pub fn create_pkcs7_signed_data_der_rsa(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>> {
match digest_algorithm {
AuthenticodeSigningDigest::Sha256 => {
create_pkcs7_signed_data_der_rsa_for_digest::<Sha256, rsa::pkcs1v15::Signature>(
econtent_type,
econtent_der,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
AuthenticodeSigningDigest::Sha384 => {
create_pkcs7_signed_data_der_rsa_for_digest::<Sha384, rsa::pkcs1v15::Signature>(
econtent_type,
econtent_der,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
AuthenticodeSigningDigest::Sha512 => {
create_pkcs7_signed_data_der_rsa_for_digest::<Sha512, rsa::pkcs1v15::Signature>(
econtent_type,
econtent_der,
digest_algorithm,
signer_cert,
chain_certs,
private_key,
)
}
}
}
fn create_pkcs7_signed_data_der_rsa_for_digest<D, Sig>(
econtent_type: ObjectIdentifier,
econtent_der: &[u8],
digest_algorithm: AuthenticodeSigningDigest,
signer_cert: Certificate,
chain_certs: Vec<Certificate>,
private_key: RsaPrivateKey,
) -> Result<Vec<u8>>
where
D: digest::Digest + rsa::pkcs8::AssociatedOid + rsa::pkcs1v15::RsaSignatureAssociatedOid,
rsa::pkcs1v15::SigningKey<D>: rsa::signature::Keypair
+ rsa::signature::Signer<Sig>
+ x509_cert::spki::DynSignatureAlgorithmIdentifier,
Sig: x509_cert::spki::SignatureBitStringEncoding,
{
let signer = rsa::pkcs1v15::SigningKey::<D>::new(private_key);
let digest_alg = digest_algorithm.digest_algorithm();
let mut rd = SliceReader::new(econtent_der)
.map_err(|e| anyhow!("encapsulated content DER reader: {e}"))?;
let econtent =
Any::decode(&mut rd).map_err(|e| anyhow!("encapsulated content as CMS Any: {e}"))?;
rd.finish(())
.map_err(|e| anyhow!("trailing octets after encapsulated content DER: {e}"))?;
let content = EncapsulatedContentInfo {
econtent_type,
econtent: Some(econtent),
};
let signer_id = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
issuer: signer_cert.tbs_certificate.issuer.clone(),
serial_number: signer_cert.tbs_certificate.serial_number.clone(),
});
let signer_info =
SignerInfoBuilder::new(&signer, signer_id, digest_alg.clone(), &content, None)
.map_err(|e| anyhow!("build CMS SignerInfo: {e}"))?;
let mut builder = SignedDataBuilder::new(&content);
builder
.add_digest_algorithm(digest_alg)
.map_err(|e| anyhow!("add CMS digest algorithm: {e}"))?
.add_certificate(CertificateChoices::Certificate(signer_cert))
.map_err(|e| anyhow!("add CMS signer certificate: {e}"))?;
for cert in chain_certs {
builder
.add_certificate(CertificateChoices::Certificate(cert))
.map_err(|e| anyhow!("add CMS chain certificate: {e}"))?;
}
let pkcs7 = builder
.add_signer_info::<rsa::pkcs1v15::SigningKey<D>, Sig>(signer_info)
.map_err(|e| anyhow!("sign CMS signed attributes: {e}"))?
.build()
.map_err(|e| anyhow!("build CMS SignedData: {e}"))?
.to_der()
.map_err(|e| anyhow!("encode CMS PKCS#7 ContentInfo: {e}"))?;
let mut sd = parse_pkcs7_signed_data_der(&pkcs7)?;
// Microsoft Authenticode/catalog PKCS#7 profiles use SignedData.version v1 even though
// RFC 5652 would normally select v3 for non-id-data encapsulated content. The existing
// parser and Windows fixtures expect this value; it is outside the signed attribute digest.
sd.version = CmsVersion::V1;
encode_pkcs7_content_info_signed_data_der(&sd)
}
/// Encode **`SignedData`** as a PKCS#7 **`ContentInfo`** (**`contentType`** = **`id-signedData`**, RFC 5652).
///
/// This is a **building block** for portable Authenticode: mutating **`SignedData`** (e.g. new **`SignerInfo`**
/// with remote signature octets) then calling this function yields DER for **`pe_embed`**. Re-encoding an
/// unmodified structure is tested for **decode → encode → decode** stability on fixtures; **byte-for-byte**
/// equality with a given **`signtool.exe`** / **`CryptMsgOpenToEncode`** output is **not** guaranteed.
pub fn encode_pkcs7_content_info_signed_data_der(sd: &SignedData) -> Result<Vec<u8>> {
let sd_der = sd.to_der().map_err(|e| anyhow!("encode SignedData: {e}"))?;
let mut rd =
SliceReader::new(sd_der.as_slice()).map_err(|e| anyhow!("SignedData DER reader: {e}"))?;
let content = Any::decode(&mut rd).map_err(|e| anyhow!("SignedData as CMS Any: {e}"))?;
let ci = ContentInfo {
content_type: ID_SIGNED_DATA_OID,
content,
};
ci.to_der().map_err(|e| anyhow!("encode ContentInfo: {e}"))
}
/// Decode **`SignedData`** from PKCS#7 DER (**outer `ContentInfo`** with **`contentType`** **`id-signedData`**).
///
/// Accepts the same blob layout as embedded PE **`WIN_CERT_TYPE_PKCS_SIGNED_DATA`** rows (after optional
/// [`crate::pkcs7_wire::normalize_pkcs7_der_for_authenticode`] trimming).
pub fn parse_pkcs7_signed_data_der(pkcs7_der: &[u8]) -> Result<SignedData> {
let normalized = crate::pkcs7_wire::normalize_pkcs7_der_for_authenticode(pkcs7_der);
let bytes = normalized.as_ref();
let mut r = SliceReader::new(bytes).map_err(|_| anyhow!("empty PKCS#7"))?;
let ci = ContentInfo::decode(&mut r).map_err(|e| anyhow!("PKCS#7 ContentInfo decode: {e}"))?;
if ci.content_type != ID_SIGNED_DATA_OID {
return Err(anyhow!(
"PKCS#7 root content type is not SignedData (got {})",
ci.content_type
));
}
ci.content
.decode_as::<SignedData>()
.map_err(|e| anyhow!("SignedData: {e}"))
}
/// **id-ce-subjectKeyIdentifier** (RFC 5280).
const SUBJECT_KEY_IDENTIFIER_EXT_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.14");
/// **id-ce-basicConstraints** (RFC 5280).
const BASIC_CONSTRAINTS_EXT_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.19");
/// **id-ce-extKeyUsage** (RFC 5280).
const EXTENDED_KEY_USAGE_EXT_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.37");
/// **id-kp-codeSigning** (RFC 5280).
const CODE_SIGNING_EKU_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3");
/// Locate the embedded **`Certificate`** matching **`SignerInfo.sid`** (**`IssuerAndSerialNumber`** or **`SubjectKeyIdentifier`**).
pub fn signed_data_certificate_for_signer_identifier<'a>(
sd: &'a SignedData,
sid: &SignerIdentifier,
) -> Result<&'a Certificate> {
let set = sd
.certificates
.as_ref()
.ok_or_else(|| anyhow!("SignedData has no certificates"))?;
for choice in set.0.iter() {
let CertificateChoices::Certificate(cert) = choice else {
continue;
};
match sid {
SignerIdentifier::IssuerAndSerialNumber(ias) => {
if cert.tbs_certificate.issuer == ias.issuer
&& cert.tbs_certificate.serial_number == ias.serial_number
{
return Ok(cert);
}
}