pub enum CertificateAuthorityExtension {
    AppleWorldwideDeveloperRelations,
    AppleApplicationIntegration,
    DeveloperId,
    AppleTimestamp,
    DeveloperAuthentication,
    AppleApplicationIntegrationG3,
    AppleWorldwideDeveloperRelationsG2,
    AppleSoftwareUpdateCertification,
}
Expand description

Denotes specific certificate extensions on Apple certificate authority certificates.

Apple’s CA certificates have extensions that appear to identify the role of that CA. This enumeration defines those.

Variants§

§

AppleWorldwideDeveloperRelations

Apple Worldwide Developer Relations.

An intermediate CA.

§

AppleApplicationIntegration

Apple Application Integration.

§

DeveloperId

Developer ID Certification Authority.

§

AppleTimestamp

Apple Timestamp.

§

DeveloperAuthentication

Developer Authentication Certification Authority.

§

AppleApplicationIntegrationG3

Application Application Integration CA - G3.

§

AppleWorldwideDeveloperRelationsG2

Apple Worldwide Developer Relations CA - G2.

§

AppleSoftwareUpdateCertification

Apple Software Update Certification.

Implementations§

Obtain all variants of this enumeration.

Examples found in repository?
src/cli.rs (line 2472)
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
fn command_x509_oids(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    println!("# Extended Key Usage (EKU) Extension OIDs");
    println!();
    for ekup in crate::certificate::ExtendedKeyUsagePurpose::all() {
        println!("{}\t{:?}", ekup.as_oid(), ekup);
    }
    println!();
    println!("# Code Signing Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CodeSigningCertificateExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }
    println!();
    println!("# Certificate Authority Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CertificateAuthorityExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }

    Ok(())
}

All the known OIDs constituting Apple CA extensions.

Examples found in repository?
src/policy.rs (line 46)
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
static POLICY_MAC_DEVELOPER_ID: Lazy<CodeRequirementExpression<'static>> = Lazy::new(|| {
    CodeRequirementExpression::And(
        Box::new(CodeRequirementExpression::And(
            Box::new(CodeRequirementExpression::AnchorAppleGeneric),
            Box::new(CodeRequirementExpression::CertificateGeneric(
                1,
                CertificateAuthorityExtension::DeveloperId.as_oid(),
                CodeRequirementMatchExpression::Exists,
            )),
        )),
        Box::new(CodeRequirementExpression::Or(
            Box::new(CodeRequirementExpression::CertificateGeneric(
                0,
                CodeSigningCertificateExtension::DeveloperIdInstaller.as_oid(),
                CodeRequirementMatchExpression::Exists,
            )),
            Box::new(CodeRequirementExpression::CertificateGeneric(
                0,
                CodeSigningCertificateExtension::DeveloperIdApplication.as_oid(),
                CodeRequirementMatchExpression::Exists,
            )),
        )),
    )
});

/// Notarized executable.
///
/// `anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and
/// certificate leaf[field.1.2.840.113635.100.6.1.13] exists and notarized'`
///
static POLICY_NOTARIZED_EXECUTABLE: Lazy<CodeRequirementExpression<'static>> = Lazy::new(|| {
    CodeRequirementExpression::And(
        Box::new(CodeRequirementExpression::And(
            Box::new(CodeRequirementExpression::And(
                Box::new(CodeRequirementExpression::AnchorAppleGeneric),
                Box::new(CodeRequirementExpression::CertificateGeneric(
                    1,
                    CertificateAuthorityExtension::DeveloperId.as_oid(),
                    CodeRequirementMatchExpression::Exists,
                )),
            )),
            Box::new(CodeRequirementExpression::CertificateGeneric(
                0,
                CodeSigningCertificateExtension::DeveloperIdApplication.as_oid(),
                CodeRequirementMatchExpression::Exists,
            )),
        )),
        Box::new(CodeRequirementExpression::Notarized),
    )
});

/// Notarized installer.
///
/// `'anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists
/// and (certificate leaf[field.1.2.840.113635.100.6.1.14] or certificate
/// leaf[field.1.2.840.113635.100.6.1.13]) and notarized'`
static POLICY_NOTARIZED_INSTALLER: Lazy<CodeRequirementExpression<'static>> = Lazy::new(|| {
    CodeRequirementExpression::And(
        Box::new(CodeRequirementExpression::And(
            Box::new(CodeRequirementExpression::And(
                Box::new(CodeRequirementExpression::AnchorAppleGeneric),
                Box::new(CodeRequirementExpression::CertificateGeneric(
                    1,
                    CertificateAuthorityExtension::DeveloperId.as_oid(),
                    CodeRequirementMatchExpression::Exists,
                )),
            )),
            Box::new(CodeRequirementExpression::Or(
                Box::new(CodeRequirementExpression::CertificateGeneric(
                    0,
                    CodeSigningCertificateExtension::DeveloperIdInstaller.as_oid(),
                    CodeRequirementMatchExpression::Exists,
                )),
                Box::new(CodeRequirementExpression::CertificateGeneric(
                    0,
                    CodeSigningCertificateExtension::DeveloperIdApplication.as_oid(),
                    CodeRequirementMatchExpression::Exists,
                )),
            )),
        )),
        Box::new(CodeRequirementExpression::Notarized),
    )
});

/// Defines well-known execution policies for signed code.
///
/// Instances can be obtained from a human-readable string for convenience. Those
/// strings are:
///
/// * `developer-id-signed`
/// * `developer-id-notarized-executable`
/// * `developer-id-notarized-installer`
#[allow(clippy::enum_variant_names)]
pub enum ExecutionPolicy {
    /// Code is signed by a certificate authorized for signing Mac applications or
    /// installers and that certificate was issued by
    /// [crate::apple_certificates::KnownCertificate::DeveloperIdG1] or
    /// [crate::apple_certificates::KnownCertificate::DeveloperIdG2].
    ///
    /// This is the policy that applies when you get a `Developer ID Application` or
    /// `Developer ID Installer` certificate from Apple.
    DeveloperIdSigned,

    /// Like [Self::DeveloperIdSigned] but only applies to executables (not installers)
    /// and the executable must be notarized.
    ///
    /// If you notarize an individual executable, you effectively convert the
    /// [Self::DeveloperIdSigned] policy into this variant.
    DeveloperIdNotarizedExecutable,

    /// Like [Self::DeveloperIdSigned] but only applies to installers (not executables)
    /// and the installer must be notarized.
    ///
    /// If you notarize an individual installer, you effectively convert the
    /// [Self::DeveloperIdSigned] policy into this variant.
    DeveloperIdNotarizedInstaller,
}

impl Deref for ExecutionPolicy {
    type Target = CodeRequirementExpression<'static>;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::DeveloperIdSigned => POLICY_MAC_DEVELOPER_ID.deref(),
            Self::DeveloperIdNotarizedExecutable => POLICY_NOTARIZED_EXECUTABLE.deref(),
            Self::DeveloperIdNotarizedInstaller => POLICY_NOTARIZED_INSTALLER.deref(),
        }
    }
}

