pub enum CodeRequirementExpression<'a> {
Show 24 variants False, True, Identifier(Cow<'a, str>), AnchorApple, AnchorCertificateHash(i32Cow<'a, [u8]>), InfoKeyValueLegacy(Cow<'a, str>, Cow<'a, str>), And(Box<CodeRequirementExpression<'a>>, Box<CodeRequirementExpression<'a>>), Or(Box<CodeRequirementExpression<'a>>, Box<CodeRequirementExpression<'a>>), CodeDirectoryHash(Cow<'a, [u8]>), Not(Box<CodeRequirementExpression<'a>>), InfoPlistKeyField(Cow<'a, str>, CodeRequirementMatchExpression<'a>), CertificateField(i32Cow<'a, str>, CodeRequirementMatchExpression<'a>), CertificateTrusted(i32), AnchorTrusted, CertificateGeneric(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>), AnchorAppleGeneric, EntitlementsKey(Cow<'a, str>, CodeRequirementMatchExpression<'a>), CertificatePolicy(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>), NamedAnchor(Cow<'a, str>), NamedCode(Cow<'a, str>), Platform(u32), Notarized, CertificateFieldDate(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>), LegacyDeveloperId,
}
Expand description

Defines a code requirement expression.

Variants§

§

False

False

false

No payload.

§

True

True

true

No payload.

§

