pub enum DigestType {
    None,
    Sha1,
    Sha256,
    Sha256Truncated,
    Sha384,
    Sha512,
    Unknown(u8),
}
Expand description

Represents a digest type encountered in code signature data structures.

Variants§

§

None

§

Sha1

§

Sha256

§

Sha256Truncated

§

Sha384

§

Sha512

§

Unknown(u8)

Implementations§

Obtain the size of hashes for this hash type.

Examples found in repository?
src/dmg.rs (line 396)
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
    pub fn create_code_directory<F: Read + Write + Seek>(
        &self,
        settings: &SigningSettings,
        fh: &mut F,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        let reader = DmgReader::new(fh)?;

        let mut flags = settings
            .code_signature_flags(SettingsScope::Main)
            .unwrap_or_else(CodeSignatureFlags::empty);

        if settings.signing_key().is_some() {
            flags -= CodeSignatureFlags::ADHOC;
        } else {
            flags |= CodeSignatureFlags::ADHOC;
        }

        warn!("using code signature flags: {:?}", flags);

        let ident = Cow::Owned(
            settings
                .binary_identifier(SettingsScope::Main)
                .ok_or(AppleCodesignError::NoIdentifier)?
                .to_string(),
        );

        warn!("using identifier {}", ident);

        let code_hashes = vec![reader.digest_content_with(*settings.digest_type(), fh)?];

        let koly_digest = reader
            .koly()
            .digest_for_code_directory(*settings.digest_type())?;

        let mut cd = CodeDirectoryBlob {
            version: 0x20100,
            flags,
            code_limit: reader.koly().offset_after_plist() as u32,
            digest_size: settings.digest_type().hash_len()? as u8,
            digest_type: *settings.digest_type(),
            page_size: 1,
            ident,
            code_digests: code_hashes,
            ..Default::default()
        };

        cd.set_slot_digest(CodeSigningSlot::RepSpecific, koly_digest)?;

        Ok(cd)
    }
More examples
Hide additional examples
src/macho_signing.rs (line 565)
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
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

        if let Some(target) = &target {
            info!(
                "binary targets {} >= {} with SDK {}",
                target.platform, target.minimum_os_version, target.sdk_version,
            );
        }

        let mut flags = CodeSignatureFlags::empty();

        if let Some(additional) = settings.code_signature_flags(SettingsScope::Main) {
            info!(
                "adding code signature flags from signing settings: {:?}",
                additional
            );
            flags |= additional;
        }

        // The adhoc flag is set when there is no CMS signature.
        if settings.signing_key().is_none() {
            info!("creating ad-hoc signature");
            flags |= CodeSignatureFlags::ADHOC;
        } else if flags.contains(CodeSignatureFlags::ADHOC) {
            info!("removing ad-hoc code signature flag");
            flags -= CodeSignatureFlags::ADHOC;
        }

        // Remove linker signed flag because we're not a linker.
        if flags.contains(CodeSignatureFlags::LINKER_SIGNED) {
            info!("removing linker signed flag from code signature (we're not a linker)");
            flags -= CodeSignatureFlags::LINKER_SIGNED;
        }

        // Code limit fields hold the file offset at which code digests stop. This
        // is the file offset in the `__LINKEDIT` segment when the embedded signature
        // SuperBlob begins.
        let (code_limit, code_limit_64) = match macho.code_limit_binary_offset()? {
            x if x > u32::MAX as u64 => (0, Some(x)),
            x => (x as u32, None),
        };

        let platform = 0;
        let page_size = 4096u32;

        let (exec_seg_base, exec_seg_limit) = macho.executable_segment_boundary()?;
        let (exec_seg_base, exec_seg_limit) = (Some(exec_seg_base), Some(exec_seg_limit));

        // Executable segment flags are wonky.
        //
        // Foremost, these flags are only present if the Mach-O binary is an executable. So not
        // matter what the settings say, we don't set these flags unless the Mach-O file type
        // is proper.
        //
        // Executable segment flags are also derived from an associated entitlements plist.
        let exec_seg_flags = if macho.is_executable() {
            if let Some(entitlements) = settings.entitlements_plist(SettingsScope::Main) {
                let flags = plist_to_executable_segment_flags(entitlements);

                if !flags.is_empty() {
                    info!("entitlements imply executable segment flags: {:?}", flags);
                }

                Some(flags | ExecutableSegmentFlags::MAIN_BINARY)
            } else {
                Some(ExecutableSegmentFlags::MAIN_BINARY)
            }
        } else {
            None
        };

        // The runtime version is the SDK version from the targeting loader commands. Same
        // u32 with nibbles encoding the version.
        //
        // If the runtime code signature flag is set, we also need to set the runtime version
        // or else the activation of the hardened runtime is incomplete.

        // If the settings defines a runtime version override, use it.
        let runtime = match settings.runtime_version(SettingsScope::Main) {
            Some(version) => {
                info!(
                    "using hardened runtime version {} from signing settings",
                    version
                );
                Some(semver_to_macho_target_version(version))
            }
            None => None,
        };

        // If we still don't have a runtime but need one, derive from the target SDK.
        let runtime = if runtime.is_none() && flags.contains(CodeSignatureFlags::RUNTIME) {
            if let Some(target) = &target {
                info!(
                    "using hardened runtime version {} derived from SDK version",
                    target.sdk_version
                );
                Some(semver_to_macho_target_version(&target.sdk_version))
            } else {
                warn!("hardened runtime version required but unable to derive suitable version; signature will likely fail Apple checks");
                None
            }
        } else {
            runtime
        };

        let code_hashes = macho
            .code_digests(*settings.digest_type(), page_size as _)?
            .into_iter()
            .map(|v| Digest { data: v.into() })
            .collect::<Vec<_>>();

        let mut special_hashes = HashMap::new();

        // There is no corresponding blob for the info plist data since it is provided
        // externally to the embedded signature.
        if let Some(data) = settings.info_plist_data(SettingsScope::Main) {
            special_hashes.insert(
                CodeSigningSlot::Info,
                Digest {
                    data: settings.digest_type().digest_data(data)?.into(),
                },
            );
        }

        // There is no corresponding blob for resources data since it is provided
        // externally to the embedded signature.
        if let Some(data) = settings.code_resources_data(SettingsScope::Main) {
            special_hashes.insert(
                CodeSigningSlot::ResourceDir,
                Digest {
                    data: settings.digest_type().digest_data(data)?.into(),
                }
                .to_owned(),
            );
        }

        let ident = Cow::Owned(
            settings
                .binary_identifier(SettingsScope::Main)
                .ok_or(AppleCodesignError::NoIdentifier)?
                .to_string(),
        );

        let team_name = settings.team_id().map(|x| Cow::Owned(x.to_string()));

        let mut cd = CodeDirectoryBlob {
            flags,
            code_limit,
            digest_size: settings.digest_type().hash_len()? as u8,
            digest_type: *settings.digest_type(),
            platform,
            page_size,
            code_limit_64,
            exec_seg_base,
            exec_seg_limit,
            exec_seg_flags,
            runtime,
            ident,
            team_name,
            code_digests: code_hashes,
            ..Default::default()
        };

        for (slot, digest) in special_hashes {
            cd.set_slot_digest(slot, digest)?;
        }

        cd.adjust_version(target);
        cd.clear_newer_fields();

        Ok(cd)
    }