impl TryFrom<&str> for ExecutionPolicy {
    type Error = AppleCodesignError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s {
            "developer-id-signed" => Ok(Self::DeveloperIdSigned),
            "developer-id-notarized-executable" => Ok(Self::DeveloperIdNotarizedExecutable),
            "developer-id-notarized-installer" => Ok(Self::DeveloperIdNotarizedInstaller),
            _ => Err(AppleCodesignError::UnknownPolicy(s.to_string())),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn get_policies() {
        ExecutionPolicy::DeveloperIdSigned.to_bytes().unwrap();
        ExecutionPolicy::DeveloperIdNotarizedExecutable
            .to_bytes()
            .unwrap();
        ExecutionPolicy::DeveloperIdNotarizedInstaller
            .to_bytes()
            .unwrap();
    }
}

/// Derive a designated requirements expression given a code signing certificate.
///
/// This function figures out what the run-time requirements of a signed binary
/// should be given its code signing certificate.
///
/// We determine the flavor of Apple code signing certificate in use and apply an
/// appropriate requirements policy. We strive for behavior equivalence with
/// Apple's `codesign` tool.
pub fn derive_designated_requirements(
    cert: &CapturedX509Certificate,
    identifier: Option<String>,
) -> Result<Option<CodeRequirementExpression<'static>>, AppleCodesignError> {
    let profile = if let Some(profile) = cert.apple_guess_profile() {
        profile
    } else {
        return Ok(None);
    };