Identifier(Cow<'a, str>)

Signing identifier.

identifier <string>

4 bytes length followed by C string.

§

AnchorApple

The certificate chain must lead to an Apple root.

anchor apple

No payload.

§

AnchorCertificateHash(i32Cow<'a, [u8]>)

The certificate chain must anchor to a certificate with specified SHA-1 hash.

anchor <slot> H"<hash>"

4 bytes slot number, 4 bytes hash length, hash value.

§

InfoKeyValueLegacy(Cow<'a, str>, Cow<'a, str>)

Info.plist key value (legacy).

info[<key>] = <value>

2 pairs of (length + value).

§

And(Box<CodeRequirementExpression<'a>>, Box<CodeRequirementExpression<'a>>)

Logical and.

expr0 and expr1

Payload consists of 2 sub-expressions with no additional encoding.

§

Or(Box<CodeRequirementExpression<'a>>, Box<CodeRequirementExpression<'a>>)

Logical or.

expr0 or expr1

Payload consists of 2 sub-expressions with no additional encoding.

§

CodeDirectoryHash(Cow<'a, [u8]>)

Code directory hash.

`cdhash H“

4 bytes length followed by raw digest value.

§

Not(Box<CodeRequirementExpression<'a>>)

Logical not.

!expr

Payload is 1 sub-expression.

§

InfoPlistKeyField(Cow<'a, str>, CodeRequirementMatchExpression<'a>)

Info plist key field.

info [key] match expression

e.g. info [CFBundleName] exists

4 bytes key length, key string, then match expression.

§

CertificateField(i32Cow<'a, str>, CodeRequirementMatchExpression<'a>)

Certificate field matches.

certificate <slot> [<field>] match expression

Slot i32, 4 bytes field length, field string, then match expression.

§

CertificateTrusted(i32)

Certificate in position is trusted for code signing.

certificate <position> trusted

4 bytes certificate position.

§

AnchorTrusted

The certificate chain must lead to a trusted root.

anchor trusted

No payload.

§

CertificateGeneric(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>)

Certificate field matches by OID.

certificate <slot> [field.<oid>] match expression

Slot i32, 4 bytes OID length, OID raw bytes, match expression.

§

AnchorAppleGeneric

For code signed by Apple, including from code signing certificates issued by Apple.

anchor apple generic

No payload.

§

EntitlementsKey(Cow<'a, str>, CodeRequirementMatchExpression<'a>)

Value associated with specified key in signature’s embedded entitlements dictionary.

entitlement [<key>] match expression

4 bytes key length, key bytes, match expression.

§

CertificatePolicy(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>)

OID associated with certificate in a given slot.

It is unknown what the OID means.

certificate <slot> [policy.<oid>] match expression

§

NamedAnchor(Cow<'a, str>)

A named Apple anchor.

anchor apple <name>

4 bytes name length, name bytes.

§

NamedCode(Cow<'a, str>)

Named code.

(<name>)

4 bytes name length, name bytes.

§

Platform(u32)

Platform value.

platform = <value>

Payload is a u32.

§

Notarized

Binary is notarized.

notarized

No Payload.

§

CertificateFieldDate(i32Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>)

Certificate field date.

Unknown what the OID corresponds to.

certificate <slot> [timestamp.<oid>] match expression

§

LegacyDeveloperId

Legacy developer ID used.

Implementations§

Construct an expression element by reading from a slice.

Returns the newly constructed element and remaining data in the slice.

Examples found in repository?
src/macho_signing.rs (line 627)
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
    pub fn create_special_blobs(
        &self,
        settings: &SigningSettings,
        is_executable: bool,
    ) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
        let mut res = Vec::new();

        let mut requirements = CodeRequirements::default();

        match settings.designated_requirement(SettingsScope::Main) {
            DesignatedRequirementMode::Auto => {
                // If we are using an Apple-issued cert, this should automatically
                // derive appropriate designated requirements.
                if let Some((_, cert)) = settings.signing_key() {
                    info!("attempting to derive code requirements from signing certificate");
                    let identifier = Some(
                        settings
                            .binary_identifier(SettingsScope::Main)
                            .ok_or(AppleCodesignError::NoIdentifier)?
                            .to_string(),
                    );

                    if let Some(expr) = derive_designated_requirements(cert, identifier)? {
                        requirements.push(expr);
                    }
                }
            }
            DesignatedRequirementMode::Explicit(exprs) => {
                info!("using provided code requirements");
                for expr in exprs {
                    requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
                }
            }
        }

        // Always emit a RequirementSet blob, even if empty. Without it, validation fails
        // with `the sealed resource directory is invalid`.
        let mut blob = RequirementSetBlob::default();

        if !requirements.is_empty() {
            info!("code requirements: {}", requirements);
            requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
        }

        res.push((CodeSigningSlot::RequirementSet, blob.into()));

        if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
            info!("adding entitlements XML");
            let blob = EntitlementsBlob::from_string(&entitlements);

            res.push((CodeSigningSlot::Entitlements, blob.into()));
        }

        // The DER encoded entitlements weren't always present in the signature. The feature
        // appears to have been introduced in macOS 10.14 and is the default behavior as of
        // macOS 12 "when signing for all platforms." `codesign` appears to add the DER
        // representation whenever entitlements are present, but only if the current binary is
        // an executable (.filetype == MH_EXECUTE).
        if is_executable {
            if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
                info!("adding entitlements DER");
                let blob = EntitlementsDerBlob::from_plist(value)?;

                res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
            }
        }

        Ok(res)
    }
More examples
Hide additional examples
src/code_requirement.rs (line 344)
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
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
    pub fn parse_payload<'a>(
        &self,
        data: &'a [u8],
    ) -> Result<(CodeRequirementExpression<'a>, &'a [u8]), AppleCodesignError> {
        match self {
            Self::False => Ok((CodeRequirementExpression::False, data)),
            Self::True => Ok((CodeRequirementExpression::True, data)),
            Self::Identifier => {
                let (value, data) = read_data(data)?;
                let s = std::str::from_utf8(value).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("identifier value not a UTF-8 string")
                })?;

                Ok((CodeRequirementExpression::Identifier(Cow::from(s)), data))
            }
            Self::AnchorApple => Ok((CodeRequirementExpression::AnchorApple, data)),
            Self::AnchorCertificateHash => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;
                let digest_length = data.pread_with::<u32>(4, scroll::BE)?;
                let digest = &data[8..8 + digest_length as usize];

                Ok((
                    CodeRequirementExpression::AnchorCertificateHash(slot, digest.into()),
                    &data[8 + digest_length as usize..],
                ))
            }
            Self::InfoKeyValueLegacy => {
                let (key, data) = read_data(data)?;

                let key = std::str::from_utf8(key).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("info key not a UTF-8 string")
                })?;

                let (value, data) = read_data(data)?;

                let value = std::str::from_utf8(value).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("info value not a UTF-8 string")
                })?;

                Ok((
                    CodeRequirementExpression::InfoKeyValueLegacy(key.into(), value.into()),
                    data,
                ))
            }
            Self::And => {
                let (a, data) = CodeRequirementExpression::from_bytes(data)?;
                let (b, data) = CodeRequirementExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::And(Box::new(a), Box::new(b)),
                    data,
                ))
            }
            Self::Or => {
                let (a, data) = CodeRequirementExpression::from_bytes(data)?;
                let (b, data) = CodeRequirementExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::Or(Box::new(a), Box::new(b)),
                    data,
                ))
            }
            Self::CodeDirectoryHash => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementExpression::CodeDirectoryHash(value.into()),
                    data,
                ))
            }
            Self::Not => {
                let (expr, data) = CodeRequirementExpression::from_bytes(data)?;

                Ok((CodeRequirementExpression::Not(Box::new(expr)), data))
            }
            Self::InfoPlistExpression => {
                let (key, data) = read_data(data)?;

                let key = std::str::from_utf8(key).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("key is not valid UTF-8")
                })?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::InfoPlistKeyField(key.into(), expr),
                    data,
                ))
            }
            Self::CertificateField => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;

                let (field, data) = read_data(&data[4..])?;

                let field = std::str::from_utf8(field).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("certificate field is not valid UTF-8")
                })?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::CertificateField(slot, field.into(), expr),
                    data,
                ))
            }
            Self::CertificateTrusted => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;

                Ok((
                    CodeRequirementExpression::CertificateTrusted(slot),
                    &data[4..],
                ))
            }
            Self::AnchorTrusted => Ok((CodeRequirementExpression::AnchorTrusted, data)),
            Self::CertificateGeneric => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;

                let (oid, data) = read_data(&data[4..])?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::CertificateGeneric(slot, Oid(oid), expr),
                    data,
                ))
            }
            Self::AnchorAppleGeneric => Ok((CodeRequirementExpression::AnchorAppleGeneric, data)),
            Self::EntitlementsField => {
                let (key, data) = read_data(data)?;

                let key = std::str::from_utf8(key).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("entitlement key is not UTF-8")
                })?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::EntitlementsKey(key.into(), expr),
                    data,
                ))
            }
            Self::CertificatePolicy => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;

                let (oid, data) = read_data(&data[4..])?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::CertificatePolicy(slot, Oid(oid), expr),
                    data,
                ))
            }
            Self::NamedAnchor => {
                let (name, data) = read_data(data)?;

                let name = std::str::from_utf8(name).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("named anchor isn't UTF-8")
                })?;

                Ok((CodeRequirementExpression::NamedAnchor(name.into()), data))
            }
            Self::NamedCode => {
                let (name, data) = read_data(data)?;

                let name = std::str::from_utf8(name).map_err(|_| {
                    AppleCodesignError::RequirementMalformed("named code isn't UTF-8")
                })?;

                Ok((CodeRequirementExpression::NamedCode(name.into()), data))
            }
            Self::Platform => {
                let value = data.pread_with::<u32>(0, scroll::BE)?;

                Ok((CodeRequirementExpression::Platform(value), &data[4..]))
            }
            Self::Notarized => Ok((CodeRequirementExpression::Notarized, data)),
            Self::CertificateFieldDate => {
                let slot = data.pread_with::<i32>(0, scroll::BE)?;

                let (oid, data) = read_data(&data[4..])?;

                let (expr, data) = CodeRequirementMatchExpression::from_bytes(data)?;

                Ok((
                    CodeRequirementExpression::CertificateFieldDate(slot, Oid(oid), expr),
                    data,
                ))
            }
            Self::LegacyDeveloperId => Ok((CodeRequirementExpression::LegacyDeveloperId, data)),
        }
    }
}

/// Defines a code requirement expression.
#[derive(Clone, Debug, PartialEq)]
pub enum CodeRequirementExpression<'a> {
    /// False
    ///
    /// `false`
    ///
    /// No payload.
    False,

    /// True
    ///
    /// `true`
    ///
    /// No payload.
    True,

    /// Signing identifier.
    ///
    /// `identifier <string>`
    ///
    /// 4 bytes length followed by C string.
    Identifier(Cow<'a, str>),

    /// The certificate chain must lead to an Apple root.
    ///
    /// `anchor apple`
    ///
    /// No payload.
    AnchorApple,

    /// The certificate chain must anchor to a certificate with specified SHA-1 hash.
    ///
    /// `anchor <slot> H"<hash>"`
    ///
    /// 4 bytes slot number, 4 bytes hash length, hash value.
    AnchorCertificateHash(i32, Cow<'a, [u8]>),

    /// Info.plist key value (legacy).
    ///
    /// `info[<key>] = <value>`
    ///
    /// 2 pairs of (length + value).
    InfoKeyValueLegacy(Cow<'a, str>, Cow<'a, str>),

    /// Logical and.
    ///
    /// `expr0 and expr1`
    ///
    /// Payload consists of 2 sub-expressions with no additional encoding.
    And(
        Box<CodeRequirementExpression<'a>>,
        Box<CodeRequirementExpression<'a>>,
    ),

    /// Logical or.
    ///
    /// `expr0 or expr1`
    ///
    /// Payload consists of 2 sub-expressions with no additional encoding.
    Or(
        Box<CodeRequirementExpression<'a>>,
        Box<CodeRequirementExpression<'a>>,
    ),

    /// Code directory hash.
    ///
    /// `cdhash H"<hash>"
    ///
    /// 4 bytes length followed by raw digest value.
    CodeDirectoryHash(Cow<'a, [u8]>),

    /// Logical not.
    ///
    /// `!expr`
    ///
    /// Payload is 1 sub-expression.
    Not(Box<CodeRequirementExpression<'a>>),

    /// Info plist key field.
    ///
    /// `info [key] match expression`
    ///
    /// e.g. `info [CFBundleName] exists`
    ///
    /// 4 bytes key length, key string, then match expression.
    InfoPlistKeyField(Cow<'a, str>, CodeRequirementMatchExpression<'a>),

    /// Certificate field matches.
    ///
    /// `certificate <slot> [<field>] match expression`
    ///
    /// Slot i32, 4 bytes field length, field string, then match expression.
    CertificateField(i32, Cow<'a, str>, CodeRequirementMatchExpression<'a>),

    /// Certificate in position is trusted for code signing.
    ///
    /// `certificate <position> trusted`
    ///
    /// 4 bytes certificate position.
    CertificateTrusted(i32),

    /// The certificate chain must lead to a trusted root.
    ///
    /// `anchor trusted`
    ///
    /// No payload.
    AnchorTrusted,

    /// Certificate field matches by OID.
    ///
    /// `certificate <slot> [field.<oid>] match expression`
    ///
    /// Slot i32, 4 bytes OID length, OID raw bytes, match expression.
    CertificateGeneric(i32, Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>),

    /// For code signed by Apple, including from code signing certificates issued by Apple.
    ///
    /// `anchor apple generic`
    ///
    /// No payload.
    AnchorAppleGeneric,

    /// Value associated with specified key in signature's embedded entitlements dictionary.
    ///
    /// `entitlement [<key>] match expression`
    ///
    /// 4 bytes key length, key bytes, match expression.
    EntitlementsKey(Cow<'a, str>, CodeRequirementMatchExpression<'a>),

    /// OID associated with certificate in a given slot.
    ///
    /// It is unknown what the OID means.
    ///
    /// `certificate <slot> [policy.<oid>] match expression`
    CertificatePolicy(i32, Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>),

    /// A named Apple anchor.
    ///
    /// `anchor apple <name>`
    ///
    /// 4 bytes name length, name bytes.
    NamedAnchor(Cow<'a, str>),

    /// Named code.
    ///
    /// `(<name>)`
    ///
    /// 4 bytes name length, name bytes.
    NamedCode(Cow<'a, str>),

    /// Platform value.
    ///
    /// `platform = <value>`
    ///
    /// Payload is a u32.
    Platform(u32),

    /// Binary is notarized.
    ///
    /// `notarized`
    ///
    /// No Payload.
    Notarized,

    /// Certificate field date.
    ///
    /// Unknown what the OID corresponds to.
    ///
    /// `certificate <slot> [timestamp.<oid>] match expression`
    CertificateFieldDate(i32, Oid<&'a [u8]>, CodeRequirementMatchExpression<'a>),

    /// Legacy developer ID used.
    LegacyDeveloperId,
}

impl<'a> Display for CodeRequirementExpression<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::False => f.write_str("never"),
            Self::True => f.write_str("always"),
            Self::Identifier(value) => f.write_fmt(format_args!("identifier \"{value}\"")),
            Self::AnchorApple => f.write_str("anchor apple"),
            Self::AnchorCertificateHash(slot, digest) => {
                f.write_fmt(format_args!("anchor {} H\"{}\"", slot, hex::encode(digest)))
            }
            Self::InfoKeyValueLegacy(key, value) => {
                f.write_fmt(format_args!("info[{key}] = \"{value}\""))
            }
            Self::And(a, b) => f.write_fmt(format_args!("({a}) and ({b})")),
            Self::Or(a, b) => f.write_fmt(format_args!("({a}) or ({b})")),
            Self::CodeDirectoryHash(digest) => {
                f.write_fmt(format_args!("cdhash H\"{}\"", hex::encode(digest)))
            }
            Self::Not(expr) => f.write_fmt(format_args!("!({expr})")),
            Self::InfoPlistKeyField(key, expr) => {
                f.write_fmt(format_args!("info [{key}] {expr}"))
            }
            Self::CertificateField(slot, field, expr) => f.write_fmt(format_args!(
                "certificate {}[{}] {}",
                format_certificate_slot(*slot),
                field,
                expr
            )),
            Self::CertificateTrusted(slot) => {
                f.write_fmt(format_args!("certificate {slot} trusted"))
            }
            Self::AnchorTrusted => f.write_str("anchor trusted"),
            Self::CertificateGeneric(slot, oid, expr) => f.write_fmt(format_args!(
                "certificate {}[field.{}] {}",
                format_certificate_slot(*slot),
                oid,
                expr
            )),
            Self::AnchorAppleGeneric => f.write_str("anchor apple generic"),
            Self::EntitlementsKey(key, expr) => {
                f.write_fmt(format_args!("entitlement [{key}] {expr}"))
            }
            Self::CertificatePolicy(slot, oid, expr) => f.write_fmt(format_args!(
                "certificate {}[policy.{}] {}",
                format_certificate_slot(*slot),
                oid,
                expr
            )),
            Self::NamedAnchor(name) => f.write_fmt(format_args!("anchor apple {name}")),
            Self::NamedCode(name) => f.write_fmt(format_args!("({name})")),
            Self::Platform(platform) => f.write_fmt(format_args!("platform = {platform}")),
            Self::Notarized => f.write_str("notarized"),
            Self::CertificateFieldDate(slot, oid, expr) => f.write_fmt(format_args!(
                "certificate {}[timestamp.{}] {}",
                format_certificate_slot(*slot),
                oid,
                expr
            )),
            Self::LegacyDeveloperId => f.write_str("legacy"),
        }
    }
}

impl<'a> From<&CodeRequirementExpression<'a>> for RequirementOpCode {
    fn from(e: &CodeRequirementExpression) -> Self {
        match e {
            CodeRequirementExpression::False => RequirementOpCode::False,
            CodeRequirementExpression::True => RequirementOpCode::True,
            CodeRequirementExpression::Identifier(_) => RequirementOpCode::Identifier,
            CodeRequirementExpression::AnchorApple => RequirementOpCode::AnchorApple,
            CodeRequirementExpression::AnchorCertificateHash(_, _) => {
                RequirementOpCode::AnchorCertificateHash
            }
            CodeRequirementExpression::InfoKeyValueLegacy(_, _) => {
                RequirementOpCode::InfoKeyValueLegacy
            }
            CodeRequirementExpression::And(_, _) => RequirementOpCode::And,
            CodeRequirementExpression::Or(_, _) => RequirementOpCode::Or,
            CodeRequirementExpression::CodeDirectoryHash(_) => RequirementOpCode::CodeDirectoryHash,
            CodeRequirementExpression::Not(_) => RequirementOpCode::Not,
            CodeRequirementExpression::InfoPlistKeyField(_, _) => {
                RequirementOpCode::InfoPlistExpression
            }
            CodeRequirementExpression::CertificateField(_, _, _) => {
                RequirementOpCode::CertificateField
            }
            CodeRequirementExpression::CertificateTrusted(_) => {
                RequirementOpCode::CertificateTrusted
            }
            CodeRequirementExpression::AnchorTrusted => RequirementOpCode::AnchorTrusted,
            CodeRequirementExpression::CertificateGeneric(_, _, _) => {
                RequirementOpCode::CertificateGeneric
            }
            CodeRequirementExpression::AnchorAppleGeneric => RequirementOpCode::AnchorAppleGeneric,
            CodeRequirementExpression::EntitlementsKey(_, _) => {
                RequirementOpCode::EntitlementsField
            }
            CodeRequirementExpression::CertificatePolicy(_, _, _) => {
                RequirementOpCode::CertificatePolicy
            }
            CodeRequirementExpression::NamedAnchor(_) => RequirementOpCode::NamedAnchor,
            CodeRequirementExpression::NamedCode(_) => RequirementOpCode::NamedCode,
            CodeRequirementExpression::Platform(_) => RequirementOpCode::Platform,
            CodeRequirementExpression::Notarized => RequirementOpCode::Notarized,
            CodeRequirementExpression::CertificateFieldDate(_, _, _) => {
                RequirementOpCode::CertificateFieldDate
            }
            CodeRequirementExpression::LegacyDeveloperId => RequirementOpCode::LegacyDeveloperId,
        }
    }
}

impl<'a> CodeRequirementExpression<'a> {
    /// Construct an expression element by reading from a slice.
    ///
    /// Returns the newly constructed element and remaining data in the slice.
    pub fn from_bytes(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let opcode_raw = data.pread_with::<u32>(0, scroll::BE)?;

        let _flags = opcode_raw & OPCODE_FLAG_MASK;
        let opcode = opcode_raw & OPCODE_VALUE_MASK;

        let data = &data[4..];

        let opcode = RequirementOpCode::try_from(opcode)?;

        opcode.parse_payload(data)
    }

    /// Write binary representation of this expression to a destination.
    pub fn write_to(&self, dest: &mut impl Write) -> Result<(), AppleCodesignError> {
        dest.iowrite_with(RequirementOpCode::from(self) as u32, scroll::BE)?;

        match self {
            Self::False => {}
            Self::True => {}
            Self::Identifier(s) => {
                write_data(dest, s.as_bytes())?;
            }
            Self::AnchorApple => {}
            Self::AnchorCertificateHash(slot, hash) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, hash)?;
            }
            Self::InfoKeyValueLegacy(key, value) => {
                write_data(dest, key.as_bytes())?;
                write_data(dest, value.as_bytes())?;
            }
            Self::And(a, b) => {
                a.write_to(dest)?;
                b.write_to(dest)?;
            }
            Self::Or(a, b) => {
                a.write_to(dest)?;
                b.write_to(dest)?;
            }
            Self::CodeDirectoryHash(hash) => {
                write_data(dest, hash)?;
            }
            Self::Not(expr) => {
                expr.write_to(dest)?;
            }
            Self::InfoPlistKeyField(key, m) => {
                write_data(dest, key.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificateField(slot, field, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, field.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificateTrusted(slot) => {
                dest.iowrite_with(*slot, scroll::BE)?;
            }
            Self::AnchorTrusted => {}
            Self::CertificateGeneric(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::AnchorAppleGeneric => {}
            Self::EntitlementsKey(key, m) => {
                write_data(dest, key.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificatePolicy(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::NamedAnchor(value) => {
                write_data(dest, value.as_bytes())?;
            }
            Self::NamedCode(value) => {
                write_data(dest, value.as_bytes())?;
            }
            Self::Platform(value) => {
                dest.iowrite_with(*value, scroll::BE)?;
            }
            Self::Notarized => {}
            Self::CertificateFieldDate(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::LegacyDeveloperId => {}
        }

        Ok(())
    }

    /// Produce the binary serialization of this expression.
    ///
    /// The blob header/magic is not included.
    pub fn to_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
        let mut res = vec![];

        self.write_to(&mut res)?;

        Ok(res)
    }
}

/// A code requirement match expression type.
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
enum MatchType {
    Exists = 0,
    Equal = 1,
    Contains = 2,
    BeginsWith = 3,
    EndsWith = 4,
    LessThan = 5,
    GreaterThan = 6,
    LessThanEqual = 7,
    GreaterThanEqual = 8,
    On = 9,
    Before = 10,
    After = 11,
    OnOrBefore = 12,
    OnOrAfter = 13,
    Absent = 14,
}

impl TryFrom<u32> for MatchType {
    type Error = AppleCodesignError;

    fn try_from(v: u32) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Self::Exists),
            1 => Ok(Self::Equal),
            2 => Ok(Self::Contains),
            3 => Ok(Self::BeginsWith),
            4 => Ok(Self::EndsWith),
            5 => Ok(Self::LessThan),
            6 => Ok(Self::GreaterThan),
            7 => Ok(Self::LessThanEqual),
            8 => Ok(Self::GreaterThanEqual),
            9 => Ok(Self::On),
            10 => Ok(Self::Before),
            11 => Ok(Self::After),
            12 => Ok(Self::OnOrBefore),
            13 => Ok(Self::OnOrAfter),
            14 => Ok(Self::Absent),
            _ => Err(AppleCodesignError::RequirementUnknownMatchExpression(v)),
        }
    }
}

impl MatchType {
    /// Parse the payload of a match expression.
    pub fn parse_payload<'a>(
        &self,
        data: &'a [u8],
    ) -> Result<(CodeRequirementMatchExpression<'a>, &'a [u8]), AppleCodesignError> {
        match self {
            Self::Exists => Ok((CodeRequirementMatchExpression::Exists, data)),
            Self::Equal => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::Equal(value.into()), data))
            }
            Self::Contains => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::Contains(value.into()), data))
            }
            Self::BeginsWith => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::BeginsWith(value.into()),
                    data,
                ))
            }
            Self::EndsWith => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::EndsWith(value.into()), data))
            }
            Self::LessThan => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::LessThan(value.into()), data))
            }
            Self::GreaterThan => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::GreaterThan(value.into()),
                    data,
                ))
            }
            Self::LessThanEqual => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::LessThanEqual(value.into()),
                    data,
                ))
            }
            Self::GreaterThanEqual => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::GreaterThanEqual(value.into()),
                    data,
                ))
            }
            Self::On => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::On(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::Before => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::Before(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::After => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::After(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::OnOrBefore => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::OnOrBefore(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::OnOrAfter => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::OnOrAfter(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::Absent => Ok((CodeRequirementMatchExpression::Absent, data)),
        }
    }
}

/// An instance of a match expression in a [CodeRequirementExpression].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CodeRequirementMatchExpression<'a> {
    /// Entity exists.
    ///
    /// `exists`
    ///
    /// No payload.
    Exists,

    /// Equality.
    ///
    /// `= <value>`
    ///
    /// 4 bytes length, raw data.
    Equal(CodeRequirementValue<'a>),

    /// Contains.
    ///
    /// `~ <value>`
    ///
    /// 4 bytes length, raw data.
    Contains(CodeRequirementValue<'a>),

    /// Begins with.
    ///
    /// `= <value>*`
    ///
    /// 4 bytes length, raw data.
    BeginsWith(CodeRequirementValue<'a>),

    /// Ends with.
    ///
    /// `= *<value>`
    ///
    /// 4 bytes length, raw data.
    EndsWith(CodeRequirementValue<'a>),

    /// Less than.
    ///
    /// `< <value>`
    ///
    /// 4 bytes length, raw data.
    LessThan(CodeRequirementValue<'a>),

    /// Greater than.
    ///
    /// `> <value>`
    GreaterThan(CodeRequirementValue<'a>),

    /// Less than or equal to.
    ///
    /// `<= <value>`
    ///
    /// 4 bytes length, raw data.
    LessThanEqual(CodeRequirementValue<'a>),

    /// Greater than or equal to.
    ///
    /// `>= <value>`
    ///
    /// 4 bytes length, raw data.
    GreaterThanEqual(CodeRequirementValue<'a>),

    /// Timestamp value equivalent.
    ///
    /// `= timestamp "<timestamp>"`
    On(chrono::DateTime<chrono::Utc>),

    /// Timestamp value before.
    ///
    /// `< timestamp "<timestamp>"`
    Before(chrono::DateTime<chrono::Utc>),

    /// Timestamp value after.
    ///
    /// `> timestamp "<timestamp>"`
    After(chrono::DateTime<chrono::Utc>),

    /// Timestamp value equivalent or before.
    ///
    /// `<= timestamp "<timestamp>"`
    OnOrBefore(chrono::DateTime<chrono::Utc>),

    /// Timestamp value equivalent or after.
    ///
    /// `>= timestamp "<timestamp>"`
    OnOrAfter(chrono::DateTime<chrono::Utc>),

    /// Value is absent.
    ///
    /// `<empty>`
    ///
    /// No payload.
    Absent,
}

impl<'a> Display for CodeRequirementMatchExpression<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Exists => f.write_str("/* exists */"),
            Self::Equal(value) => f.write_fmt(format_args!("= \"{value}\"")),
            Self::Contains(value) => f.write_fmt(format_args!("~ \"{value}\"")),
            Self::BeginsWith(value) => f.write_fmt(format_args!("= \"{value}*\"")),
            Self::EndsWith(value) => f.write_fmt(format_args!("= \"*{value}\"")),
            Self::LessThan(value) => f.write_fmt(format_args!("< \"{value}\"")),
            Self::GreaterThan(value) => f.write_fmt(format_args!("> \"{value}\"")),
            Self::LessThanEqual(value) => f.write_fmt(format_args!("<= \"{value}\"")),
            Self::GreaterThanEqual(value) => f.write_fmt(format_args!(">= \"{value}\"")),
            Self::On(value) => f.write_fmt(format_args!("= \"{value}\"")),
            Self::Before(value) => f.write_fmt(format_args!("< \"{value}\"")),
            Self::After(value) => f.write_fmt(format_args!("> \"{value}\"")),
            Self::OnOrBefore(value) => f.write_fmt(format_args!("<= \"{value}\"")),
            Self::OnOrAfter(value) => f.write_fmt(format_args!(">= \"{value}\"")),
            Self::Absent => f.write_str("absent"),
        }
    }
}

impl<'a> From<&CodeRequirementMatchExpression<'a>> for MatchType {
    fn from(m: &CodeRequirementMatchExpression<'a>) -> Self {
        match m {
            CodeRequirementMatchExpression::Exists => MatchType::Exists,
            CodeRequirementMatchExpression::Equal(_) => MatchType::Equal,
            CodeRequirementMatchExpression::Contains(_) => MatchType::Contains,
            CodeRequirementMatchExpression::BeginsWith(_) => MatchType::BeginsWith,
            CodeRequirementMatchExpression::EndsWith(_) => MatchType::EndsWith,
            CodeRequirementMatchExpression::LessThan(_) => MatchType::LessThan,
            CodeRequirementMatchExpression::GreaterThan(_) => MatchType::GreaterThan,
            CodeRequirementMatchExpression::LessThanEqual(_) => MatchType::LessThanEqual,
            CodeRequirementMatchExpression::GreaterThanEqual(_) => MatchType::GreaterThanEqual,
            CodeRequirementMatchExpression::On(_) => MatchType::On,
            CodeRequirementMatchExpression::Before(_) => MatchType::Before,
            CodeRequirementMatchExpression::After(_) => MatchType::After,
            CodeRequirementMatchExpression::OnOrBefore(_) => MatchType::OnOrBefore,
            CodeRequirementMatchExpression::OnOrAfter(_) => MatchType::OnOrAfter,
            CodeRequirementMatchExpression::Absent => MatchType::Absent,
        }
    }
}

impl<'a> CodeRequirementMatchExpression<'a> {
    /// Parse a match expression from bytes.
    ///
    /// The slice should begin with the match type u32.
    pub fn from_bytes(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let typ = data.pread_with::<u32>(0, scroll::BE)?;

        let typ = MatchType::try_from(typ)?;

        typ.parse_payload(&data[4..])
    }

    /// Write binary representation of this match expression to a destination.
    pub fn write_to(&self, dest: &mut impl Write) -> Result<(), AppleCodesignError> {
        dest.iowrite_with(MatchType::from(self) as u32, scroll::BE)?;

        match self {
            Self::Exists => {}
            Self::Equal(value) => value.write_encoded(dest)?,
            Self::Contains(value) => value.write_encoded(dest)?,
            Self::BeginsWith(value) => value.write_encoded(dest)?,
            Self::EndsWith(value) => value.write_encoded(dest)?,
            Self::LessThan(value) => value.write_encoded(dest)?,
            Self::GreaterThan(value) => value.write_encoded(dest)?,
            Self::LessThanEqual(value) => value.write_encoded(dest)?,
            Self::GreaterThanEqual(value) => value.write_encoded(dest)?,
            Self::On(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::Before(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::After(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::OnOrBefore(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::OnOrAfter(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::Absent => {}
        }

        Ok(())
    }
}

/// Represents a series of [CodeRequirementExpression].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CodeRequirements<'a>(Vec<CodeRequirementExpression<'a>>);

impl<'a> Deref for CodeRequirements<'a> {
    type Target = Vec<CodeRequirementExpression<'a>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> DerefMut for CodeRequirements<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a> Display for CodeRequirements<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, expr) in self.0.iter().enumerate() {
            f.write_fmt(format_args!("{i}: {expr};"))?;
        }

        Ok(())
    }
}

impl<'a> From<Vec<CodeRequirementExpression<'a>>> for CodeRequirements<'a> {
    fn from(v: Vec<CodeRequirementExpression<'a>>) -> Self {
        Self(v)
    }
}

impl<'a> CodeRequirements<'a> {
    /// Parse the binary serialization of code requirements.
    ///
    /// This parses the data that follows the requirement blob header/magic that
    /// usually accompanies the binary representation of code requirements.
    pub fn parse_binary(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let count = data.pread_with::<u32>(0, scroll::BE)?;
        let mut data = &data[4..];

        let mut elements = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let res = CodeRequirementExpression::from_bytes(data)?;

            elements.push(res.0);
            data = res.1;
        }

        Ok((Self(elements), data))
    }

Write binary representation of this expression to a destination.

Examples found in repository?
src/code_requirement.rs (line 818)
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
    pub fn write_to(&self, dest: &mut impl Write) -> Result<(), AppleCodesignError> {
        dest.iowrite_with(RequirementOpCode::from(self) as u32, scroll::BE)?;

        match self {
            Self::False => {}
            Self::True => {}
            Self::Identifier(s) => {
                write_data(dest, s.as_bytes())?;
            }
            Self::AnchorApple => {}
            Self::AnchorCertificateHash(slot, hash) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, hash)?;
            }
            Self::InfoKeyValueLegacy(key, value) => {
                write_data(dest, key.as_bytes())?;
                write_data(dest, value.as_bytes())?;
            }
            Self::And(a, b) => {
                a.write_to(dest)?;
                b.write_to(dest)?;
            }
            Self::Or(a, b) => {
                a.write_to(dest)?;
                b.write_to(dest)?;
            }
            Self::CodeDirectoryHash(hash) => {
                write_data(dest, hash)?;
            }
            Self::Not(expr) => {
                expr.write_to(dest)?;
            }
            Self::InfoPlistKeyField(key, m) => {
                write_data(dest, key.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificateField(slot, field, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, field.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificateTrusted(slot) => {
                dest.iowrite_with(*slot, scroll::BE)?;
            }
            Self::AnchorTrusted => {}
            Self::CertificateGeneric(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::AnchorAppleGeneric => {}
            Self::EntitlementsKey(key, m) => {
                write_data(dest, key.as_bytes())?;
                m.write_to(dest)?;
            }
            Self::CertificatePolicy(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::NamedAnchor(value) => {
                write_data(dest, value.as_bytes())?;
            }
            Self::NamedCode(value) => {
                write_data(dest, value.as_bytes())?;
            }
            Self::Platform(value) => {
                dest.iowrite_with(*value, scroll::BE)?;
            }
            Self::Notarized => {}
            Self::CertificateFieldDate(slot, oid, m) => {
                dest.iowrite_with(*slot, scroll::BE)?;
                write_data(dest, oid.as_ref())?;
                m.write_to(dest)?;
            }
            Self::LegacyDeveloperId => {}
        }

        Ok(())
    }

    /// Produce the binary serialization of this expression.
    ///
    /// The blob header/magic is not included.
    pub fn to_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
        let mut res = vec![];

        self.write_to(&mut res)?;

        Ok(res)
    }
}

/// A code requirement match expression type.
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
enum MatchType {
    Exists = 0,
    Equal = 1,
    Contains = 2,
    BeginsWith = 3,
    EndsWith = 4,
    LessThan = 5,
    GreaterThan = 6,
    LessThanEqual = 7,
    GreaterThanEqual = 8,
    On = 9,
    Before = 10,
    After = 11,
    OnOrBefore = 12,
    OnOrAfter = 13,
    Absent = 14,
}

impl TryFrom<u32> for MatchType {
    type Error = AppleCodesignError;

    fn try_from(v: u32) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Self::Exists),
            1 => Ok(Self::Equal),
            2 => Ok(Self::Contains),
            3 => Ok(Self::BeginsWith),
            4 => Ok(Self::EndsWith),
            5 => Ok(Self::LessThan),
            6 => Ok(Self::GreaterThan),
            7 => Ok(Self::LessThanEqual),
            8 => Ok(Self::GreaterThanEqual),
            9 => Ok(Self::On),
            10 => Ok(Self::Before),
            11 => Ok(Self::After),
            12 => Ok(Self::OnOrBefore),
            13 => Ok(Self::OnOrAfter),
            14 => Ok(Self::Absent),
            _ => Err(AppleCodesignError::RequirementUnknownMatchExpression(v)),
        }
    }
}

impl MatchType {
    /// Parse the payload of a match expression.
    pub fn parse_payload<'a>(
        &self,
        data: &'a [u8],
    ) -> Result<(CodeRequirementMatchExpression<'a>, &'a [u8]), AppleCodesignError> {
        match self {
            Self::Exists => Ok((CodeRequirementMatchExpression::Exists, data)),
            Self::Equal => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::Equal(value.into()), data))
            }
            Self::Contains => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::Contains(value.into()), data))
            }
            Self::BeginsWith => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::BeginsWith(value.into()),
                    data,
                ))
            }
            Self::EndsWith => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::EndsWith(value.into()), data))
            }
            Self::LessThan => {
                let (value, data) = read_data(data)?;

                Ok((CodeRequirementMatchExpression::LessThan(value.into()), data))
            }
            Self::GreaterThan => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::GreaterThan(value.into()),
                    data,
                ))
            }
            Self::LessThanEqual => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::LessThanEqual(value.into()),
                    data,
                ))
            }
            Self::GreaterThanEqual => {
                let (value, data) = read_data(data)?;

                Ok((
                    CodeRequirementMatchExpression::GreaterThanEqual(value.into()),
                    data,
                ))
            }
            Self::On => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::On(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::Before => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::Before(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::After => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::After(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::OnOrBefore => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::OnOrBefore(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::OnOrAfter => {
                let value = data.pread_with::<i64>(0, scroll::BE)?;

                Ok((
                    CodeRequirementMatchExpression::OnOrAfter(
                        chrono::Utc
                            .timestamp_opt(value, 0)
                            .single()
                            .ok_or(AppleCodesignError::BadTime)?,
                    ),
                    &data[8..],
                ))
            }
            Self::Absent => Ok((CodeRequirementMatchExpression::Absent, data)),
        }
    }
}

/// An instance of a match expression in a [CodeRequirementExpression].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CodeRequirementMatchExpression<'a> {
    /// Entity exists.
    ///
    /// `exists`
    ///
    /// No payload.
    Exists,

    /// Equality.
    ///
    /// `= <value>`
    ///
    /// 4 bytes length, raw data.
    Equal(CodeRequirementValue<'a>),

    /// Contains.
    ///
    /// `~ <value>`
    ///
    /// 4 bytes length, raw data.
    Contains(CodeRequirementValue<'a>),

    /// Begins with.
    ///
    /// `= <value>*`
    ///
    /// 4 bytes length, raw data.
    BeginsWith(CodeRequirementValue<'a>),

    /// Ends with.
    ///
    /// `= *<value>`
    ///
    /// 4 bytes length, raw data.
    EndsWith(CodeRequirementValue<'a>),

    /// Less than.
    ///
    /// `< <value>`
    ///
    /// 4 bytes length, raw data.
    LessThan(CodeRequirementValue<'a>),

    /// Greater than.
    ///
    /// `> <value>`
    GreaterThan(CodeRequirementValue<'a>),

    /// Less than or equal to.
    ///
    /// `<= <value>`
    ///
    /// 4 bytes length, raw data.
    LessThanEqual(CodeRequirementValue<'a>),

    /// Greater than or equal to.
    ///
    /// `>= <value>`
    ///
    /// 4 bytes length, raw data.
    GreaterThanEqual(CodeRequirementValue<'a>),

    /// Timestamp value equivalent.
    ///
    /// `= timestamp "<timestamp>"`
    On(chrono::DateTime<chrono::Utc>),

    /// Timestamp value before.
    ///
    /// `< timestamp "<timestamp>"`
    Before(chrono::DateTime<chrono::Utc>),

    /// Timestamp value after.
    ///
    /// `> timestamp "<timestamp>"`
    After(chrono::DateTime<chrono::Utc>),

    /// Timestamp value equivalent or before.
    ///
    /// `<= timestamp "<timestamp>"`
    OnOrBefore(chrono::DateTime<chrono::Utc>),

    /// Timestamp value equivalent or after.
    ///
    /// `>= timestamp "<timestamp>"`
    OnOrAfter(chrono::DateTime<chrono::Utc>),

    /// Value is absent.
    ///
    /// `<empty>`
    ///
    /// No payload.
    Absent,
}

impl<'a> Display for CodeRequirementMatchExpression<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Exists => f.write_str("/* exists */"),
            Self::Equal(value) => f.write_fmt(format_args!("= \"{value}\"")),
            Self::Contains(value) => f.write_fmt(format_args!("~ \"{value}\"")),
            Self::BeginsWith(value) => f.write_fmt(format_args!("= \"{value}*\"")),
            Self::EndsWith(value) => f.write_fmt(format_args!("= \"*{value}\"")),
            Self::LessThan(value) => f.write_fmt(format_args!("< \"{value}\"")),
            Self::GreaterThan(value) => f.write_fmt(format_args!("> \"{value}\"")),
            Self::LessThanEqual(value) => f.write_fmt(format_args!("<= \"{value}\"")),
            Self::GreaterThanEqual(value) => f.write_fmt(format_args!(">= \"{value}\"")),
            Self::On(value) => f.write_fmt(format_args!("= \"{value}\"")),
            Self::Before(value) => f.write_fmt(format_args!("< \"{value}\"")),
            Self::After(value) => f.write_fmt(format_args!("> \"{value}\"")),
            Self::OnOrBefore(value) => f.write_fmt(format_args!("<= \"{value}\"")),
            Self::OnOrAfter(value) => f.write_fmt(format_args!(">= \"{value}\"")),
            Self::Absent => f.write_str("absent"),
        }
    }
}

impl<'a> From<&CodeRequirementMatchExpression<'a>> for MatchType {
    fn from(m: &CodeRequirementMatchExpression<'a>) -> Self {
        match m {
            CodeRequirementMatchExpression::Exists => MatchType::Exists,
            CodeRequirementMatchExpression::Equal(_) => MatchType::Equal,
            CodeRequirementMatchExpression::Contains(_) => MatchType::Contains,
            CodeRequirementMatchExpression::BeginsWith(_) => MatchType::BeginsWith,
            CodeRequirementMatchExpression::EndsWith(_) => MatchType::EndsWith,
            CodeRequirementMatchExpression::LessThan(_) => MatchType::LessThan,
            CodeRequirementMatchExpression::GreaterThan(_) => MatchType::GreaterThan,
            CodeRequirementMatchExpression::LessThanEqual(_) => MatchType::LessThanEqual,
            CodeRequirementMatchExpression::GreaterThanEqual(_) => MatchType::GreaterThanEqual,
            CodeRequirementMatchExpression::On(_) => MatchType::On,
            CodeRequirementMatchExpression::Before(_) => MatchType::Before,
            CodeRequirementMatchExpression::After(_) => MatchType::After,
            CodeRequirementMatchExpression::OnOrBefore(_) => MatchType::OnOrBefore,
            CodeRequirementMatchExpression::OnOrAfter(_) => MatchType::OnOrAfter,
            CodeRequirementMatchExpression::Absent => MatchType::Absent,
        }
    }
}

impl<'a> CodeRequirementMatchExpression<'a> {
    /// Parse a match expression from bytes.
    ///
    /// The slice should begin with the match type u32.
    pub fn from_bytes(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let typ = data.pread_with::<u32>(0, scroll::BE)?;

        let typ = MatchType::try_from(typ)?;

        typ.parse_payload(&data[4..])
    }

    /// Write binary representation of this match expression to a destination.
    pub fn write_to(&self, dest: &mut impl Write) -> Result<(), AppleCodesignError> {
        dest.iowrite_with(MatchType::from(self) as u32, scroll::BE)?;

        match self {
            Self::Exists => {}
            Self::Equal(value) => value.write_encoded(dest)?,
            Self::Contains(value) => value.write_encoded(dest)?,
            Self::BeginsWith(value) => value.write_encoded(dest)?,
            Self::EndsWith(value) => value.write_encoded(dest)?,
            Self::LessThan(value) => value.write_encoded(dest)?,
            Self::GreaterThan(value) => value.write_encoded(dest)?,
            Self::LessThanEqual(value) => value.write_encoded(dest)?,
            Self::GreaterThanEqual(value) => value.write_encoded(dest)?,
            Self::On(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::Before(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::After(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::OnOrBefore(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::OnOrAfter(value) => dest.iowrite_with(value.timestamp(), scroll::BE)?,
            Self::Absent => {}
        }

        Ok(())
    }
}

/// Represents a series of [CodeRequirementExpression].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CodeRequirements<'a>(Vec<CodeRequirementExpression<'a>>);

impl<'a> Deref for CodeRequirements<'a> {
    type Target = Vec<CodeRequirementExpression<'a>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> DerefMut for CodeRequirements<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a> Display for CodeRequirements<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, expr) in self.0.iter().enumerate() {
            f.write_fmt(format_args!("{i}: {expr};"))?;
        }

        Ok(())
    }
}

impl<'a> From<Vec<CodeRequirementExpression<'a>>> for CodeRequirements<'a> {
    fn from(v: Vec<CodeRequirementExpression<'a>>) -> Self {
        Self(v)
    }
}

impl<'a> CodeRequirements<'a> {
    /// Parse the binary serialization of code requirements.
    ///
    /// This parses the data that follows the requirement blob header/magic that
    /// usually accompanies the binary representation of code requirements.
    pub fn parse_binary(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let count = data.pread_with::<u32>(0, scroll::BE)?;
        let mut data = &data[4..];

        let mut elements = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let res = CodeRequirementExpression::from_bytes(data)?;

            elements.push(res.0);
            data = res.1;
        }

        Ok((Self(elements), data))
    }

    /// Parse a code requirement blob, which begins with header magic.
    ///
    /// This can be used to parse the output generated by `csreq -b`.
    pub fn parse_blob(data: &'a [u8]) -> Result<(Self, &'a [u8]), AppleCodesignError> {
        let data = read_and_validate_blob_header(
            data,
            u32::from(CodeSigningMagic::Requirement),
            "code requirement blob",
        )
        .map_err(|_| AppleCodesignError::RequirementMalformed("blob header"))?;

        Self::parse_binary(data)
    }

    /// Write binary representation of these expressions to a destination.
    ///
    /// The blob header/magic is not written.
    pub fn write_to(&self, dest: &mut impl Write) -> Result<(), AppleCodesignError> {
        dest.iowrite_with(self.0.len() as u32, scroll::BE)?;
        for e in &self.0 {
            e.write_to(dest)?;
        }

        Ok(())
    }

Produce the binary serialization of this expression.

The blob header/magic is not included.

Examples found in repository?
src/signing_settings.rs (line 536)
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
    pub fn set_designated_requirement_expression(
        &mut self,
        scope: SettingsScope,
        expr: &CodeRequirementExpression,
    ) -> Result<(), AppleCodesignError> {
        self.designated_requirement.insert(
            scope,
            DesignatedRequirementMode::Explicit(vec![expr.to_bytes()?]),
        );

        Ok(())
    }

    /// Set the designated requirement expression for a Mach-O binary given serialized bytes.
    ///
    /// This is like [SigningSettings::set_designated_requirement_expression] except the
    /// designated requirement expression is given as serialized bytes. The bytes passed are
    /// the value that would be produced by compiling a code requirement expression via
    /// `csreq -b`.
    pub fn set_designated_requirement_bytes(
        &mut self,
        scope: SettingsScope,
        data: impl AsRef<[u8]>,
    ) -> Result<(), AppleCodesignError> {
        let blob = RequirementBlob::from_blob_bytes(data.as_ref())?;

        self.designated_requirement.insert(
            scope,
            DesignatedRequirementMode::Explicit(
                blob.parse_expressions()?
                    .iter()
                    .map(|x| x.to_bytes())
                    .collect::<Result<Vec<_>, AppleCodesignError>>()?,
            ),
        );

        Ok(())
    }

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
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

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
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