Obtain a hasher for this digest type.

Examples found in repository?
src/embedded_signature.rs (line 451)
450
451
452
453
454
455
456
457
458
459
460
461
    pub fn digest_data(&self, data: &[u8]) -> Result<Vec<u8>, AppleCodesignError> {
        let mut hasher = self.as_hasher()?;

        hasher.update(data);
        let mut hash = hasher.finish().as_ref().to_vec();

        if matches!(self, Self::Sha256Truncated) {
            hash.truncate(20);
        }

        Ok(hash)
    }
More examples
Hide additional examples
src/dmg.rs (line 208)
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
    fn digest_slice_with<R: Read + Seek>(
        &self,
        digest: DigestType,
        reader: &mut R,
        offset: u64,
        length: u64,
    ) -> Result<Digest<'static>, AppleCodesignError> {
        reader.seek(SeekFrom::Start(offset))?;

        let mut reader = reader.take(length);

        let mut d = digest.as_hasher()?;

        loop {
            let mut buffer = [0u8; 16384];
            let count = reader.read(&mut buffer)?;

            d.update(&buffer[0..count]);

            if count == 0 {
                break;
            }
        }

        Ok(Digest {
            data: d.finish().as_ref().to_vec().into(),
        })
    }

Digest data given the configured hasher.

Examples found in repository?
src/embedded_signature.rs (line 430)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
    pub fn hash_len(&self) -> Result<usize, AppleCodesignError> {
        Ok(self.digest_data(&[])?.len())
    }

    /// Obtain a hasher for this digest type.
    pub fn as_hasher(&self) -> Result<ring::digest::Context, AppleCodesignError> {
        match self {
            Self::None => Err(AppleCodesignError::DigestUnknownAlgorithm),
            Self::Sha1 => Ok(ring::digest::Context::new(
                &ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
            )),
            Self::Sha256 | Self::Sha256Truncated => {
                Ok(ring::digest::Context::new(&ring::digest::SHA256))
            }
            Self::Sha384 => Ok(ring::digest::Context::new(&ring::digest::SHA384)),
            Self::Sha512 => Ok(ring::digest::Context::new(&ring::digest::SHA512)),
            Self::Unknown(_) => Err(AppleCodesignError::DigestUnknownAlgorithm),
        }
    }

    /// Digest data given the configured hasher.
    pub fn digest_data(&self, data: &[u8]) -> Result<Vec<u8>, AppleCodesignError> {
        let mut hasher = self.as_hasher()?;

        hasher.update(data);
        let mut hash = hasher.finish().as_ref().to_vec();

        if matches!(self, Self::Sha256Truncated) {
            hash.truncate(20);
        }

        Ok(hash)
    }
}

pub struct Digest<'a> {
    pub data: Cow<'a, [u8]>,
}

impl<'a> Digest<'a> {
    /// Whether this is the null hash (all 0s).
    pub fn is_null(&self) -> bool {
        self.data.iter().all(|b| *b == 0)
    }

    pub fn to_vec(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    pub fn to_owned(&self) -> Digest<'static> {
        Digest {
            data: Cow::Owned(self.data.clone().into_owned()),
        }
    }