    match profile {
        // These appear to be the same policy.
        CertificateProfile::AppleDevelopment | CertificateProfile::AppleDistribution => {
            let cn = cert.subject_common_name().ok_or_else(|| {
                AppleCodesignError::PolicyFormulationError(format!(
                    "(deriving for {profile:?}) certificate common name not available"
                ))
            })?;

            let expr = CodeRequirementExpression::And(
                // It chains to Apple root CA.
                Box::new(CodeRequirementExpression::AnchorAppleGeneric),
                Box::new(CodeRequirementExpression::And(
                    // It was signed by this cert.
                    Box::new(CodeRequirementExpression::CertificateField(
                        0,
                        "subject.CN".to_string().into(),
                        CodeRequirementMatchExpression::Equal(cn.into()),
                    )),
                    // That cert was signed by a CA with WWDR extension.
                    Box::new(CodeRequirementExpression::CertificateGeneric(
                        1,
                        CertificateAuthorityExtension::AppleWorldwideDeveloperRelations.as_oid(),
                        CodeRequirementMatchExpression::Exists,
                    )),
                )),
            );

            Ok(Some(if let Some(identifier) = identifier {
                CodeRequirementExpression::And(
                    Box::new(CodeRequirementExpression::Identifier(identifier.into())),
                    Box::new(expr),
                )
            } else {
                expr
            }))
        }
        CertificateProfile::DeveloperIdApplication => {
            let team_id = cert.apple_team_id().ok_or_else(|| {
                AppleCodesignError::PolicyFormulationError(format!(
                    "(deriving for {profile:?}) could not find team identifier in signing certificate"
                ))
            })?;

            let expr = CodeRequirementExpression::And(
                // Chains to Apple root CA.
                Box::new(CodeRequirementExpression::AnchorAppleGeneric),
                Box::new(CodeRequirementExpression::And(
                    // Certificate issued by CA with Developer ID extension.
                    Box::new(CodeRequirementExpression::CertificateGeneric(
                        1,
                        CertificateAuthorityExtension::DeveloperId.as_oid(),
                        CodeRequirementMatchExpression::Exists,
                    )),
                    Box::new(CodeRequirementExpression::And(
                        // A certificate entrusted with Developer ID Application signing rights.
                        Box::new(CodeRequirementExpression::CertificateGeneric(
                            0,
                            CodeSigningCertificateExtension::DeveloperIdApplication.as_oid(),
                            CodeRequirementMatchExpression::Exists,
                        )),
                        // Signed by this team ID.
                        Box::new(CodeRequirementExpression::CertificateField(
                            0,
                            "subject.OU".to_string().into(),
                            CodeRequirementMatchExpression::Equal(team_id.into()),
                        )),
                    )),
                )),
            );

            Ok(Some(if let Some(identifier) = identifier {
                CodeRequirementExpression::And(
                    Box::new(CodeRequirementExpression::Identifier(identifier.into())),
                    Box::new(expr),
                )
            } else {
                expr
            }))
        }
        CertificateProfile::MacInstallerDistribution | CertificateProfile::DeveloperIdInstaller => {
            Err(AppleCodesignError::PolicyFormulationError(format!(
                "(deriving for {profile:?}) we do not know how to handle this policy"
            )))
        }
    }
}
More examples
Hide additional examples
src/cli.rs (line 809)
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
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
fn print_certificate_info(cert: &CapturedX509Certificate) -> Result<(), AppleCodesignError> {
    println!(
        "Subject CN:                  {}",
        cert.subject_common_name()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!(
        "Issuer CN:                   {}",
        cert.issuer_common_name()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!("Subject is Issuer?:          {}", cert.subject_is_issuer());
    println!(
        "Team ID:                     {}",
        cert.apple_team_id()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!(
        "SHA-1 fingerprint:           {}",
        hex::encode(cert.sha1_fingerprint()?)
    );
    println!(
        "SHA-256 fingerprint:         {}",
        hex::encode(cert.sha256_fingerprint()?)
    );
    if let Some(alg) = cert.key_algorithm() {
        println!("Key Algorithm:               {alg}");
    }
    if let Some(alg) = cert.signature_algorithm() {
        println!("Signature Algorithm:         {alg}");
    }
    println!(
        "Public Key Data:             {}",
        base64::encode(
            cert.to_public_key_der()
                .map_err(|e| AppleCodesignError::X509Parse(format!(
                    "error constructing SPKI: {e}"
                )))?
        )
    );
    println!(
        "Signed by Apple?:            {}",
        cert.chains_to_apple_root_ca()
    );
    if cert.chains_to_apple_root_ca() {
        println!("Apple Issuing Chain:");
        for signer in cert.apple_issuing_chain() {
            println!(
                "  - {}",
                signer
                    .subject_common_name()
                    .unwrap_or_else(|| "<unknown>".to_string())
            );
        }
    }

    println!(
        "Guessed Certificate Profile: {}",
        if let Some(profile) = cert.apple_guess_profile() {
            format!("{profile:?}")
        } else {
            "none".to_string()
        }
    );
    println!("Is Apple Root CA?:           {}", cert.is_apple_root_ca());
    println!(
        "Is Apple Intermediate CA?:   {}",
        cert.is_apple_intermediate_ca()
    );
    println!(
        "Apple CA Extension:          {}",
        if let Some(ext) = cert.apple_ca_extension() {
            format!("{} ({:?})", ext.as_oid(), ext)
        } else {
            "none".to_string()
        }
    );
    println!("Apple Extended Key Usage Purpose Extensions:");
    for purpose in cert.apple_extended_key_usage_purposes() {
        println!("  - {} ({:?})", purpose.as_oid(), purpose);
    }
    println!("Apple Code Signing Extensions:");
    for ext in cert.apple_code_signing_extensions() {
        println!("  - {} ({:?})", ext.as_oid(), ext);
    }
    print!(
        "\n{}",
        cert.to_public_key_pem(Default::default())
            .map_err(|e| AppleCodesignError::X509Parse(format!(
                "error constructing SPKI: {e}"
            )))?
    );
    print!("\n{}", cert.encode_pem());

    Ok(())
}

fn print_session_join(sjs_base64: &str, sjs_pem: &str) -> Result<(), RemoteSignError> {
    error!("");
    error!("Run the following command to join this signing session:");
    error!("");
    error!("    rcodesign remote-sign {}", sjs_base64);
    error!("");
    error!("Or if this output is too long, paste the following output:");
    error!("");
    for line in sjs_pem.lines() {
        error!("{}", line);
    }
    error!("");
    error!("Into an interactive editor using:");
    error!("");
    error!("    rcodesign remote-sign --editor");
    error!("");
    error!("Or into a new file whose path you define with:");
    error!("");
    error!("    rcodesign remote-sign --sjs-path /path/to/file/you/just/saved");
    error!("");
    error!("(waiting for remote signer to join)");

    Ok(())
}

#[allow(unused)]
fn prompt_smartcard_pin() -> Result<Vec<u8>, AppleCodesignError> {
    let pin = dialoguer::Password::new()
        .with_prompt("Please enter device PIN")
        .interact()?;

    Ok(pin.as_bytes().to_vec())
}

#[cfg(feature = "yubikey")]
fn handle_smartcard_sign_slot(
    slot: &str,
    pin_env_var: Option<&str>,
    private_keys: &mut Vec<Box<dyn PrivateKey>>,
    public_certificates: &mut Vec<CapturedX509Certificate>,
) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(slot)?;
    let formatted = hex::encode([u8::from(slot_id)]);
    let mut yk = YubiKey::new()?;

    if let Some(pin_var) = pin_env_var {
        let pin_var = pin_var.to_owned();

        yk.set_pin_callback(move || {
            if let Ok(pin) = std::env::var(&pin_var) {
                eprintln!("using PIN from {} environment variable", &pin_var);
                Ok(pin.as_bytes().to_vec())
            } else {
                prompt_smartcard_pin()
            }
        });
    } else {
        yk.set_pin_callback(prompt_smartcard_pin);
    }

    if let Some(cert) = yk.get_certificate_signer(slot_id)? {
        warn!("using certificate in smartcard slot {}", formatted);
        public_certificates.push(cert.certificate().clone());
        private_keys.push(Box::new(cert));

        Ok(())
    } else {
        Err(AppleCodesignError::SmartcardNoCertificate(formatted))
    }
}

#[cfg(not(feature = "yubikey"))]
fn handle_smartcard_sign_slot(
    _slot: &str,
    _pin_env_var: Option<&str>,
    _private_keys: &mut [Box<dyn PrivateKey>],
    _public_certificates: &mut [CapturedX509Certificate],
) -> Result<(), AppleCodesignError> {
    error!("smartcard support not available; ignoring --smartcard-slot");

    Ok(())
}

#[cfg(target_os = "macos")]
fn find_certificates_in_keychain(
    args: &ArgMatches,
    private_keys: &mut Vec<Box<dyn PrivateKey>>,
    public_certificates: &mut Vec<CapturedX509Certificate>,
) -> Result<(), AppleCodesignError> {
    // No arguments pertinent to keychains. Don't even speak to the
    // keychain API since this could only error.
    if !args.contains_id("keychain") {
        return Ok(());
    }

    // Collect all the keychain domains to search.
    let domains = if let Some(domains) = args.get_many::<String>("keychain_domain") {
        domains
            .into_iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
    } else {
        vec!["user".to_string()]
    };

    let domains = domains
        .into_iter()
        .map(|domain| {
            KeychainDomain::try_from(domain.as_str())
                .expect("clap should have validated domain values")
        })
        .collect::<Vec<_>>();

    // Now iterate all the keychains and try to find requested certificates.

    for domain in domains {
        for cert in keychain_find_code_signing_certificates(domain, None)? {
            let matches =
                if let Some(wanted_fingerprint) = args.get_one::<String>("keychain_fingerprint") {
                    let got_fingerprint = hex::encode(cert.sha256_fingerprint()?.as_ref());

                    wanted_fingerprint.to_ascii_lowercase() == got_fingerprint.to_ascii_lowercase()
                } else {
                    false
                };

            if matches {
                public_certificates.push(cert.as_captured_x509_certificate());
                private_keys.push(Box::new(cert));
            }
        }
    }

    Ok(())
}

#[cfg(not(target_os = "macos"))]
fn find_certificates_in_keychain(
    args: &ArgMatches,
    _private_keys: &mut [Box<dyn PrivateKey>],
    _public_certificates: &mut [CapturedX509Certificate],
) -> Result<(), AppleCodesignError> {
    if args.contains_id("keychain") {
        error!(
            "--keychain* arguments only supported on macOS and will be ignored on this platform"
        );
    }

    Ok(())
}

fn command_analyze_certificate(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let certs = collect_certificates_from_args(args, true)?.1;

    for (i, cert) in certs.into_iter().enumerate() {
        println!("# Certificate {i}");
        println!();
        print_certificate_info(&cert)?;
        println!();
    }

    Ok(())
}

fn command_compute_code_hashes(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let index = args.get_one::<String>("universal_index").unwrap();
    let index = usize::from_str(index).map_err(|_| AppleCodesignError::CliBadArgument)?;
    let hash_type = DigestType::try_from(args.get_one::<String>("hash").unwrap().as_str())?;
    let page_size = usize::from_str(
        args.get_one::<String>("page_size")
            .expect("page_size should have default value"),
    )
    .map_err(|_| AppleCodesignError::CliBadArgument)?;

    let data = std::fs::read(path)?;
    let mach = MachFile::parse(&data)?;
    let macho = mach.nth_macho(index)?;

    let hashes = macho.code_digests(hash_type, page_size)?;

    for hash in hashes {
        println!("{}", hex::encode(hash));
    }

    Ok(())
}

fn command_diff_signatures(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path0 = args
        .get_one::<String>("path0")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let path1 = args
        .get_one::<String>("path1")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let reader = SignatureReader::from_path(path0)?;

    let a_entities = reader.entities()?;

    let reader = SignatureReader::from_path(path1)?;
    let b_entities = reader.entities()?;

    let a = serde_yaml::to_string(&a_entities)?;
    let b = serde_yaml::to_string(&b_entities)?;

    let Changeset { diffs, .. } = Changeset::new(&a, &b, "\n");

    for item in diffs {
        match item {
            Difference::Same(ref x) => {
                for line in x.lines() {
                    println!(" {line}");
                }
            }
            Difference::Add(ref x) => {
                for line in x.lines() {
                    println!("+{line}");
                }
            }
            Difference::Rem(ref x) => {
                for line in x.lines() {
                    println!("-{line}");
                }
            }
        }
    }

    Ok(())
}

const ENCODE_APP_STORE_CONNECT_API_KEY_ABOUT: &str = "\
Encode an App Store Connect API Key to JSON.

App Store Connect API Keys
(https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api)
are defined by 3 components:

* The Issuer ID (likely a UUID)
* A Key ID (an alphanumeric value like `DEADBEEF42`)
* A PEM encoded ECDSA private key (typically a file beginning with
  `-----BEGIN PRIVATE KEY-----`).

This command is used to encode all API Key components into a single JSON
object so you only have to refer to a single entity when performing
operations (like notarization) using these API Keys.

The API Key components are specified as positional arguments.

By default, the JSON encoded unified representation is printed to stdout.
You can write to a file instead by passing `--output-path <path>`.

# Security Considerations

The App Store Connect API Key contains a private key and its value should be
treated as sensitive: if an unwanted party obtains your private key, they
effectively have access to your App Store Connect account.

When this command writes JSON files, an attempt is made to limit access
to the file. However, file access restrictions may not be as secure as you
want. Security conscious individuals should audit the permissions of the
file and adjust accordingly.
";

fn command_encode_app_store_connect_api_key(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let issuer_id = args
        .get_one::<String>("issuer_id")
        .expect("arg should have been required");
    let key_id = args
        .get_one::<String>("key_id")
        .expect("arg should have been required");
    let private_key_path = args
        .get_one::<PathBuf>("private_key_path")
        .expect("arg should have been required");

    let unified = UnifiedApiKey::from_ecdsa_pem_path(issuer_id, key_id, private_key_path)?;

    if let Some(output_path) = args.get_one::<PathBuf>("output_path") {
        eprintln!("writing unified key JSON to {}", output_path.display());
        unified.write_json_file(output_path)?;
        eprintln!(
            "consider auditing the file's access permissions to ensure its content remains secure"
        );
    } else {
        println!("{}", unified.to_json_string()?);
    }

    Ok(())
}

fn print_signed_data(
    prefix: &str,
    signed_data: &SignedData,
    external_content: Option<Vec<u8>>,
) -> Result<(), AppleCodesignError> {
    println!(
        "{}signed content (embedded): {:?}",
        prefix,
        signed_data.signed_content().map(hex::encode)
    );
    println!(
        "{}signed content (external): {:?}... ({} bytes)",
        prefix,
        external_content.as_ref().map(|x| hex::encode(&x[0..40])),
        external_content.as_ref().map(|x| x.len()).unwrap_or(0),
    );

    let content = if let Some(v) = signed_data.signed_content() {
        Some(v)
    } else {
        external_content.as_ref().map(|v| v.as_ref())
    };

    if let Some(content) = content {
        println!(
            "{}signed content SHA-1:   {}",
            prefix,
            hex::encode(DigestType::Sha1.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-256: {}",
            prefix,
            hex::encode(DigestType::Sha256.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-384: {}",
            prefix,
            hex::encode(DigestType::Sha384.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-512: {}",
            prefix,
            hex::encode(DigestType::Sha512.digest_data(content)?)
        );
    }
    println!(
        "{}certificate count: {}",
        prefix,
        signed_data.certificates().count()
    );
    for (i, cert) in signed_data.certificates().enumerate() {
        println!(
            "{}certificate #{}: subject CN={}; self signed={}",
            prefix,
            i,
            cert.subject_common_name()
                .unwrap_or_else(|| "<unknown>".to_string()),
            cert.subject_is_issuer()
        );
    }
    println!("{}signer count: {}", prefix, signed_data.signers().count());
    for (i, signer) in signed_data.signers().enumerate() {
        println!(
            "{}signer #{}: digest algorithm: {:?}",
            prefix,
            i,
            signer.digest_algorithm()
        );
        println!(
            "{}signer #{}: signature algorithm: {:?}",
            prefix,
            i,
            signer.signature_algorithm()
        );

        if let Some(sa) = signer.signed_attributes() {
            println!(
                "{}signer #{}: content type: {}",
                prefix,
                i,
                sa.content_type()
            );
            println!(
                "{}signer #{}: message digest: {}",
                prefix,
                i,
                hex::encode(sa.message_digest())
            );
            println!(
                "{}signer #{}: signing time: {:?}",
                prefix,
                i,
                sa.signing_time()
            );
        }

        let digested_data = signer.signed_content_with_signed_data(signed_data);

        println!(
            "{}signer #{}: signature content SHA-1:   {}",
            prefix,
            i,
            hex::encode(DigestType::Sha1.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-256: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha256.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-384: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha384.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-512: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha512.digest_data(&digested_data)?)
        );

        if signed_data.signed_content().is_some() {
            println!(
                "{}signer #{}: digest valid: {}",
                prefix,
                i,
                signer
                    .verify_message_digest_with_signed_data(signed_data)
                    .is_ok()
            );
        }
        println!(
            "{}signer #{}: signature valid: {}",
            prefix,
            i,
            signer
                .verify_signature_with_signed_data(signed_data)
                .is_ok()
        );

        println!(
            "{}signer #{}: time-stamp token present: {}",
            prefix,
            i,
            signer.time_stamp_token_signed_data()?.is_some()
        );

        if let Some(tsp_signed_data) = signer.time_stamp_token_signed_data()? {
            let prefix = format!("{prefix}signer #{i}: time-stamp token: ");

            print_signed_data(&prefix, &tsp_signed_data, None)?;
        }
    }

    Ok(())
}

fn command_extract(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let format = args
        .get_one::<String>("data")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let index = args.get_one::<String>("universal_index").unwrap();
    let index = usize::from_str(index).map_err(|_| AppleCodesignError::CliBadArgument)?;

    let data = std::fs::read(path)?;
    let mach = MachFile::parse(&data)?;
    let macho = mach.nth_macho(index)?;

    match format.as_str() {
        "blobs" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            for blob in embedded.blobs {
                let parsed = blob.into_parsed_blob()?;
                println!("{parsed:#?}");
            }
        }
        "cms-info" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(cms) = embedded.signature_data()? {
                let signed_data = SignedData::parse_ber(cms)?;

                let cd_data = if let Ok(Some(blob)) = embedded.code_directory() {
                    Some(blob.to_blob_bytes()?)
                } else {
                    None
                };

                print_signed_data("", &signed_data, cd_data)?;
            } else {
                eprintln!("no CMS data");
            }
        }
        "cms-pem" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(cms) = embedded.signature_data()? {
                print!(
                    "{}",
                    pem::encode(&pem::Pem {
                        tag: "PKCS7".to_string(),
                        contents: cms.to_vec(),
                    })
                );
            } else {
                eprintln!("no CMS data");
            }
        }
        "cms-raw" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(cms) = embedded.signature_data()? {
                std::io::stdout().write_all(cms)?;
            } else {
                eprintln!("no CMS data");
            }
        }
        "cms" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(signed_data) = embedded.signed_data()? {
                println!("{signed_data:#?}");
            } else {
                eprintln!("no CMS data");
            }
        }
        "code-directory-raw" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(blob) = embedded.find_slot(CodeSigningSlot::CodeDirectory) {
                std::io::stdout().write_all(blob.data)?;
            } else {
                eprintln!("no code directory");
            }
        }
        "code-directory-serialized-raw" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Ok(Some(cd)) = embedded.code_directory() {
                std::io::stdout().write_all(&cd.to_blob_bytes()?)?;
            } else {
                eprintln!("no code directory");
            }
        }
        "code-directory-serialized" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Ok(Some(cd)) = embedded.code_directory() {
                let serialized = cd.to_blob_bytes()?;
                println!("{:#?}", CodeDirectoryBlob::from_blob_bytes(&serialized)?);
            }
        }
        "code-directory" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(cd) = embedded.code_directory()? {
                println!("{cd:#?}");
            } else {
                eprintln!("no code directory");
            }
        }
        "linkedit-info" => {
            let sig = macho
                .find_signature_data()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
            println!("__LINKEDIT segment index: {}", sig.linkedit_segment_index);
            println!(
                "__LINKEDIT segment start offset: {}",
                sig.linkedit_segment_start_offset
            );
            println!(
                "__LINKEDIT segment end offset: {}",
                sig.linkedit_segment_end_offset
            );
            println!(
                "__LINKEDIT segment size: {}",
                sig.linkedit_segment_data.len()
            );
            println!(
                "__LINKEDIT signature global start offset: {}",
                sig.linkedit_signature_start_offset
            );
            println!(
                "__LINKEDIT signature global end offset: {}",
                sig.linkedit_signature_end_offset
            );
            println!(
                "__LINKEDIT signature local segment start offset: {}",
                sig.signature_start_offset
            );
            println!(
                "__LINKEDIT signature local segment end offset: {}",
                sig.signature_end_offset
            );
            println!("__LINKEDIT signature size: {}", sig.signature_data.len());
        }
        "linkedit-segment-raw" => {
            let sig = macho
                .find_signature_data()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
            std::io::stdout().write_all(sig.linkedit_segment_data)?;
        }
        "macho-load-commands" => {
            println!("load command count: {}", macho.macho.load_commands.len());

            for command in &macho.macho.load_commands {
                println!(
                    "{}; offsets=0x{:x}-0x{:x} ({}-{}); size={}",
                    goblin::mach::load_command::cmd_to_str(command.command.cmd()),
                    command.offset,
                    command.offset + command.command.cmdsize(),
                    command.offset,
                    command.offset + command.command.cmdsize(),
                    command.command.cmdsize(),
                );
            }
        }
        "macho-segments" => {
            println!("segments count: {}", macho.macho.segments.len());
            for (segment_index, segment) in macho.macho.segments.iter().enumerate() {
                let sections = segment.sections()?;

                println!(
                    "segment #{}; {}; offsets=0x{:x}-0x{:x}; vm/file size {}/{}; section count {}",
                    segment_index,
                    segment.name()?,
                    segment.fileoff,
                    segment.fileoff as usize + segment.data.len(),
                    segment.vmsize,
                    segment.filesize,
                    sections.len()
                );
                for (section_index, (section, _)) in sections.into_iter().enumerate() {
                    println!(
                        "segment #{}; section #{}: {}; segment offsets=0x{:x}-0x{:x} size {}",
                        segment_index,
                        section_index,
                        section.name()?,
                        section.offset,
                        section.offset as u64 + section.size,
                        section.size
                    );
                }
            }
        }
        "macho-target" => {
            if let Some(target) = macho.find_targeting()? {
                println!("Platform: {}", target.platform);
                println!("Minimum OS: {}", target.minimum_os_version);
                println!("SDK: {}", target.sdk_version);
            } else {
                println!("Unable to resolve Mach-O targeting from load commands");
            }
        }
        "requirements-raw" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(blob) = embedded.find_slot(CodeSigningSlot::RequirementSet) {
                std::io::stdout().write_all(blob.data)?;
            } else {
                eprintln!("no requirements");
            }
        }
        "requirements-rust" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(reqs) = embedded.code_requirements()? {
                for (typ, req) in &reqs.requirements {
                    for expr in req.parse_expressions()?.iter() {
                        println!("{typ} => {expr:#?}");
                    }
                }
            } else {
                eprintln!("no requirements");
            }
        }
        "requirements-serialized-raw" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(reqs) = embedded.code_requirements()? {
                std::io::stdout().write_all(&reqs.to_blob_bytes()?)?;
            } else {
                eprintln!("no requirements");
            }
        }
        "requirements-serialized" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(reqs) = embedded.code_requirements()? {
                let serialized = reqs.to_blob_bytes()?;
                println!("{:#?}", RequirementSetBlob::from_blob_bytes(&serialized)?);
            } else {
                eprintln!("no requirements");
            }
        }
        "requirements" => {
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            if let Some(reqs) = embedded.code_requirements()? {
                for (typ, req) in &reqs.requirements {
                    for expr in req.parse_expressions()?.iter() {
                        println!("{typ} => {expr}");
                    }
                }
            } else {
                eprintln!("no requirements");
            }
        }
        "signature-raw" => {
            let sig = macho
                .find_signature_data()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
            std::io::stdout().write_all(sig.signature_data)?;
        }
        "superblob" => {
            let sig = macho
                .find_signature_data()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
            let embedded = macho
                .code_signature()?
                .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

            println!("file start offset: {}", sig.linkedit_signature_start_offset);
            println!("file end offset: {}", sig.linkedit_signature_end_offset);
            println!("__LINKEDIT start offset: {}", sig.signature_start_offset);
            println!("__LINKEDIT end offset: {}", sig.signature_end_offset);
            println!("length: {}", embedded.length);
            println!("blob count: {}", embedded.count);
            println!("blobs:");
            for blob in embedded.blobs {
                println!("- index: {}", blob.index);
                println!(
                    "  offsets: 0x{:x}-0x{:x} ({}-{})",
                    blob.offset,
                    blob.offset + blob.length - 1,
                    blob.offset,
                    blob.offset + blob.length - 1
                );
                println!("  length: {}", blob.length);
                println!("  slot: {:?}", blob.slot);
                println!("  magic: {:?} (0x{:x})", blob.magic, u32::from(blob.magic));
                println!(
                    "  sha1: {}",
                    hex::encode(blob.digest_with(DigestType::Sha1)?)
                );
                println!(
                    "  sha256: {}",
                    hex::encode(blob.digest_with(DigestType::Sha256)?)
                );
                println!(
                    "  sha256-truncated: {}",
                    hex::encode(blob.digest_with(DigestType::Sha256Truncated)?)
                );
                println!(
                    "  sha384: {}",
                    hex::encode(blob.digest_with(DigestType::Sha384)?),
                );
                println!(
                    "  sha512: {}",
                    hex::encode(blob.digest_with(DigestType::Sha512)?),
                );
                println!(
                    "  sha1-base64: {}",
                    base64::encode(blob.digest_with(DigestType::Sha1)?)
                );
                println!(
                    "  sha256-base64: {}",
                    base64::encode(blob.digest_with(DigestType::Sha256)?)
                );
                println!(
                    "  sha256-truncated-base64: {}",
                    base64::encode(blob.digest_with(DigestType::Sha256Truncated)?)
                );
                println!(
                    "  sha384-base64: {}",
                    base64::encode(blob.digest_with(DigestType::Sha384)?)
                );
                println!(
                    "  sha512-base64: {}",
                    base64::encode(blob.digest_with(DigestType::Sha512)?)
                );
            }
        }
        _ => panic!("unhandled format: {format}"),
    }

    Ok(())
}

fn command_generate_certificate_signing_request(
    args: &ArgMatches,
) -> Result<(), AppleCodesignError> {
    let csr_pem_path = args.get_one::<String>("csr_pem_path").map(PathBuf::from);

    let (private_keys, _) = collect_certificates_from_args(args, true)?;

    let private_key = if private_keys.is_empty() {
        error!("no private keys found; a private key is required to sign a certificate signing request");
        return Err(AppleCodesignError::CliBadArgument);
    } else if private_keys.len() > 1 {
        error!(
            "at most 1 private key can be present (found {}); aborting",
            private_keys.len()
        );
        return Err(AppleCodesignError::CliBadArgument);
    } else {
        private_keys.into_iter().next().expect("checked size above")
    };

    let key_algorithm = private_key.key_algorithm().ok_or_else(|| {
        error!("unable to determine key algorithm of private key (please report this issue)");
        AppleCodesignError::CliBadArgument
    })?;

    let mut builder = X509CertificateBuilder::new(key_algorithm);
    builder
        .subject()
        .append_common_name_utf8_string("Apple Code Signing CSR")
        .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{e:?}")))?;

    warn!("generating CSR; you may be prompted to enter credentials to unlock the signing key");
    let pem = builder
        .create_certificate_signing_request(private_key.as_key_info_signer())?
        .encode_pem()?;

    if let Some(dest_path) = csr_pem_path {
        if let Some(parent) = dest_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        warn!("writing PEM encoded CSR to {}", dest_path.display());
        std::fs::write(&dest_path, pem.as_bytes())?;
    }

    print!("{pem}");

    Ok(())
}