    pub fn as_hex(&self) -> String {
        hex::encode(&self.data)
    }
}

impl<'a> std::fmt::Debug for Digest<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&hex::encode(&self.data))
    }
}

impl<'a> From<Vec<u8>> for Digest<'a> {
    fn from(v: Vec<u8>) -> Self {
        Self { data: v.into() }
    }
}

/// Read the header from a Blob.
///
/// Blobs begin with a u32 magic and u32 length, inclusive.
fn read_blob_header(data: &[u8]) -> Result<(u32, usize, &[u8]), scroll::Error> {
    let magic = data.pread_with(0, scroll::BE)?;
    let length = data.pread_with::<u32>(4, scroll::BE)?;

    Ok((magic, length as usize, &data[8..]))
}

pub(crate) fn read_and_validate_blob_header<'a>(
    data: &'a [u8],
    expected_magic: u32,
    what: &'static str,
) -> Result<&'a [u8], AppleCodesignError> {
    let (magic, _, data) = read_blob_header(data)?;

    if magic != expected_magic {
        Err(AppleCodesignError::BadMagic(what))
    } else {
        Ok(data)
    }
}

/// Create the binary content for a SuperBlob.
pub fn create_superblob<'a>(
    magic: CodeSigningMagic,
    blobs: impl Iterator<Item = &'a (CodeSigningSlot, Vec<u8>)>,
) -> Result<Vec<u8>, AppleCodesignError> {
    // Makes offset calculation easier.
    let blobs = blobs.collect::<Vec<_>>();

    let mut cursor = std::io::Cursor::new(Vec::<u8>::new());

    let mut blob_data = Vec::new();
    // magic + total length + blob count.
    let mut total_length: u32 = 4 + 4 + 4;
    // 8 bytes for each blob index.
    total_length += 8 * blobs.len() as u32;

    let mut indices = Vec::with_capacity(blobs.len());

    for (slot, blob) in blobs {
        blob_data.push(blob);

        indices.push(BlobIndex {
            typ: u32::from(*slot),
            offset: total_length,
        });

        total_length += blob.len() as u32;
    }

    cursor.iowrite_with(u32::from(magic), scroll::BE)?;
    cursor.iowrite_with(total_length, scroll::BE)?;
    cursor.iowrite_with(indices.len() as u32, scroll::BE)?;
    for index in indices {
        cursor.iowrite_with(index.typ, scroll::BE)?;
        cursor.iowrite_with(index.offset, scroll::BE)?;
    }
    for data in blob_data {
        cursor.write_all(data)?;
    }

    Ok(cursor.into_inner())
}

/// Represents a single blob as defined by a SuperBlob index entry.
///
/// Instances have copies of their own index info, including the relative
/// order, slot type, and start offset within the `SuperBlob`.
///
/// The blob data is unparsed in this type. The blob payloads can be
/// turned into [ParsedBlob] via `.try_into()`.
#[derive(Clone)]
pub struct BlobEntry<'a> {
    /// Our blob index within the `SuperBlob`.
    pub index: usize,

    /// The slot type.
    pub slot: CodeSigningSlot,

    /// Our start offset within the `SuperBlob`.
    ///
    /// First byte is start of our magic.
    pub offset: usize,

    /// The magic value appearing at the beginning of the blob.
    pub magic: CodeSigningMagic,

    /// The length of the blob payload.
    pub length: usize,

    /// The raw data in this blob, including magic and length.
    pub data: &'a [u8],
}

impl<'a> std::fmt::Debug for BlobEntry<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("BlobEntry")
            .field("index", &self.index)
            .field("slot", &self.slot)
            .field("offset", &self.offset)
            .field("length", &self.length)
            .field("magic", &self.magic)
            // .field("data", &self.data)
            .finish()
    }
}

impl<'a> BlobEntry<'a> {
    /// Attempt to convert to a [ParsedBlob].
    pub fn into_parsed_blob(self) -> Result<ParsedBlob<'a>, AppleCodesignError> {
        self.try_into()
    }

    /// Obtain the payload of this blob.
    ///
    /// This is the data in the blob without the blob header.
    pub fn payload(&self) -> Result<&'a [u8], AppleCodesignError> {
        Ok(read_blob_header(self.data)?.2)
    }

    /// Compute the content digest of this blob using the specified hash type.
    pub fn digest_with(&self, hash: DigestType) -> Result<Vec<u8>, AppleCodesignError> {
        hash.digest_data(self.data)
    }
}

/// Provides common features for a parsed blob type.
pub trait Blob<'a>
where
    Self: Sized,
{
    /// The header magic that identifies this format.
    fn magic() -> u32;

    /// Attempt to construct an instance by parsing a bytes slice.
    ///
    /// The slice begins with the 8 byte blob header denoting the magic
    /// and length.
    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>;

    /// Serialize the payload of this blob to bytes.
    ///
    /// Does not include the magic or length header fields common to blobs.
    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>;

    /// Serialize this blob to bytes.
    ///
    /// This is [Blob::serialize_payload] with the blob magic and length
    /// prepended.
    fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
        let mut res = Vec::new();
        res.iowrite_with(Self::magic(), scroll::BE)?;

        let payload = self.serialize_payload()?;
        // Length includes our own header.
        res.iowrite_with(payload.len() as u32 + 8, scroll::BE)?;

        res.extend(payload);

        Ok(res)
    }

    /// Obtain the digest of the blob using the specified hasher.
    ///
    /// Default implementation calls [Blob::to_blob_bytes] and digests that, which
    /// should always be correct.
    fn digest_with(&self, hash_type: DigestType) -> Result<Vec<u8>, AppleCodesignError> {
        hash_type.digest_data(&self.to_blob_bytes()?)
    }
}

/// Represents a Requirement blob.
///
/// `csreq -b` will emit instances of this blob, header magic and all. So data generated
/// by `csreq -b` can be fed into [RequirementBlob.from_blob_bytes] to obtain an instance.
pub struct RequirementBlob<'a> {
    pub data: Cow<'a, [u8]>,
}

impl<'a> Blob<'a> for RequirementBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::Requirement)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        let data = read_and_validate_blob_header(data, Self::magic(), "requirement blob")?;

        Ok(Self { data: data.into() })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }
}

impl<'a> std::fmt::Debug for RequirementBlob<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("RequirementBlob({})", hex::encode(&self.data)))
    }
}

impl<'a> RequirementBlob<'a> {
    pub fn to_owned(&self) -> RequirementBlob<'static> {
        RequirementBlob {
            data: Cow::Owned(self.data.clone().into_owned()),
        }
    }

    /// Parse the binary data in this blob into Code Requirement expressions.
    pub fn parse_expressions(&self) -> Result<CodeRequirements, AppleCodesignError> {
        Ok(CodeRequirements::parse_binary(&self.data)?.0)
    }
}

/// Represents a Requirement set blob.
///
/// A Requirement set blob contains nested Requirement blobs.
#[derive(Debug, Default)]
pub struct RequirementSetBlob<'a> {
    pub requirements: HashMap<RequirementType, RequirementBlob<'a>>,
}

impl<'a> Blob<'a> for RequirementSetBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::RequirementSet)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        read_and_validate_blob_header(data, Self::magic(), "requirement set blob")?;

        // There are other blobs nested within. A u32 denotes how many there are.
        // Then there is an array of N (u32, u32) denoting the type and
        // offset of each.
        let offset = &mut 8;
        let count = data.gread_with::<u32>(offset, scroll::BE)?;

        let mut indices = Vec::with_capacity(count as usize);
        for _ in 0..count {
            indices.push((
                data.gread_with::<u32>(offset, scroll::BE)?,
                data.gread_with::<u32>(offset, scroll::BE)?,
            ));
        }

        let mut requirements = HashMap::with_capacity(indices.len());

        for (i, (flavor, offset)) in indices.iter().enumerate() {
            let typ = RequirementType::from(*flavor);

            let end_offset = if i == indices.len() - 1 {
                data.len()
            } else {
                indices[i + 1].1 as usize
            };

            let requirement_data = &data[*offset as usize..end_offset];

            requirements.insert(typ, RequirementBlob::from_blob_bytes(requirement_data)?);
        }

        Ok(Self { requirements })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        let mut res = Vec::new();

        // The index contains blob relative offsets. To know what the start offset will
        // be, we calculate the total index size.
        let data_start_offset = 8 + 4 + (8 * self.requirements.len() as u32);
        let mut written_requirements_data = 0;

        res.iowrite_with(self.requirements.len() as u32, scroll::BE)?;

        // Write an index of all nested requirement blobs.
        for (typ, requirement) in &self.requirements {
            res.iowrite_with(u32::from(*typ), scroll::BE)?;
            res.iowrite_with(data_start_offset + written_requirements_data, scroll::BE)?;
            written_requirements_data += requirement.to_blob_bytes()?.len() as u32;
        }

        // Now write every requirement's raw data.
        for requirement in self.requirements.values() {
            res.write_all(&requirement.to_blob_bytes()?)?;
        }

        Ok(res)
    }
}

impl<'a> RequirementSetBlob<'a> {
    pub fn to_owned(&self) -> RequirementSetBlob<'static> {
        RequirementSetBlob {
            requirements: self
                .requirements
                .iter()
                .map(|(flavor, blob)| (*flavor, blob.to_owned()))
                .collect::<HashMap<_, _>>(),
        }
    }

    /// Set the requirements for a given [RequirementType].
    pub fn set_requirements(&mut self, slot: RequirementType, blob: RequirementBlob<'a>) {
        self.requirements.insert(slot, blob);
    }
}

/// Represents an embedded signature.
#[derive(Debug)]
pub struct EmbeddedSignatureBlob<'a> {
    data: &'a [u8],
}

impl<'a> Blob<'a> for EmbeddedSignatureBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::EmbeddedSignature)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        Ok(Self {
            data: read_and_validate_blob_header(data, Self::magic(), "embedded signature blob")?,
        })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }
}

/// An old embedded signature.
#[derive(Debug)]
pub struct EmbeddedSignatureOldBlob<'a> {
    data: &'a [u8],
}

impl<'a> Blob<'a> for EmbeddedSignatureOldBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::EmbeddedSignatureOld)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        Ok(Self {
            data: read_and_validate_blob_header(
                data,
                Self::magic(),
                "old embedded signature blob",
            )?,
        })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }
}