fn command_generate_self_signed_certificate(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let algorithm = match args
        .get_one::<String>("algorithm")
        .ok_or(AppleCodesignError::CliBadArgument)?
        .as_str()
    {
        "ecdsa" => KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1),
        "ed25519" => KeyAlgorithm::Ed25519,
        value => panic!(
            "algorithm values should have been validated by arg parser: {value}"
        ),
    };

    let profile = args
        .get_one::<String>("profile")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let profile = CertificateProfile::from_str(profile)?;
    let team_id = args
        .get_one::<String>("team_id")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let person_name = args
        .get_one::<String>("person_name")
        .ok_or(AppleCodesignError::CliBadArgument)?;
    let country_name = args
        .get_one::<String>("country_name")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let validity_days = args.get_one::<String>("validity_days").unwrap();
    let validity_days =
        i64::from_str(validity_days).map_err(|_| AppleCodesignError::CliBadArgument)?;

    let pem_filename = args.get_one::<String>("pem_filename");

    let validity_duration = chrono::Duration::days(validity_days);

    let (cert, _, raw) = create_self_signed_code_signing_certificate(
        algorithm,
        profile,
        team_id,
        person_name,
        country_name,
        validity_duration,
    )?;

    let cert_pem = cert.encode_pem();
    let key_pem = pem::encode(&pem::Pem {
        tag: "PRIVATE KEY".to_string(),
        contents: raw.as_ref().to_vec(),
    });

    let mut wrote_file = false;

    if let Some(pem_filename) = pem_filename {
        let cert_path = PathBuf::from(format!("{pem_filename}.crt"));
        let key_path = PathBuf::from(format!("{pem_filename}.key"));

        if let Some(parent) = cert_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        println!("writing public certificate to {}", cert_path.display());
        std::fs::write(&cert_path, cert_pem.as_bytes())?;
        println!("writing private signing key to {}", key_path.display());
        std::fs::write(&key_path, key_pem.as_bytes())?;

        wrote_file = true;
    }

    if !wrote_file {
        print!("{cert_pem}");
        print!("{key_pem}");
    }

    Ok(())
}