/// Represents an Entitlements blob.
///
/// An entitlements blob contains an XML plist with a dict. Keys are
/// strings of the entitlements being requested and values appear to be
/// simple bools.
#[derive(Debug)]
pub struct EntitlementsBlob<'a> {
    plist: Cow<'a, str>,
}

impl<'a> Blob<'a> for EntitlementsBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::Entitlements)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        let data = read_and_validate_blob_header(data, Self::magic(), "entitlements blob")?;
        let s = std::str::from_utf8(data).map_err(AppleCodesignError::EntitlementsBadUtf8)?;

        Ok(Self { plist: s.into() })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.plist.as_bytes().to_vec())
    }
}

impl<'a> EntitlementsBlob<'a> {
    /// Construct an instance using any string as the payload.
    pub fn from_string(s: &(impl ToString + ?Sized)) -> Self {
        Self {
            plist: s.to_string().into(),
        }
    }

    /// Obtain the plist representation as a string.
    pub fn as_str(&self) -> &str {
        &self.plist
    }
}

impl<'a> std::fmt::Display for EntitlementsBlob<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.plist)
    }
}

#[derive(Debug)]
pub struct EntitlementsDerBlob<'a> {
    der: Cow<'a, [u8]>,
}

impl<'a> Blob<'a> for EntitlementsDerBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::EntitlementsDer)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        let der = read_and_validate_blob_header(data, Self::magic(), "DER entitlements blob")?;

        Ok(Self { der: der.into() })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.der.to_vec())
    }
}

impl<'a> EntitlementsDerBlob<'a> {
    /// Construct an instance from a [plist::Value].
    ///
    /// Not all plists can be encoded to this blob as not all plist value types can
    /// be encoded to DER. If a plist with an illegal value is passed in, this
    /// function will error, as DER encoding is performed immediately.
    ///
    /// The outermost plist value should be a dictionary.
    pub fn from_plist(v: &plist::Value) -> Result<Self, AppleCodesignError> {
        let der = crate::entitlements::der_encode_entitlements_plist(v)?;

        Ok(Self { der: der.into() })
    }
}

/// A detached signature.
#[derive(Debug)]
pub struct DetachedSignatureBlob<'a> {
    data: &'a [u8],
}

impl<'a> Blob<'a> for DetachedSignatureBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::DetachedSignature)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        Ok(Self {
            data: read_and_validate_blob_header(data, Self::magic(), "detached signature blob")?,
        })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }
}

/// Represents a generic blob wrapper.
pub struct BlobWrapperBlob<'a> {
    data: Cow<'a, [u8]>,
}

impl<'a> Blob<'a> for BlobWrapperBlob<'a> {
    fn magic() -> u32 {
        u32::from(CodeSigningMagic::BlobWrapper)
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        Ok(Self {
            data: read_and_validate_blob_header(data, Self::magic(), "blob wrapper blob")?.into(),
        })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }
}

impl<'a> std::fmt::Debug for BlobWrapperBlob<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}", hex::encode(&self.data)))
    }
}

impl<'a> BlobWrapperBlob<'a> {
    /// Construct an instance where the payload (post blob header) is given data.
    pub fn from_data_borrowed(data: &'a [u8]) -> BlobWrapperBlob<'a> {
        Self { data: data.into() }
    }
}

impl BlobWrapperBlob<'static> {
    /// Construct an instance with payload data.
    pub fn from_data_owned(data: Vec<u8>) -> BlobWrapperBlob<'static> {
        Self { data: data.into() }
    }
}

/// Represents an unknown blob type.
pub struct OtherBlob<'a> {
    pub magic: u32,
    pub data: &'a [u8],
}

impl<'a> Blob<'a> for OtherBlob<'a> {
    fn magic() -> u32 {
        // Use a placeholder magic value because there is no self bind here.
        u32::MAX
    }

    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        let (magic, _, data) = read_blob_header(data)?;

        Ok(Self { magic, data })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        Ok(self.data.to_vec())
    }

    // We need to implement this for custom magic serialization.
    fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
        let mut res = Vec::with_capacity(self.data.len() + 8);
        res.iowrite_with(self.magic, scroll::BE)?;
        res.iowrite_with(self.data.len() as u32 + 8, scroll::BE)?;
        res.write_all(self.data)?;

        Ok(res)
    }
}

impl<'a> std::fmt::Debug for OtherBlob<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}", hex::encode(self.data)))
    }
}