#[cfg(target_os = "macos")]
fn command_keychain_export_certificate_chain(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let user_id = args.get_one::<String>("user_id").unwrap();

    let domain = args
        .get_one::<String>("domain")
        .expect("clap should have added default value");

    let domain = KeychainDomain::try_from(domain.as_str())
        .expect("clap should have validated domain values");

    let password = if let Some(path) = args.get_one::<String>("password_file") {
        let data = std::fs::read_to_string(path)?;

        Some(
            data.lines()
                .next()
                .expect("should get a single line")
                .to_string(),
        )
    } else if let Some(password) = args.get_one::<String>("password") {
        Some(password.to_string())
    } else {
        None
    };

    let certs = macos_keychain_find_certificate_chain(domain, password.as_deref(), user_id)?;

    for (i, cert) in certs.iter().enumerate() {
        if args.get_flag("no_print_self") && i == 0 {
            continue;
        }

        print!("{}", cert.encode_pem());
    }

    Ok(())
}

#[cfg(not(target_os = "macos"))]
fn command_keychain_export_certificate_chain(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    Err(AppleCodesignError::CliGeneralError(
        "macOS Keychain export only supported on macOS".to_string(),
    ))
}

#[cfg(target_os = "macos")]
fn command_keychain_print_certificates(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let domain = args
        .get_one::<String>("domain")
        .expect("clap should have added default value");

    let domain = KeychainDomain::try_from(domain.as_str())
        .expect("clap should have validated domain values");

    let certs = keychain_find_code_signing_certificates(domain, None)?;

    for (i, cert) in certs.into_iter().enumerate() {
        println!("# Certificate {}", i);
        println!();
        print_certificate_info(&cert)?;
        println!();
    }

    Ok(())
}

#[cfg(not(target_os = "macos"))]
fn command_keychain_print_certificates(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    Err(AppleCodesignError::CliGeneralError(
        "macOS Keychain integration supported on macOS".to_string(),
    ))
}

const NOTARIZE_ABOUT: &str = "\
Submit a notarization request to Apple.

This command is used to submit an asset to Apple for notarization. Given
a path to an asset with a code signature, this command will connect to Apple's
Notary API and upload the asset. It will then optionally wait on the submission
to finish processing (which typically takes a few dozen seconds). If the
asset validates Apple's requirements, Apple will issue a *notarization ticket*
as proof that they approved of it. This ticket is then added to the asset in a
process called *stapling*, which this command can do automatically if the
`--staple` argument is passed.

# App Store Connect API Key

In order to communicate with Apple's servers, you need an App Store Connect
API Key. This requires an Apple Developer account. You can generate an
API Key at https://appstoreconnect.apple.com/access/api.