/// Represents a single, parsed Blob entry/slot.
///
/// Each variant corresponds to a [CodeSigningMagic] blob type.
#[derive(Debug)]
pub enum BlobData<'a> {
    Requirement(Box<RequirementBlob<'a>>),
    RequirementSet(Box<RequirementSetBlob<'a>>),
    CodeDirectory(Box<CodeDirectoryBlob<'a>>),
    EmbeddedSignature(Box<EmbeddedSignatureBlob<'a>>),
    EmbeddedSignatureOld(Box<EmbeddedSignatureOldBlob<'a>>),
    Entitlements(Box<EntitlementsBlob<'a>>),
    EntitlementsDer(Box<EntitlementsDerBlob<'a>>),
    DetachedSignature(Box<DetachedSignatureBlob<'a>>),
    BlobWrapper(Box<BlobWrapperBlob<'a>>),
    Other(Box<OtherBlob<'a>>),
}

impl<'a> Blob<'a> for BlobData<'a> {
    fn magic() -> u32 {
        u32::MAX
    }

    /// Parse blob data by reading its magic and feeding into magic-specific parser.
    fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
        let (magic, length, _) = read_blob_header(data)?;

        // This should be a no-op. But it could (correctly) cause a panic if the
        // advertised length is incorrect and we would incur a buffer overrun.
        let data = &data[0..length];

        let magic = CodeSigningMagic::from(magic);

        Ok(match magic {
            CodeSigningMagic::Requirement => {
                Self::Requirement(Box::new(RequirementBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::RequirementSet => {
                Self::RequirementSet(Box::new(RequirementSetBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::CodeDirectory => {
                Self::CodeDirectory(Box::new(CodeDirectoryBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::EmbeddedSignature => {
                Self::EmbeddedSignature(Box::new(EmbeddedSignatureBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::EmbeddedSignatureOld => Self::EmbeddedSignatureOld(Box::new(
                EmbeddedSignatureOldBlob::from_blob_bytes(data)?,
            )),
            CodeSigningMagic::Entitlements => {
                Self::Entitlements(Box::new(EntitlementsBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::EntitlementsDer => {
                Self::EntitlementsDer(Box::new(EntitlementsDerBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::DetachedSignature => {
                Self::DetachedSignature(Box::new(DetachedSignatureBlob::from_blob_bytes(data)?))
            }
            CodeSigningMagic::BlobWrapper => {
                Self::BlobWrapper(Box::new(BlobWrapperBlob::from_blob_bytes(data)?))
            }
            _ => Self::Other(Box::new(OtherBlob::from_blob_bytes(data)?)),
        })
    }

    fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
        match self {
            Self::Requirement(b) => b.serialize_payload(),
            Self::RequirementSet(b) => b.serialize_payload(),
            Self::CodeDirectory(b) => b.serialize_payload(),
            Self::EmbeddedSignature(b) => b.serialize_payload(),
            Self::EmbeddedSignatureOld(b) => b.serialize_payload(),
            Self::Entitlements(b) => b.serialize_payload(),
            Self::EntitlementsDer(b) => b.serialize_payload(),
            Self::DetachedSignature(b) => b.serialize_payload(),
            Self::BlobWrapper(b) => b.serialize_payload(),
            Self::Other(b) => b.serialize_payload(),
        }
    }

    fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
        match self {
            Self::Requirement(b) => b.to_blob_bytes(),
            Self::RequirementSet(b) => b.to_blob_bytes(),
            Self::CodeDirectory(b) => b.to_blob_bytes(),
            Self::EmbeddedSignature(b) => b.to_blob_bytes(),
            Self::EmbeddedSignatureOld(b) => b.to_blob_bytes(),
            Self::Entitlements(b) => b.to_blob_bytes(),
            Self::EntitlementsDer(b) => b.to_blob_bytes(),
            Self::DetachedSignature(b) => b.to_blob_bytes(),
            Self::BlobWrapper(b) => b.to_blob_bytes(),
            Self::Other(b) => b.to_blob_bytes(),
        }
    }
}

impl<'a> From<RequirementBlob<'a>> for BlobData<'a> {
    fn from(b: RequirementBlob<'a>) -> Self {
        Self::Requirement(Box::new(b))
    }
}

impl<'a> From<RequirementSetBlob<'a>> for BlobData<'a> {
    fn from(b: RequirementSetBlob<'a>) -> Self {
        Self::RequirementSet(Box::new(b))
    }
}

impl<'a> From<CodeDirectoryBlob<'a>> for BlobData<'a> {
    fn from(b: CodeDirectoryBlob<'a>) -> Self {
        Self::CodeDirectory(Box::new(b))
    }
}

impl<'a> From<EmbeddedSignatureBlob<'a>> for BlobData<'a> {
    fn from(b: EmbeddedSignatureBlob<'a>) -> Self {
        Self::EmbeddedSignature(Box::new(b))
    }
}

impl<'a> From<EmbeddedSignatureOldBlob<'a>> for BlobData<'a> {
    fn from(b: EmbeddedSignatureOldBlob<'a>) -> Self {
        Self::EmbeddedSignatureOld(Box::new(b))
    }
}

impl<'a> From<EntitlementsBlob<'a>> for BlobData<'a> {
    fn from(b: EntitlementsBlob<'a>) -> Self {
        Self::Entitlements(Box::new(b))
    }
}

impl<'a> From<EntitlementsDerBlob<'a>> for BlobData<'a> {
    fn from(b: EntitlementsDerBlob<'a>) -> Self {
        Self::EntitlementsDer(Box::new(b))
    }
}

impl<'a> From<DetachedSignatureBlob<'a>> for BlobData<'a> {
    fn from(b: DetachedSignatureBlob<'a>) -> Self {
        Self::DetachedSignature(Box::new(b))
    }
}

impl<'a> From<BlobWrapperBlob<'a>> for BlobData<'a> {
    fn from(b: BlobWrapperBlob<'a>) -> Self {
        Self::BlobWrapper(Box::new(b))
    }
}

impl<'a> From<OtherBlob<'a>> for BlobData<'a> {
    fn from(b: OtherBlob<'a>) -> Self {
        Self::Other(Box::new(b))
    }
}

/// Represents the parsed content of a blob entry.
#[derive(Debug)]
pub struct ParsedBlob<'a> {
    /// The blob record this blob came from.
    pub blob_entry: BlobEntry<'a>,

    /// The parsed blob data.
    pub blob: BlobData<'a>,
}

impl<'a> ParsedBlob<'a> {
    /// Compute the content digest of this blob using the specified hash type.
    pub fn digest_with(&self, hash: DigestType) -> Result<Vec<u8>, AppleCodesignError> {
        hash.digest_data(self.blob_entry.data)
    }
More examples
Hide additional examples
src/macho.rs (line 251)
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
    pub fn code_digests_size(
        &self,
        digest: DigestType,
        page_size: usize,
    ) -> Result<usize, AppleCodesignError> {
        let empty = digest.digest_data(b"")?;

        Ok(self.digested_code_data()?.chunks(page_size).count() * empty.len())
    }

    /// Compute digests over code in this binary.
    pub fn code_digests(
        &self,
        digest: DigestType,
        page_size: usize,
    ) -> Result<Vec<Vec<u8>>, AppleCodesignError> {
        let data = self.digested_code_data()?;

        // Premature parallelism can be slower due to overhead of having to spin up threads.
        // So only do parallel digests if we have enough data to warrant it.
        if data.len() > 64 * 1024 * 1024 {
            data.par_chunks(page_size)
                .map(|c| digest.digest_data(c))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        } else {
            self.digested_code_data()?
                .chunks(page_size)
                .map(|chunk| digest.digest_data(chunk))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        }
    }
src/dmg.rs (line 144)
133
134
135
136
137
138
139
140
141
142
143
144
145
    pub fn digest_for_code_directory(
        &self,
        digest: DigestType,
    ) -> Result<Vec<u8>, AppleCodesignError> {
        let mut koly = self.clone();
        koly.code_signature_size = 0;
        koly.code_signature_offset = self.offset_after_plist();

        let mut buf = [0u8; KOLY_SIZE as usize];
        buf.pwrite_with(koly, 0, scroll::BE)?;

        digest.digest_data(&buf)
    }
src/code_resources.rs (line 764)
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
    pub fn seal_regular_file(
        &mut self,
        files_flavor: FilesFlavor,
        path: impl ToString,
        content: impl AsRef<[u8]>,
        optional: bool,
    ) -> Result<(), AppleCodesignError> {
        match files_flavor {
            FilesFlavor::Rules => {
                let digest = DigestType::Sha1.digest_data(content.as_ref())?;
                self.files.insert(
                    path.to_string(),
                    if optional {
                        FilesValue::Optional(digest)
                    } else {
                        FilesValue::Required(digest)
                    },
                );

                Ok(())
            }
            FilesFlavor::Rules2 => {
                let hash2 = Some(DigestType::Sha256.digest_data(content.as_ref())?);

                self.files2.insert(
                    path.to_string(),
                    Files2Value {
                        cdhash: None,
                        hash: None,
                        hash2,
                        optional: if optional { Some(true) } else { None },
                        requirement: None,
                        symlink: None,
                    },
                );

                Ok(())
            }
            FilesFlavor::Rules2WithSha1 => {
                let hash = Some(DigestType::Sha1.digest_data(content.as_ref())?);
                let hash2 = Some(DigestType::Sha256.digest_data(content.as_ref())?);

                self.files2.insert(
                    path.to_string(),
                    Files2Value {
                        cdhash: None,
                        hash,
                        hash2,
                        optional: if optional { Some(true) } else { None },
                        requirement: None,
                        symlink: None,
                    },
                );

                Ok(())
            }
        }
    }

    /// Seal a symlink file.
    ///
    /// `path` is the path of the symlink and `target` is the path it points to.
    pub fn seal_symlink(&mut self, path: impl ToString, target: impl ToString) {
        self.files2.insert(
            path.to_string(),
            Files2Value {
                cdhash: None,
                hash: None,
                hash2: None,
                optional: None,
                requirement: None,
                symlink: Some(target.to_string()),
            },
        );
    }

    /// Record metadata of a previously signed Mach-O binary.
    ///
    /// If sealing a fat/universal binary, pass in metadata for the first Mach-O within in.
    pub fn seal_macho(
        &mut self,
        path: impl ToString,
        info: &SignedMachOInfo,
        optional: bool,
    ) -> Result<(), AppleCodesignError> {
        self.files2.insert(
            path.to_string(),
            Files2Value {
                cdhash: Some(DigestType::Sha256Truncated.digest_data(&info.code_directory_blob)?),
                hash: None,
                hash2: None,
                optional: if optional { Some(true) } else { None },
                requirement: info.designated_code_requirement.clone(),
                symlink: None,
            },
        );

        Ok(())
    }
src/bundle_signing.rs (line 205)
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
    pub fn parse_data(data: &[u8]) -> Result<Self, AppleCodesignError> {
        // Initial Mach-O's signature data is used.
        let mach = MachFile::parse(data)?;
        let macho = mach.nth_macho(0)?;

        let signature = macho
            .code_signature()?
            .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

        let code_directory_blob = signature.preferred_code_directory()?.to_blob_bytes()?;

        let designated_code_requirement = if let Some(requirements) =
            signature.code_requirements()?
        {
            if let Some(designated) = requirements.requirements.get(&RequirementType::Designated) {
                let req = designated.parse_expressions()?;

                Some(format!("{}", req[0]))
            } else {
                // In case no explicit requirements has been set, we use current file cdhashes.
                let mut requirement_expr = None;

                for macho in mach.iter_macho() {
                    let cd = macho
                        .code_signature()?
                        .ok_or(AppleCodesignError::BinaryNoCodeSignature)?
                        .preferred_code_directory()?;

                    let digest_type = if cd.digest_type == DigestType::Sha256 {
                        DigestType::Sha256Truncated
                    } else {
                        cd.digest_type
                    };

                    let digest = digest_type.digest_data(&cd.to_blob_bytes()?)?;
                    let expression = Box::new(CodeRequirementExpression::CodeDirectoryHash(
                        Cow::from(digest),
                    ));

                    if let Some(left_part) = requirement_expr {
                        requirement_expr = Some(Box::new(CodeRequirementExpression::Or(
                            left_part, expression,
                        )))
                    } else {
                        requirement_expr = Some(expression);
                    }
                }

                Some(format!(
                    "{}",
                    requirement_expr.expect("a Mach-O should have been present")
                ))
            }
        } else {
            None
        };

        Ok(SignedMachOInfo {
            code_directory_blob,
            designated_code_requirement,
        })
    }
src/reader.rs (line 644)
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
    pub fn from_xar<R: Read + Seek + Sized + Debug>(
        xar: &mut XarReader<R>,
    ) -> Result<Self, AppleCodesignError> {
        let (digest_type, digest) = xar.checksum()?;
        let _xml = xar.table_of_contents_decoded_data()?;

        let (rsa_signature, rsa_signature_verifies) = if let Some(sig) = xar.rsa_signature()? {
            (
                Some(hex::encode(sig.0)),
                Some(xar.verify_rsa_checksum_signature().unwrap_or(false)),
            )
        } else {
            (None, None)
        };
        let (cms_signature, cms_signature_verifies) =
            if let Some(signed_data) = xar.cms_signature()? {
                (
                    Some(CmsSignature::try_from(signed_data)?),
                    Some(xar.verify_cms_signature().unwrap_or(false)),
                )
            } else {
                (None, None)
            };

        let toc_checksum_actual_sha1 = xar.digest_table_of_contents_with(XarChecksumType::Sha1)?;
        let toc_checksum_actual_sha256 =
            xar.digest_table_of_contents_with(XarChecksumType::Sha256)?;

        let checksum_verifies = xar.verify_table_of_contents_checksum().unwrap_or(false);

        let header = xar.header();
        let toc = xar.table_of_contents();
        let checksum_offset = toc.checksum.offset;
        let checksum_size = toc.checksum.size;

        // This can be useful for debugging.
        //let xml = String::from_utf8_lossy(&pretty_print_xml(&xml)?)
        //    .lines()
        //    .map(|x| x.to_string())
        //    .collect::<Vec<_>>();
        let xml = vec![];

        Ok(Self {
            toc_length_compressed: header.toc_length_compressed,
            toc_length_uncompressed: header.toc_length_uncompressed,
            checksum_offset,
            checksum_size,
            checksum_type: apple_xar::format::XarChecksum::from(header.checksum_algorithm_id)
                .to_string(),
            toc_start_offset: header.size,
            heap_start_offset: xar.heap_start_offset(),
            creation_time: toc.creation_time.clone(),
            toc_checksum_reported: format!("{}:{}", digest_type, hex::encode(&digest)),
            toc_checksum_reported_sha1_digest: hex::encode(DigestType::Sha1.digest_data(&digest)?),
            toc_checksum_reported_sha256_digest: hex::encode(
                DigestType::Sha256.digest_data(&digest)?,
            ),
            toc_checksum_actual_sha1: hex::encode(toc_checksum_actual_sha1),
            toc_checksum_actual_sha256: hex::encode(toc_checksum_actual_sha256),
            checksum_verifies,
            signature: if let Some(sig) = &toc.signature {
                Some(sig.try_into()?)
            } else {
                None
            },
            x_signature: if let Some(sig) = &toc.x_signature {
                Some(sig.try_into()?)
            } else {
                None
            },
            xml,
            rsa_signature,
            rsa_signature_verifies,
            cms_signature,
            cms_signature_verifies,
        })
    }

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
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. 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.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. 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.
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
Converts self into T using Into<T>. Read more
Compare self to key and return true if they are equal.
Causes self to use its Binary implementation when Debug-formatted.
Causes self to use its Display implementation when Debug-formatted.
Causes self to use its LowerExp implementation when Debug-formatted.
Causes self to use its LowerHex implementation when Debug-formatted.
Causes self to use its Octal implementation when Debug-formatted.
Causes self to use its Pointer implementation when Debug-formatted.
Causes self to use its UpperExp implementation when Debug-formatted.
Causes self to use its UpperHex implementation when Debug-formatted.
Formats each item in a sequence. Read more

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.

Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function.
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function.
The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds.
Calls .tap_borrow() only in debug builds, and is erased in release builds.
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Calls .tap_ref() only in debug builds, and is erased in release builds.
Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Calls .tap_deref() only in debug builds, and is erased in release builds.
Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
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
Converts the given value to a String. Read more
Attempts to convert self into T using TryInto<T>. 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