The recommended mechanism to define the API Key is via `--api-key-path`,
which takes the path to a file containing JSON produced by the
`encode-app-store-connect-api-key` command. See that command's help for
more details.

If you don't wish to use `--api-key-path`, you can define the key components
via the `--api-issuer` and `--api-key` arguments. You will need a file named
`AuthKey_<ID>.p8` in one of the following locations: `$(pwd)/private_keys/`,
`~/private_keys/`, '~/.private_keys/`, and `~/.appstoreconnect/private_keys/`
(searched in that order). The name of the file is derived from the value of
`--api-key`.

In all cases, App Store Connect API Keys can be managed at
https://appstoreconnect.apple.com/access/api.

# Modes of Operation

By default, the `notarize` command will initiate an upload to Apple and exit
once the upload is complete.

Once an upload is performed, Apple will asynchronously process the uploaded
content. This can take seconds to minutes.

To poll Apple's servers and wait on the server-side processing to finish,
specify `--wait`. This will query the state of the processing every few seconds
until it is finished, the max wait time is reached, or an error occurs.

To automatically staple an asset after server-side processing has finished,
specify `--staple`. This implies `--wait`.
";

/// Obtain a notarization client from arguments.
fn notarizer_from_args(args: &ArgMatches) -> Result<Notarizer, AppleCodesignError> {
    let api_key_path = args.get_one::<PathBuf>("api_key_path");
    let api_issuer = args.get_one::<String>("api_issuer");
    let api_key = args.get_one::<String>("api_key");

    if let Some(api_key_path) = api_key_path {
        Notarizer::from_api_key(api_key_path)
    } else if let (Some(issuer), Some(key)) = (api_issuer, api_key) {
        Notarizer::from_api_key_id(issuer, key)
    } else {
        Err(AppleCodesignError::NotarizeNoAuthCredentials)
    }
}

fn notarizer_wait_duration(args: &ArgMatches) -> Result<std::time::Duration, AppleCodesignError> {
    let max_wait_seconds = args
        .get_one::<String>("max_wait_seconds")
        .expect("argument should have default value");
    let max_wait_seconds =
        u64::from_str(max_wait_seconds).map_err(|_| AppleCodesignError::CliBadArgument)?;

    Ok(std::time::Duration::from_secs(max_wait_seconds))
}

fn command_notary_log(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let notarizer = notarizer_from_args(args)?;
    let submission_id = args
        .get_one::<String>("submission_id")
        .expect("submission_id is required");

    let log = notarizer.fetch_notarization_log(submission_id)?;

    for line in serde_json::to_string_pretty(&log)?.lines() {
        println!("{line}");
    }

    Ok(())
}

fn command_notary_submit(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = PathBuf::from(
        args.get_one::<String>("path")
            .expect("clap should have validated arguments"),
    );
    let staple = args.get_flag("staple");
    let wait = args.get_flag("wait") || staple;

    let wait_limit = if wait {
        Some(notarizer_wait_duration(args)?)
    } else {
        None
    };
    let notarizer = notarizer_from_args(args)?;

    let upload = notarizer.notarize_path(&path, wait_limit)?;

    if staple {
        match upload {
            crate::notarization::NotarizationUpload::UploadId(_) => {
                panic!(
                    "NotarizationUpload::UploadId should not be returned if we waited successfully"
                );
            }
            crate::notarization::NotarizationUpload::NotaryResponse(_) => {
                let stapler = crate::stapling::Stapler::new()?;
                stapler.staple_path(&path)?;
            }
        }
    }

    Ok(())
}

fn command_notary_wait(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let wait_duration = notarizer_wait_duration(args)?;
    let notarizer = notarizer_from_args(args)?;
    let submission_id = args
        .get_one::<String>("submission_id")
        .expect("submission_id is required");

    notarizer.wait_on_notarization_and_fetch_log(submission_id, wait_duration)?;

    Ok(())
}

fn command_parse_code_signing_requirement(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("input_path")
        .expect("clap should have validated argument");

    let data = std::fs::read(path)?;

    let requirements = CodeRequirements::parse_blob(&data)?.0;

    for requirement in requirements.iter() {
        match args
            .get_one::<String>("format")
            .expect("clap should have validated argument")
            .as_str()
        {
            "csrl" => {
                println!("{requirement}");
            }
            "expression-tree" => {
                println!("{requirement:#?}");
            }
            format => panic!("unhandled format: {format}"),
        }
    }

    Ok(())
}

fn command_print_signature_info(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .expect("clap should have validated argument");

    let reader = SignatureReader::from_path(path)?;

    let entities = reader.entities()?;
    serde_yaml::to_writer(std::io::stdout(), &entities)?;

    Ok(())
}

fn command_remote_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let remote_url = args
        .get_one::<String>("remote_signing_url")
        .expect("remote signing URL should always be present");

    let session_join_string = if args.get_flag("session_join_string_editor") {
        let mut value = None;

        for _ in 0..3 {
            if let Some(content) = dialoguer::Editor::new()
                .require_save(true)
                .edit("# Please enter the -----BEGIN SESSION JOIN STRING---- content below.\n# Remember to save the file!")?
            {
                value = Some(content);
                break;
            }
        }

        value.ok_or_else(|| {
            AppleCodesignError::CliGeneralError("session join string not entered in editor".into())
        })?
    } else if let Some(path) = args.get_one::<String>("session_join_string_path") {
        std::fs::read_to_string(path)?
    } else if let Some(value) = args.get_one::<String>("session_join_string") {
        value.to_string()
    } else {
        return Err(AppleCodesignError::CliGeneralError(
            "session join string argument parsing failure".into(),
        ));
    };

    let mut joiner = create_session_joiner(session_join_string)?;

    if let Some(env) = args.get_one::<String>("remote_shared_secret_env") {
        let secret = std::env::var(env).map_err(|_| AppleCodesignError::CliBadArgument)?;
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    } else if let Some(secret) = args.get_one::<String>("remote_shared_secret") {
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    }

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    let private = private_keys
        .into_iter()
        .next()
        .ok_or(AppleCodesignError::NoSigningCertificate)?;

    let cert = public_certificates.remove(0);

    let certificates = if let Some(chain) = cert.apple_root_certificate_chain() {
        // The chain starts with self.
        chain.into_iter().skip(1).collect::<Vec<_>>()
    } else {
        public_certificates
    };

    joiner.register_state(SessionJoinState::PublicKeyDecrypt(
        private.to_public_key_peer_decrypt()?,
    ))?;

    let client = UnjoinedSigningClient::new_signer(
        joiner,
        private.as_key_info_signer(),
        cert,
        certificates,
        remote_url.to_string(),
    )?;
    client.run()?;

    Ok(())
}

fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut settings = SigningSettings::default();

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    if private_keys.len() > 1 {
        error!("at most 1 PRIVATE KEY can be present; aborting");
        return Err(AppleCodesignError::CliBadArgument);
    }

    let private = if private_keys.is_empty() {
        None
    } else {
        Some(&private_keys[0])
    };

    if let Some(signing_key) = &private {
        if public_certificates.is_empty() {
            error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
            return Err(AppleCodesignError::CliBadArgument);
        }

        let cert = public_certificates.remove(0);

        warn!("registering signing key");
        settings.set_signing_key(signing_key.as_key_info_signer(), cert);
        if let Some(certs) = settings.chain_apple_certificates() {
            for cert in certs {
                warn!(
                    "automatically registered Apple CA certificate: {}",
                    cert.subject_common_name()
                        .unwrap_or_else(|| "default".into())
                );
            }
        }

        if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
            if timestamp_url != "none" {
                warn!("using time-stamp protocol server {}", timestamp_url);
                settings.set_time_stamp_url(timestamp_url)?;
            }
        }
    }

    if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
        warn!(
            "automatically setting team ID from signing certificate: {}",
            team_id
        );
    }

    for cert in public_certificates {
        warn!("registering extra X.509 certificate");
        settings.chain_certificate(cert);
    }

    if let Some(team_name) = args.get_one::<String>("team_name") {
        settings.set_team_id(team_name);
    }

    if let Some(value) = args.get_one::<String>("digest") {
        let digest_type = DigestType::try_from(value.as_str())?;
        settings.set_digest_type(digest_type);
    }

    if let Some(values) = args.get_many::<String>("extra_digest") {
        for value in values {
            let (scope, digest_type) = parse_scoped_value(value)?;
            let digest_type = DigestType::try_from(digest_type)?;
            settings.add_extra_digest(scope, digest_type);
        }
    }

    if let Some(values) = args.get_many::<String>("exclude") {
        for pattern in values {
            settings.add_path_exclusion(pattern)?;
        }
    }

    if let Some(values) = args.get_many::<String>("binary_identifier") {
        for value in values {
            let (scope, identifier) = parse_scoped_value(value)?;
            settings.set_binary_identifier(scope, identifier);
        }
    }

    if let Some(values) = args.get_many::<String>("code_requirements_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            let code_requirements_data = std::fs::read(path)?;
            let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
            for expr in reqs.iter() {
                warn!(
                    "setting designated code requirements for {}: {}",
                    scope, expr
                );
                settings.set_designated_requirement_expression(scope.clone(), expr)?;
            }
        }
    }

    if let Some(values) = args.get_many::<String>("code_resources") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!(
                "setting code resources data for {} from path {}",
                scope, path
            );
            let code_resources_data = std::fs::read(path)?;
            settings.set_code_resources_data(scope, code_resources_data);
        }
    }

    if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let flags = CodeSignatureFlags::from_str(value)?;
            settings.set_code_signature_flags(scope, flags);
        }
    }

    if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!("setting entitlments XML for {} from path {}", scope, path);
            let entitlements_data = std::fs::read_to_string(path)?;
            settings.set_entitlements_xml(scope, entitlements_data)?;
        }
    }

    if let Some(values) = args.get_many::<String>("runtime_version") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let version = semver::Version::parse(value)?;
            settings.set_runtime_version(scope, version);
        }
    }

    if let Some(values) = args.get_many::<String>("info_plist_path") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let content = std::fs::read(value)?;
            settings.set_info_plist_data(scope, content);
        }
    }

    let input_path = PathBuf::from(
        args.get_one::<String>("input_path")
            .expect("input_path presence should have been validated by clap"),
    );
    let output_path = args.get_one::<String>("output_path");

    let signer = UnifiedSigner::new(settings);

    if let Some(output_path) = output_path {
        warn!("signing {} to {}", input_path.display(), output_path);
        signer.sign_path(input_path, output_path)?;
    } else {
        warn!("signing {} in place", input_path.display());
        signer.sign_path_in_place(input_path)?;
    }

    if let Some(private) = &private {
        private.finish()?;
    }

    Ok(())
}

#[cfg(feature = "yubikey")]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut ctx = ::yubikey::reader::Context::open()?;
    for (index, reader) in ctx.iter()?.enumerate() {
        println!("Device {}: {}", index, reader.name());

        if let Ok(yk) = reader.open() {
            let mut yk = crate::yubikey::YubiKey::from(yk);
            println!("Device {}: Serial: {}", index, yk.inner()?.serial());
            println!("Device {}: Version: {}", index, yk.inner()?.version());

            for (slot, cert) in yk.find_certificates()? {
                println!(
                    "Device {}: Certificate in slot {:?} / {}",
                    index,
                    slot,
                    hex::encode([u8::from(slot)])
                );
                print_certificate_info(&cert)?;
                println!();
            }
        }
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard reading requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_generate_key(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;

    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    yk.generate_key(slot_id, touch_policy, pin_policy)?;

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_generate_key(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard integration requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_import(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let (keys, certs) = collect_certificates_from_args(args, false)?;

    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;
    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;
    let use_existing_key = args.get_flag("existing_key");

    println!(
        "found {} private keys and {} public certificates",
        keys.len(),
        certs.len()
    );

    let key = if use_existing_key {
        println!("using existing private key in smartcard");

        if !keys.is_empty() {
            println!(
                "ignoring {} private keys specified via arguments",
                keys.len()
            );
        }

        None
    } else {
        Some(keys.into_iter().next().ok_or_else(|| {
            println!("no private key found");
            AppleCodesignError::CliBadArgument
        })?)
    };

    let cert = certs.into_iter().next().ok_or_else(|| {
        println!("no public certificates found");
        AppleCodesignError::CliBadArgument
    })?;

    println!(
        "Will import the following certificate into slot {}",
        hex::encode([u8::from(slot_id)])
    );
    print_certificate_info(&cert)?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    if args.get_flag("dry_run") {
        println!("dry run mode enabled; stopping");
        return Ok(());
    }

    if let Some(key) = key {
        yk.import_key(
            slot_id,
            key.as_key_info_signer(),
            &cert,
            touch_policy,
            pin_policy,
        )?;
    } else {
        yk.import_certificate(slot_id, &cert)?;
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_import(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard import requires `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

fn command_staple(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let stapler = crate::stapling::Stapler::new()?;
    stapler.staple_path(path)?;

    Ok(())
}

fn command_verify(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let data = std::fs::read(path)?;

    let problems = crate::verify::verify_macho_data(data);

    for problem in &problems {
        println!("{problem}");
    }

    if problems.is_empty() {
        eprintln!("no problems detected!");
        eprintln!("(we do not verify everything so please do not assume that the signature meets Apple standards)");
        Ok(())
    } else {
        Err(AppleCodesignError::VerificationProblems)
    }
}

fn command_x509_oids(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    println!("# Extended Key Usage (EKU) Extension OIDs");
    println!();
    for ekup in crate::certificate::ExtendedKeyUsagePurpose::all() {
        println!("{}\t{:?}", ekup.as_oid(), ekup);
    }
    println!();
    println!("# Code Signing Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CodeSigningCertificateExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }
    println!();
    println!("# Certificate Authority Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CertificateAuthorityExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }

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