pub struct MachOBinary<'a> {
    pub index: Option<usize>,
    pub macho: MachO<'a>,
    pub data: &'a [u8],
}
Expand description

A Mach-O binary.

Fields§

§index: Option<usize>

Index within a fat binary this Mach-O resides at.

If None, this is not inside a fat binary.

§macho: MachO<'a>

The parsed Mach-O binary.

§data: &'a [u8]

The raw data backing the Mach-O binary.

Implementations§

Parse a non-universal Mach-O binary from raw data.

Examples found in repository?
src/macho_signing.rs (line 319)
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    pub fn write_signed_binary(
        &self,
        settings: &SigningSettings,
        writer: &mut impl Write,
    ) -> Result<(), AppleCodesignError> {
        // Implementing a true streaming writer requires calculating final sizes
        // of all binaries so fat header offsets and sizes can be written first. We take
        // the easy road and buffer individual Mach-O binaries internally.

        let binaries = self
            .machos
            .iter()
            .enumerate()
            .map(|(index, original_macho)| {
                info!("signing Mach-O binary at index {}", index);
                let settings =
                    settings.as_nested_macho_settings(index, original_macho.macho.header.cputype());

                let signature_len = original_macho.estimate_embedded_signature_size(&settings)?;

                // Derive an intermediate Mach-O with placeholder NULLs for signature
                // data so Code Directory digests over the load commands are correct.
                let placeholder_signature_data = b"\0".repeat(signature_len);

                let intermediate_macho_data =
                    create_macho_with_signature(original_macho, &placeholder_signature_data)?;

                // A nice side-effect of this is that it catches bugs if we write malformed Mach-O!
                let intermediate_macho = MachOBinary::parse(&intermediate_macho_data)?;

                let mut signature_data = self.create_superblob(&settings, &intermediate_macho)?;
                info!("total signature size: {} bytes", signature_data.len());

                // The Mach-O writer adjusts load commands based on the signature length. So pad
                // with NULLs to get to our placeholder length.
                match signature_data.len().cmp(&placeholder_signature_data.len()) {
                    Ordering::Greater => {
                        return Err(AppleCodesignError::SignatureDataTooLarge);
                    }
                    Ordering::Equal => {}
                    Ordering::Less => {
                        signature_data.extend_from_slice(
                            &b"\0".repeat(placeholder_signature_data.len() - signature_data.len()),
                        );
                    }
                }

                create_macho_with_signature(&intermediate_macho, &signature_data)
            })
            .collect::<Result<Vec<_>, AppleCodesignError>>()?;

        if binaries.len() > 1 {
            create_universal_macho(writer, binaries.iter().map(|x| x.as_slice()))?;
        } else {
            writer.write_all(&binaries[0])?;
        }

        Ok(())
    }

Attempt to extract a reference to raw signature data in a Mach-O binary.

An LC_CODE_SIGNATURE load command in the Mach-O file header points to signature data in the __LINKEDIT segment.

This function is used as part of parsing signature data. You probably want to use a function that parses referenced data.

Examples found in repository?
src/macho.rs (line 132)
131
132
133
134
135
136
137
138
139
    pub fn code_signature(&self) -> Result<Option<EmbeddedSignature>, AppleCodesignError> {
        if let Some(signature) = self.find_signature_data()? {
            Ok(Some(EmbeddedSignature::from_bytes(
                signature.signature_data,
            )?))
        } else {
            Ok(None)
        }
    }
More examples
Hide additional examples
src/reader.rs (line 891)
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
    fn resolve_macho_entity(macho: MachOBinary) -> Result<MachOEntity, AppleCodesignError> {
        let mut entity = MachOEntity::default();

        if let Some(sig) = macho.find_signature_data()? {
            entity.linkedit_segment_file_start_offset = Some(sig.linkedit_segment_start_offset);
            entity.linkedit_segment_file_end_offset = Some(sig.linkedit_segment_end_offset);
            entity.signature_file_start_offset = Some(sig.linkedit_signature_start_offset);
            entity.signature_file_end_offset = Some(sig.linkedit_signature_end_offset);
            entity.signature_linkedit_start_offset = Some(sig.signature_start_offset);
            entity.signature_linkedit_end_offset = Some(sig.signature_end_offset);
        }

        if let Some(sig) = macho.code_signature()? {
            entity.signature = Some(sig.try_into()?);
        }

        Ok(entity)
    }
src/verify.rs (line 254)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
fn verify_macho_internal(
    macho: &MachOBinary,
    context: VerificationContext,
) -> Vec<VerificationProblem> {
    let signature_data = match macho.find_signature_data() {
        Ok(Some(data)) => data,
        Ok(None) => {
            return vec![VerificationProblem {
                context,
                problem: VerificationProblemType::NoMachOSignatureData,
            }];
        }
        Err(e) => {
            return vec![VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            }];
        }
    };

    let mut problems = vec![];

    // __LINKEDIT segment should be the last segment.
    if signature_data.linkedit_segment_index != macho.macho.segments.len() - 1 {
        problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::LinkeditNotLastSegment,
        });
    }

    // Signature data should be the last data in the __LINKEDIT segment.
    if signature_data.signature_end_offset != signature_data.linkedit_segment_data.len() {
        problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::SignatureNotLastLinkeditData,
        });
    }

    let signature = match macho.code_signature() {
        Ok(Some(signature)) => signature,
        Ok(None) => {
            panic!("no signature should have been handled above");
        }
        Err(e) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            });

            // Can't do anything more if we couldn't parse the signature data.
            return problems;
        }
    };

    match signature.signature_data() {
        Ok(Some(cms_blob)) => {
            problems.extend(verify_cms_signature(cms_blob, context.clone()));
        }
        Ok(None) => problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::NoCryptographicSignature,
        }),
        Err(e) => {
            problems.push(VerificationProblem {
                context: context.clone(),
                problem: VerificationProblemType::MachOSignatureError(e),
            });
        }
    }

    match signature.code_directory() {
        Ok(Some(cd)) => {
            problems.extend(verify_code_directory(macho, &signature, &cd, context));
        }
        Ok(None) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::NoCodeDirectory,
            });
        }
        Err(e) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            });
        }
    }

    problems
}
src/cli.rs (line 1413)
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
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(())
}

Obtain the code signature in the entity.

Returns Ok(None) if no signature exists, Ok(Some) if it does, or Err if there is a parse error.

Examples found in repository?
src/reader.rs (line 900)
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
    fn resolve_macho_entity(macho: MachOBinary) -> Result<MachOEntity, AppleCodesignError> {
        let mut entity = MachOEntity::default();

        if let Some(sig) = macho.find_signature_data()? {
            entity.linkedit_segment_file_start_offset = Some(sig.linkedit_segment_start_offset);
            entity.linkedit_segment_file_end_offset = Some(sig.linkedit_segment_end_offset);
            entity.signature_file_start_offset = Some(sig.linkedit_signature_start_offset);
            entity.signature_file_end_offset = Some(sig.linkedit_signature_end_offset);
            entity.signature_linkedit_start_offset = Some(sig.signature_start_offset);
            entity.signature_linkedit_end_offset = Some(sig.signature_end_offset);
        }

        if let Some(sig) = macho.code_signature()? {
            entity.signature = Some(sig.try_into()?);
        }

        Ok(entity)
    }
More examples
Hide additional examples
src/bundle_signing.rs (line 177)
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    pub fn parse_data(data: &[u8]) -> Result<Self, AppleCodesignError> {
        // Initial Mach-O's signature data is used.
        let mach = MachFile::parse(data)?;
        let macho = mach.nth_macho(0)?;

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

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

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

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

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

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

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

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

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

        Ok(SignedMachOInfo {
            code_directory_blob,
            designated_code_requirement,
        })
    }
src/verify.rs (line 288)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
fn verify_macho_internal(
    macho: &MachOBinary,
    context: VerificationContext,
) -> Vec<VerificationProblem> {
    let signature_data = match macho.find_signature_data() {
        Ok(Some(data)) => data,
        Ok(None) => {
            return vec![VerificationProblem {
                context,
                problem: VerificationProblemType::NoMachOSignatureData,
            }];
        }
        Err(e) => {
            return vec![VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            }];
        }
    };

    let mut problems = vec![];

    // __LINKEDIT segment should be the last segment.
    if signature_data.linkedit_segment_index != macho.macho.segments.len() - 1 {
        problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::LinkeditNotLastSegment,
        });
    }

    // Signature data should be the last data in the __LINKEDIT segment.
    if signature_data.signature_end_offset != signature_data.linkedit_segment_data.len() {
        problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::SignatureNotLastLinkeditData,
        });
    }

    let signature = match macho.code_signature() {
        Ok(Some(signature)) => signature,
        Ok(None) => {
            panic!("no signature should have been handled above");
        }
        Err(e) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            });

            // Can't do anything more if we couldn't parse the signature data.
            return problems;
        }
    };

    match signature.signature_data() {
        Ok(Some(cms_blob)) => {
            problems.extend(verify_cms_signature(cms_blob, context.clone()));
        }
        Ok(None) => problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::NoCryptographicSignature,
        }),
        Err(e) => {
            problems.push(VerificationProblem {
                context: context.clone(),
                problem: VerificationProblemType::MachOSignatureError(e),
            });
        }
    }

    match signature.code_directory() {
        Ok(Some(cd)) => {
            problems.extend(verify_code_directory(macho, &signature, &cd, context));
        }
        Ok(None) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::NoCodeDirectory,
            });
        }
        Err(e) => {
            problems.push(VerificationProblem {
                context,
                problem: VerificationProblemType::MachOSignatureError(e),
            });
        }
    }

    problems
}
src/signing_settings.rs (line 793)
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
    pub fn import_settings_from_macho(&mut self, data: &[u8]) -> Result<(), AppleCodesignError> {
        info!("inferring default signing settings from Mach-O binary");

        for macho in MachFile::parse(data)?.into_iter() {
            let index = macho.index.unwrap_or(0);

            let scope_main = SettingsScope::Main;
            let scope_index = SettingsScope::MultiArchIndex(index);
            let scope_arch = SettingsScope::MultiArchCpuType(macho.macho.header.cputype());

            // Older operating system versions don't have support for SHA-256 in
            // signatures. If the minimum version targeting in the binary doesn't
            // support SHA-256, we automatically change the digest targeting settings
            // so the binary will be signed correctly.
            if let Some(targeting) = macho.find_targeting()? {
                let sha256_version = targeting.platform.sha256_digest_support()?;

                if !sha256_version.matches(&targeting.minimum_os_version) {
                    info!(
                        "activating SHA-1 digests because minimum OS target {} is not {}",
                        targeting.minimum_os_version, sha256_version
                    );

                    // This logic is a bit wonky. We want SHA-1 to be present on all binaries
                    // within a fat binary. So if we need SHA-1 mode, we set the setting on the
                    // main scope and then clear any overrides on fat binary scopes so our
                    // settings are canonical.
                    self.set_digest_type(DigestType::Sha1);
                    self.add_extra_digest(scope_main.clone(), DigestType::Sha256);
                    self.extra_digests.remove(&scope_arch);
                    self.extra_digests.remove(&scope_index);
                }
            }

            // The Mach-O can have embedded Info.plist data. Use it if available and not
            // already defined in settings.
            if let Some(info_plist) = macho.embedded_info_plist()? {
                if self.info_plist_data(&scope_main).is_some()
                    || self.info_plist_data(&scope_index).is_some()
                    || self.info_plist_data(&scope_arch).is_some()
                {
                    info!("using Info.plist data from settings");
                } else {
                    info!("preserving Info.plist data already present in Mach-O");
                    self.set_info_plist_data(scope_index.clone(), info_plist);
                }
            }

            if let Some(sig) = macho.code_signature()? {
                if let Some(cd) = sig.code_directory()? {
                    if self.binary_identifier(&scope_main).is_some()
                        || self.binary_identifier(&scope_index).is_some()
                        || self.binary_identifier(&scope_arch).is_some()
                    {
                        info!("using binary identifier from settings");
                    } else {
                        info!("preserving existing binary identifier in Mach-O");
                        self.set_binary_identifier(scope_index.clone(), cd.ident);
                    }

                    if self.team_id.contains_key(&scope_main)
                        || self.team_id.contains_key(&scope_index)
                        || self.team_id.contains_key(&scope_arch)
                    {
                        info!("using team ID from settings");
                    } else if let Some(team_id) = cd.team_name {
                        info!("preserving team ID in existing Mach-O signature");
                        self.team_id
                            .insert(scope_index.clone(), team_id.to_string());
                    }

                    if self.code_signature_flags(&scope_main).is_some()
                        || self.code_signature_flags(&scope_index).is_some()
                        || self.code_signature_flags(&scope_arch).is_some()
                    {
                        info!("using code signature flags from settings");
                    } else if !cd.flags.is_empty() {
                        info!("preserving code signature flags in existing Mach-O signature");
                        self.set_code_signature_flags(scope_index.clone(), cd.flags);
                    }

                    if self.runtime_version(&scope_main).is_some()
                        || self.runtime_version(&scope_index).is_some()
                        || self.runtime_version(&scope_arch).is_some()
                    {
                        info!("using runtime version from settings");
                    } else if let Some(version) = cd.runtime {
                        info!("preserving runtime version in existing Mach-O signature");
                        self.set_runtime_version(
                            scope_index.clone(),
                            parse_version_nibbles(version),
                        );
                    }
                }

                if let Some(entitlements) = sig.entitlements()? {
                    if self.entitlements_plist(&scope_main).is_some()
                        || self.entitlements_plist(&scope_index).is_some()
                        || self.entitlements_plist(&scope_arch).is_some()
                    {
                        info!("using entitlements from settings");
                    } else {
                        info!("preserving existing entitlements in Mach-O");
                        self.set_entitlements_xml(
                            SettingsScope::MultiArchIndex(index),
                            entitlements.as_str(),
                        )?;
                    }
                }
            }
        }

        Ok(())
    }
src/cli.rs (line 1302)
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
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(())
}

Determine the start and end offset of the executable segment of a binary.

Examples found in repository?
src/macho_signing.rs (line 462)
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

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

        let mut flags = CodeSignatureFlags::empty();

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

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

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

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

        let platform = 0;
        let page_size = 4096u32;

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

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

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

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

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

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

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

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

        let mut special_hashes = HashMap::new();

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

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

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

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

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

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

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

        Ok(cd)
    }

Whether this is an executable Mach-O file.

Examples found in repository?
src/macho_signing.rs (line 366)
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
    pub fn create_superblob(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<Vec<u8>, AppleCodesignError> {
        let mut builder = EmbeddedSignatureBuilder::default();

        for (slot, blob) in self.create_special_blobs(settings, macho.is_executable())? {
            builder.add_blob(slot, blob)?;
        }

        let code_directory = self.create_code_directory(settings, macho)?;
        info!("code directory version: {}", code_directory.version);

        builder.add_code_directory(CodeSigningSlot::CodeDirectory, code_directory)?;

        if let Some(digests) = settings.extra_digests(SettingsScope::Main) {
            for digest_type in digests {
                // Since everything consults settings for the digest to use, just make a new settings
                // with a different digest.
                let mut alt_settings = settings.clone();
                alt_settings.set_digest_type(*digest_type);

                info!(
                    "adding alternative code directory using digest {:?}",
                    digest_type
                );
                let cd = self.create_code_directory(&alt_settings, macho)?;

                builder.add_alternative_code_directory(cd)?;
            }
        }

        if let Some((signing_key, signing_cert)) = settings.signing_key() {
            builder.create_cms_signature(
                signing_key,
                signing_cert,
                settings.time_stamp_url(),
                settings.certificate_chain().iter().cloned(),
            )?;
        }

        builder.create_superblob()
    }

    /// Create the `CodeDirectory` for the current configuration.
    ///
    /// This takes an explicit Mach-O to operate on due to a circular dependency
    /// between writing out the Mach-O and digesting its content. See the note
    /// in [MachOSigner] for details.
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

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

        let mut flags = CodeSignatureFlags::empty();

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

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

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

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

        let platform = 0;
        let page_size = 4096u32;

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

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

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

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

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

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

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

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

        let mut special_hashes = HashMap::new();

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

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

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

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

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

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

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

        Ok(cd)
    }

The start offset of the code signature data within the __LINKEDIT segment.

Examples found in repository?
src/macho.rs (line 175)
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
    pub fn code_signature_linkedit_end_offset(&self) -> Option<u32> {
        let start_offset = self.code_signature_linkedit_start_offset()?;

        self.code_signature_load_command()
            .map(|command| start_offset + command.datasize)
    }

    /// Obtain Mach-O segments by file offset order.
    ///
    /// The header-defined order may vary by the file layout order. This ensures the ordering
    /// is by file layout.
    pub fn segments_by_file_offset(&self) -> Vec<&Segment<'a>> {
        let mut segments = self.macho.segments.iter().collect::<Vec<_>>();

        segments.sort_by(|a, b| a.fileoff.cmp(&b.fileoff));

        segments
    }

    /// The byte offset within the binary at which point "code" stops.
    ///
    /// If a signature is present, this is the offset of the start of the
    /// signature. Else it represents the end of the binary.
    pub fn code_limit_binary_offset(&self) -> Result<u64, AppleCodesignError> {
        let last_segment = self
            .segments_by_file_offset()
            .last()
            .copied()
            .ok_or(AppleCodesignError::MissingLinkedit)?;

        if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
            return Err(AppleCodesignError::LinkeditNotLast);
        }

        if let Some(offset) = self.code_signature_linkedit_start_offset() {
            Ok(last_segment.fileoff + offset as u64)
        } else {
            Ok(last_segment.fileoff + last_segment.data.len() as u64)
        }
    }

    /// Obtain __LINKEDIT segment data before the signature data.
    ///
    /// If there is no signature, returns all the data for the __LINKEDIT segment.
    pub fn linkedit_data_before_signature(&self) -> Option<&[u8]> {
        let segment = self
            .macho
            .segments
            .iter()
            .find(|segment| matches!(segment.name(), Ok(SEG_LINKEDIT)));

        if let Some(segment) = segment {
            if let Some(offset) = self.code_signature_linkedit_start_offset() {
                Some(&segment.data[0..offset as usize])
            } else {
                Some(segment.data)
            }
        } else {
            None
        }
    }

The end offset of the code signature data within the __LINKEDIT segment.

Examples found in repository?
src/macho.rs (line 339)
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
    pub fn check_signing_capability(&self) -> Result<(), AppleCodesignError> {
        let last_segment = self
            .segments_by_file_offset()
            .last()
            .copied()
            .ok_or(AppleCodesignError::MissingLinkedit)?;

        // Last segment needs to be __LINKEDIT so we don't have to write offsets.
        if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
            return Err(AppleCodesignError::LinkeditNotLast);
        }

        // Rules:
        //
        // 1. If there is an existing signature, there must be no data in
        //    the binary after it. (We don't know how to update references to
        //    other data to reflect offset changes.)
        // 2. If there isn't an existing signature, there must be "room" between
        //    the last load command and the first section to write a new load
        //    command for the signature.

        if let Some(offset) = self.code_signature_linkedit_end_offset() {
            if offset as usize == last_segment.data.len() {
                Ok(())
            } else {
                Err(AppleCodesignError::DataAfterSignature)
            }
        } else {
            let last_load_command = self
                .macho
                .load_commands
                .iter()
                .last()
                .ok_or_else(|| AppleCodesignError::InvalidBinary("no load commands".into()))?;

            let first_section = self
                .macho
                .segments
                .iter()
                .map(|segment| segment.sections())
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .flatten()
                .next()
                .ok_or_else(|| AppleCodesignError::InvalidBinary("no sections".into()))?;

            let load_commands_end_offset =
                last_load_command.offset + last_load_command.command.cmdsize();

            if first_section.0.offset as usize - load_commands_end_offset
                >= SIZEOF_LINKEDIT_DATA_COMMAND
            {
                Ok(())
            } else {
                Err(AppleCodesignError::LoadCommandNoRoom)
            }
        }
    }

Obtain Mach-O segments by file offset order.

The header-defined order may vary by the file layout order. This ensures the ordering is by file layout.

Examples found in repository?
src/macho.rs (line 199)
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    pub fn code_limit_binary_offset(&self) -> Result<u64, AppleCodesignError> {
        let last_segment = self
            .segments_by_file_offset()
            .last()
            .copied()
            .ok_or(AppleCodesignError::MissingLinkedit)?;

        if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
            return Err(AppleCodesignError::LinkeditNotLast);
        }

        if let Some(offset) = self.code_signature_linkedit_start_offset() {
            Ok(last_segment.fileoff + offset as u64)
        } else {
            Ok(last_segment.fileoff + last_segment.data.len() as u64)
        }
    }

    /// Obtain __LINKEDIT segment data before the signature data.
    ///
    /// If there is no signature, returns all the data for the __LINKEDIT segment.
    pub fn linkedit_data_before_signature(&self) -> Option<&[u8]> {
        let segment = self
            .macho
            .segments
            .iter()
            .find(|segment| matches!(segment.name(), Ok(SEG_LINKEDIT)));

        if let Some(segment) = segment {
            if let Some(offset) = self.code_signature_linkedit_start_offset() {
                Some(&segment.data[0..offset as usize])
            } else {
                Some(segment.data)
            }
        } else {
            None
        }
    }

    /// Obtain Mach-O binary data to be digested in code digests.
    ///
    /// Returns the raw data whose digests will be captured by the Code Directory code digests.
    pub fn digested_code_data(&self) -> Result<&[u8], AppleCodesignError> {
        let code_limit = self.code_limit_binary_offset()?;

        Ok(&self.data[0..code_limit as _])
    }

    /// Obtain the size in bytes of all code digests given a digest type and page size.
    pub fn code_digests_size(
        &self,
        digest: DigestType,
        page_size: usize,
    ) -> Result<usize, AppleCodesignError> {
        let empty = digest.digest_data(b"")?;

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

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

        // Premature parallelism can be slower due to overhead of having to spin up threads.
        // So only do parallel digests if we have enough data to warrant it.
        if data.len() > 64 * 1024 * 1024 {
            data.par_chunks(page_size)
                .map(|c| digest.digest_data(c))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        } else {
            self.digested_code_data()?
                .chunks(page_size)
                .map(|chunk| digest.digest_data(chunk))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        }
    }

    /// Resolve the load command for the code signature.
    pub fn code_signature_load_command(&self) -> Option<LinkeditDataCommand> {
        self.macho.load_commands.iter().find_map(|lc| {
            if let CommandVariant::CodeSignature(command) = lc.command {
                Some(command)
            } else {
                None
            }
        })
    }

    /// Attempt to locate embedded Info.plist data.
    pub fn embedded_info_plist(&self) -> Result<Option<Vec<u8>>, AppleCodesignError> {
        // Mach-O binaries can have the Info.plist data in an `__info_plist` section
        // within the __TEXT segment.
        for segment in &self.macho.segments {
            if matches!(segment.name(), Ok(SEG_TEXT)) {
                for (section, data) in segment.sections()? {
                    if matches!(section.name(), Ok("__info_plist")) {
                        return Ok(Some(data.to_vec()));
                    }
                }
            }
        }

        Ok(None)
    }

    /// Determines whether this crate is capable of signing a given Mach-O binary.
    ///
    /// Code in this crate is limited in the amount of Mach-O binary manipulation
    /// it can perform (supporting rewriting all valid Mach-O binaries effectively
    /// requires low-level awareness of all Mach-O constructs in order to perform
    /// offset manipulation). This function can be used to test signing
    /// compatibility.
    ///
    /// We currently only support signing Mach-O files already containing an
    /// embedded signature. Often linked binaries automatically contain an embedded
    /// signature containing just the code directory (without a cryptographically
    /// signed signature), so this limitation hopefully isn't impactful.
    pub fn check_signing_capability(&self) -> Result<(), AppleCodesignError> {
        let last_segment = self
            .segments_by_file_offset()
            .last()
            .copied()
            .ok_or(AppleCodesignError::MissingLinkedit)?;

        // Last segment needs to be __LINKEDIT so we don't have to write offsets.
        if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
            return Err(AppleCodesignError::LinkeditNotLast);
        }

        // Rules:
        //
        // 1. If there is an existing signature, there must be no data in
        //    the binary after it. (We don't know how to update references to
        //    other data to reflect offset changes.)
        // 2. If there isn't an existing signature, there must be "room" between
        //    the last load command and the first section to write a new load
        //    command for the signature.

        if let Some(offset) = self.code_signature_linkedit_end_offset() {
            if offset as usize == last_segment.data.len() {
                Ok(())
            } else {
                Err(AppleCodesignError::DataAfterSignature)
            }
        } else {
            let last_load_command = self
                .macho
                .load_commands
                .iter()
                .last()
                .ok_or_else(|| AppleCodesignError::InvalidBinary("no load commands".into()))?;

            let first_section = self
                .macho
                .segments
                .iter()
                .map(|segment| segment.sections())
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .flatten()
                .next()
                .ok_or_else(|| AppleCodesignError::InvalidBinary("no sections".into()))?;

            let load_commands_end_offset =
                last_load_command.offset + last_load_command.command.cmdsize();

            if first_section.0.offset as usize - load_commands_end_offset
                >= SIZEOF_LINKEDIT_DATA_COMMAND
            {
                Ok(())
            } else {
                Err(AppleCodesignError::LoadCommandNoRoom)
            }
        }
    }
More examples
Hide additional examples
src/macho_signing.rs (line 163)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
fn create_macho_with_signature(
    macho: &MachOBinary,
    signature_data: &[u8],
) -> Result<Vec<u8>, AppleCodesignError> {
    // This should have already been called. But we do it again out of paranoia.
    macho.check_signing_capability()?;

    // The assumption made by checking_signing_capability() is that signature data
    // is at the end of the __LINKEDIT segment. So the replacement segment is the
    // existing segment truncated at the signature start followed by the new signature
    // data.
    let new_linkedit_segment_size = macho
        .linkedit_data_before_signature()
        .ok_or(AppleCodesignError::MissingLinkedit)?
        .len()
        + signature_data.len();

    // `codesign` rounds up the segment's vmsize to the nearest 16kb boundary.
    // We emulate that behavior.
    let remainder = new_linkedit_segment_size % 16384;
    let new_linkedit_segment_vmsize = if remainder == 0 {
        new_linkedit_segment_size
    } else {
        new_linkedit_segment_size + 16384 - remainder
    };

    assert!(new_linkedit_segment_vmsize >= new_linkedit_segment_size);
    assert_eq!(new_linkedit_segment_vmsize % 16384, 0);

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

    // Mach-O data structures are variable endian. So use the endian defined
    // by the magic when writing.
    let ctx = parse_magic_and_ctx(macho.data, 0)?
        .1
        .expect("context should have been parsed before");

    // If there isn't a code signature presently, we'll need to introduce a load
    // command for it.
    let mut header = macho.macho.header;
    if macho.code_signature_load_command().is_none() {
        header.ncmds += 1;
        header.sizeofcmds += SIZEOF_LINKEDIT_DATA_COMMAND as u32;
    }

    cursor.iowrite_with(header, ctx)?;

    // Following the header are load commands. We need to update load commands
    // to reflect changes to the signature size and __LINKEDIT segment size.

    let mut seen_signature_load_command = false;

    for load_command in &macho.macho.load_commands {
        let original_command_data =
            &macho.data[load_command.offset..load_command.offset + load_command.command.cmdsize()];

        let written_len = match &load_command.command {
            CommandVariant::CodeSignature(command) => {
                seen_signature_load_command = true;

                let mut command = *command;
                command.datasize = signature_data.len() as _;

                cursor.iowrite_with(command, ctx.le)?;

                LinkeditDataCommand::size_with(&ctx.le)
            }
            CommandVariant::Segment32(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand32::size_with(&ctx.le)
            }
            CommandVariant::Segment64(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand64::size_with(&ctx.le)
            }
            _ => {
                // Reflect the original bytes.
                cursor.write_all(original_command_data)?;
                original_command_data.len()
            }
        };

        // For the commands we mutated ourselves, there may be more data after the
        // load command header. Write it out if present.
        cursor.write_all(&original_command_data[written_len..])?;
    }

    // If we didn't see a signature load command, write one out now.
    if !seen_signature_load_command {
        let command = LinkeditDataCommand {
            cmd: LC_CODE_SIGNATURE,
            cmdsize: SIZEOF_LINKEDIT_DATA_COMMAND as _,
            dataoff: macho.code_limit_binary_offset()? as _,
            datasize: signature_data.len() as _,
        };

        cursor.iowrite_with(command, ctx.le)?;
    }

    // Write out segments, updating the __LINKEDIT segment when we encounter it.
    for segment in macho.segments_by_file_offset() {
        // The initial __PAGEZERO segment contains no data (it is the magic and load
        // commands) and overlaps with the __TEXT segment, which has .fileoff =0, so
        // we ignore it.
        if matches!(segment.name(), Ok(SEG_PAGEZERO)) {
            continue;
        }

        match cursor.position().cmp(&segment.fileoff) {
            // Mach-O segments may have padding between them. In this case, copy these
            // bytes (presumably NULLs but that isn't guaranteed) to the output.
            Ordering::Less => {
                let padding = &macho.data[cursor.position() as usize..segment.fileoff as usize];
                debug!(
                    "copying {} bytes outside segment boundaries before segment {}",
                    padding.len(),
                    segment.name().unwrap_or("<unknown>")
                );
                cursor.write_all(padding)?;
            }
            // The __TEXT segment usually has .fileoff = 0, which has it overlapping with
            // already written data. Allow this special case through.
            Ordering::Greater if segment.fileoff == 0 => {}

            // The writer has overran into this segment. That means we screwed up on a
            // previous loop iteration.
            Ordering::Greater => {
                return Err(AppleCodesignError::MachOWrite(format!(
                    "Mach-O segment corruption: cursor at 0x{:x} but segment begins at 0x{:x} (please report this bug)",
                    cursor.position(),
                    segment.fileoff
                )));
            }
            Ordering::Equal => {}
        }

        assert!(segment.fileoff == 0 || segment.fileoff == cursor.position());

        match segment.name() {
            Ok(SEG_LINKEDIT) => {
                cursor.write_all(
                    macho
                        .linkedit_data_before_signature()
                        .expect("__LINKEDIT segment data should resolve"),
                )?;
                cursor.write_all(signature_data)?;
            }
            _ => {
                // At least the __TEXT segment has .fileoff = 0, which has it
                // overlapping with already written data. So only write segment
                // data new to the writer.
                if segment.fileoff < cursor.position() {
                    if segment.data.is_empty() {
                        continue;
                    }
                    let remaining =
                        &segment.data[cursor.position() as usize..segment.filesize as usize];
                    cursor.write_all(remaining)?;
                } else {
                    cursor.write_all(segment.data)?;
                }
            }
        }
    }

    Ok(cursor.into_inner())
}

The byte offset within the binary at which point “code” stops.

If a signature is present, this is the offset of the start of the signature. Else it represents the end of the binary.

Examples found in repository?
src/macho.rs (line 240)
239
240
241
242
243
    pub fn digested_code_data(&self) -> Result<&[u8], AppleCodesignError> {
        let code_limit = self.code_limit_binary_offset()?;

        Ok(&self.data[0..code_limit as _])
    }
More examples
Hide additional examples
src/macho_signing.rs (line 155)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
fn create_macho_with_signature(
    macho: &MachOBinary,
    signature_data: &[u8],
) -> Result<Vec<u8>, AppleCodesignError> {
    // This should have already been called. But we do it again out of paranoia.
    macho.check_signing_capability()?;

    // The assumption made by checking_signing_capability() is that signature data
    // is at the end of the __LINKEDIT segment. So the replacement segment is the
    // existing segment truncated at the signature start followed by the new signature
    // data.
    let new_linkedit_segment_size = macho
        .linkedit_data_before_signature()
        .ok_or(AppleCodesignError::MissingLinkedit)?
        .len()
        + signature_data.len();

    // `codesign` rounds up the segment's vmsize to the nearest 16kb boundary.
    // We emulate that behavior.
    let remainder = new_linkedit_segment_size % 16384;
    let new_linkedit_segment_vmsize = if remainder == 0 {
        new_linkedit_segment_size
    } else {
        new_linkedit_segment_size + 16384 - remainder
    };

    assert!(new_linkedit_segment_vmsize >= new_linkedit_segment_size);
    assert_eq!(new_linkedit_segment_vmsize % 16384, 0);

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

    // Mach-O data structures are variable endian. So use the endian defined
    // by the magic when writing.
    let ctx = parse_magic_and_ctx(macho.data, 0)?
        .1
        .expect("context should have been parsed before");

    // If there isn't a code signature presently, we'll need to introduce a load
    // command for it.
    let mut header = macho.macho.header;
    if macho.code_signature_load_command().is_none() {
        header.ncmds += 1;
        header.sizeofcmds += SIZEOF_LINKEDIT_DATA_COMMAND as u32;
    }

    cursor.iowrite_with(header, ctx)?;

    // Following the header are load commands. We need to update load commands
    // to reflect changes to the signature size and __LINKEDIT segment size.

    let mut seen_signature_load_command = false;

    for load_command in &macho.macho.load_commands {
        let original_command_data =
            &macho.data[load_command.offset..load_command.offset + load_command.command.cmdsize()];

        let written_len = match &load_command.command {
            CommandVariant::CodeSignature(command) => {
                seen_signature_load_command = true;

                let mut command = *command;
                command.datasize = signature_data.len() as _;

                cursor.iowrite_with(command, ctx.le)?;

                LinkeditDataCommand::size_with(&ctx.le)
            }
            CommandVariant::Segment32(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand32::size_with(&ctx.le)
            }
            CommandVariant::Segment64(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand64::size_with(&ctx.le)
            }
            _ => {
                // Reflect the original bytes.
                cursor.write_all(original_command_data)?;
                original_command_data.len()
            }
        };

        // For the commands we mutated ourselves, there may be more data after the
        // load command header. Write it out if present.
        cursor.write_all(&original_command_data[written_len..])?;
    }

    // If we didn't see a signature load command, write one out now.
    if !seen_signature_load_command {
        let command = LinkeditDataCommand {
            cmd: LC_CODE_SIGNATURE,
            cmdsize: SIZEOF_LINKEDIT_DATA_COMMAND as _,
            dataoff: macho.code_limit_binary_offset()? as _,
            datasize: signature_data.len() as _,
        };

        cursor.iowrite_with(command, ctx.le)?;
    }

    // Write out segments, updating the __LINKEDIT segment when we encounter it.
    for segment in macho.segments_by_file_offset() {
        // The initial __PAGEZERO segment contains no data (it is the magic and load
        // commands) and overlaps with the __TEXT segment, which has .fileoff =0, so
        // we ignore it.
        if matches!(segment.name(), Ok(SEG_PAGEZERO)) {
            continue;
        }

        match cursor.position().cmp(&segment.fileoff) {
            // Mach-O segments may have padding between them. In this case, copy these
            // bytes (presumably NULLs but that isn't guaranteed) to the output.
            Ordering::Less => {
                let padding = &macho.data[cursor.position() as usize..segment.fileoff as usize];
                debug!(
                    "copying {} bytes outside segment boundaries before segment {}",
                    padding.len(),
                    segment.name().unwrap_or("<unknown>")
                );
                cursor.write_all(padding)?;
            }
            // The __TEXT segment usually has .fileoff = 0, which has it overlapping with
            // already written data. Allow this special case through.
            Ordering::Greater if segment.fileoff == 0 => {}

            // The writer has overran into this segment. That means we screwed up on a
            // previous loop iteration.
            Ordering::Greater => {
                return Err(AppleCodesignError::MachOWrite(format!(
                    "Mach-O segment corruption: cursor at 0x{:x} but segment begins at 0x{:x} (please report this bug)",
                    cursor.position(),
                    segment.fileoff
                )));
            }
            Ordering::Equal => {}
        }

        assert!(segment.fileoff == 0 || segment.fileoff == cursor.position());

        match segment.name() {
            Ok(SEG_LINKEDIT) => {
                cursor.write_all(
                    macho
                        .linkedit_data_before_signature()
                        .expect("__LINKEDIT segment data should resolve"),
                )?;
                cursor.write_all(signature_data)?;
            }
            _ => {
                // At least the __TEXT segment has .fileoff = 0, which has it
                // overlapping with already written data. So only write segment
                // data new to the writer.
                if segment.fileoff < cursor.position() {
                    if segment.data.is_empty() {
                        continue;
                    }
                    let remaining =
                        &segment.data[cursor.position() as usize..segment.filesize as usize];
                    cursor.write_all(remaining)?;
                } else {
                    cursor.write_all(segment.data)?;
                }
            }
        }
    }

    Ok(cursor.into_inner())
}

/// Write Mach-O file content to an output file.
pub fn write_macho_file(
    input_path: &Path,
    output_path: &Path,
    macho_data: &[u8],
) -> Result<(), AppleCodesignError> {
    // Read permissions first in case we overwrite the original file.
    let permissions = std::fs::metadata(input_path)?.permissions();

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

    {
        let mut fh = std::fs::File::create(output_path)?;
        fh.write_all(macho_data)?;
    }

    std::fs::set_permissions(output_path, permissions)?;

    Ok(())
}

/// Mach-O binary signer.
///
/// This type provides a high-level interface for signing Mach-O binaries.
/// It handles parsing and rewriting Mach-O binaries and contains most of the
/// functionality for producing signatures for individual Mach-O binaries.
///
/// Signing of both single architecture and fat/universal binaries is supported.
///
/// # Circular Dependency
///
/// There is a circular dependency between the generation of the Code Directory
/// present in the embedded signature and the Mach-O binary. See the note
/// in [crate::specification] for the gory details. The tl;dr is the Mach-O
/// data up to the signature data needs to be digested. But that digested data
/// contains load commands that reference the signature data and its size, which
/// can't be known until the Code Directory, CMS blob, and SuperBlob are all
/// created.
///
/// Our solution to this problem is to estimate the size of the embedded
/// signature data and then pad the unused data will 0s.
pub struct MachOSigner<'data> {
    /// Parsed Mach-O binaries.
    machos: Vec<MachOBinary<'data>>,
}

impl<'data> MachOSigner<'data> {
    /// Construct a new instance from unparsed data representing a Mach-O binary.
    ///
    /// The data will be parsed as a Mach-O binary (either single arch or fat/universal)
    /// and validated that we are capable of signing it.
    pub fn new(macho_data: &'data [u8]) -> Result<Self, AppleCodesignError> {
        let machos = MachFile::parse(macho_data)?.into_iter().collect::<Vec<_>>();

        Ok(Self { machos })
    }

    /// Write signed Mach-O data to the given writer using signing settings.
    pub fn write_signed_binary(
        &self,
        settings: &SigningSettings,
        writer: &mut impl Write,
    ) -> Result<(), AppleCodesignError> {
        // Implementing a true streaming writer requires calculating final sizes
        // of all binaries so fat header offsets and sizes can be written first. We take
        // the easy road and buffer individual Mach-O binaries internally.

        let binaries = self
            .machos
            .iter()
            .enumerate()
            .map(|(index, original_macho)| {
                info!("signing Mach-O binary at index {}", index);
                let settings =
                    settings.as_nested_macho_settings(index, original_macho.macho.header.cputype());

                let signature_len = original_macho.estimate_embedded_signature_size(&settings)?;

                // Derive an intermediate Mach-O with placeholder NULLs for signature
                // data so Code Directory digests over the load commands are correct.
                let placeholder_signature_data = b"\0".repeat(signature_len);

                let intermediate_macho_data =
                    create_macho_with_signature(original_macho, &placeholder_signature_data)?;

                // A nice side-effect of this is that it catches bugs if we write malformed Mach-O!
                let intermediate_macho = MachOBinary::parse(&intermediate_macho_data)?;

                let mut signature_data = self.create_superblob(&settings, &intermediate_macho)?;
                info!("total signature size: {} bytes", signature_data.len());

                // The Mach-O writer adjusts load commands based on the signature length. So pad
                // with NULLs to get to our placeholder length.
                match signature_data.len().cmp(&placeholder_signature_data.len()) {
                    Ordering::Greater => {
                        return Err(AppleCodesignError::SignatureDataTooLarge);
                    }
                    Ordering::Equal => {}
                    Ordering::Less => {
                        signature_data.extend_from_slice(
                            &b"\0".repeat(placeholder_signature_data.len() - signature_data.len()),
                        );
                    }
                }

                create_macho_with_signature(&intermediate_macho, &signature_data)
            })
            .collect::<Result<Vec<_>, AppleCodesignError>>()?;

        if binaries.len() > 1 {
            create_universal_macho(writer, binaries.iter().map(|x| x.as_slice()))?;
        } else {
            writer.write_all(&binaries[0])?;
        }

        Ok(())
    }

    /// Create data constituting the SuperBlob to be embedded in the `__LINKEDIT` segment.
    ///
    /// The superblob contains the code directory, any extra blobs, and an optional
    /// CMS structure containing a cryptographic signature.
    ///
    /// This takes an explicit Mach-O to operate on due to a circular dependency
    /// between writing out the Mach-O and digesting its content. See the note
    /// in [MachOSigner] for details.
    pub fn create_superblob(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<Vec<u8>, AppleCodesignError> {
        let mut builder = EmbeddedSignatureBuilder::default();

        for (slot, blob) in self.create_special_blobs(settings, macho.is_executable())? {
            builder.add_blob(slot, blob)?;
        }

        let code_directory = self.create_code_directory(settings, macho)?;
        info!("code directory version: {}", code_directory.version);

        builder.add_code_directory(CodeSigningSlot::CodeDirectory, code_directory)?;

        if let Some(digests) = settings.extra_digests(SettingsScope::Main) {
            for digest_type in digests {
                // Since everything consults settings for the digest to use, just make a new settings
                // with a different digest.
                let mut alt_settings = settings.clone();
                alt_settings.set_digest_type(*digest_type);

                info!(
                    "adding alternative code directory using digest {:?}",
                    digest_type
                );
                let cd = self.create_code_directory(&alt_settings, macho)?;

                builder.add_alternative_code_directory(cd)?;
            }
        }

        if let Some((signing_key, signing_cert)) = settings.signing_key() {
            builder.create_cms_signature(
                signing_key,
                signing_cert,
                settings.time_stamp_url(),
                settings.certificate_chain().iter().cloned(),
            )?;
        }

        builder.create_superblob()
    }

    /// Create the `CodeDirectory` for the current configuration.
    ///
    /// This takes an explicit Mach-O to operate on due to a circular dependency
    /// between writing out the Mach-O and digesting its content. See the note
    /// in [MachOSigner] for details.
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

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

        let mut flags = CodeSignatureFlags::empty();

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

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

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

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

        let platform = 0;
        let page_size = 4096u32;

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

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

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

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

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

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

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

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

        let mut special_hashes = HashMap::new();

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

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

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

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

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

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

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

        Ok(cd)
    }

Obtain __LINKEDIT segment data before the signature data.

If there is no signature, returns all the data for the __LINKEDIT segment.

Examples found in repository?
src/macho_signing.rs (line 51)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
fn create_macho_with_signature(
    macho: &MachOBinary,
    signature_data: &[u8],
) -> Result<Vec<u8>, AppleCodesignError> {
    // This should have already been called. But we do it again out of paranoia.
    macho.check_signing_capability()?;

    // The assumption made by checking_signing_capability() is that signature data
    // is at the end of the __LINKEDIT segment. So the replacement segment is the
    // existing segment truncated at the signature start followed by the new signature
    // data.
    let new_linkedit_segment_size = macho
        .linkedit_data_before_signature()
        .ok_or(AppleCodesignError::MissingLinkedit)?
        .len()
        + signature_data.len();

    // `codesign` rounds up the segment's vmsize to the nearest 16kb boundary.
    // We emulate that behavior.
    let remainder = new_linkedit_segment_size % 16384;
    let new_linkedit_segment_vmsize = if remainder == 0 {
        new_linkedit_segment_size
    } else {
        new_linkedit_segment_size + 16384 - remainder
    };

    assert!(new_linkedit_segment_vmsize >= new_linkedit_segment_size);
    assert_eq!(new_linkedit_segment_vmsize % 16384, 0);

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

    // Mach-O data structures are variable endian. So use the endian defined
    // by the magic when writing.
    let ctx = parse_magic_and_ctx(macho.data, 0)?
        .1
        .expect("context should have been parsed before");

    // If there isn't a code signature presently, we'll need to introduce a load
    // command for it.
    let mut header = macho.macho.header;
    if macho.code_signature_load_command().is_none() {
        header.ncmds += 1;
        header.sizeofcmds += SIZEOF_LINKEDIT_DATA_COMMAND as u32;
    }

    cursor.iowrite_with(header, ctx)?;

    // Following the header are load commands. We need to update load commands
    // to reflect changes to the signature size and __LINKEDIT segment size.

    let mut seen_signature_load_command = false;

    for load_command in &macho.macho.load_commands {
        let original_command_data =
            &macho.data[load_command.offset..load_command.offset + load_command.command.cmdsize()];

        let written_len = match &load_command.command {
            CommandVariant::CodeSignature(command) => {
                seen_signature_load_command = true;

                let mut command = *command;
                command.datasize = signature_data.len() as _;

                cursor.iowrite_with(command, ctx.le)?;

                LinkeditDataCommand::size_with(&ctx.le)
            }
            CommandVariant::Segment32(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand32::size_with(&ctx.le)
            }
            CommandVariant::Segment64(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand64::size_with(&ctx.le)
            }
            _ => {
                // Reflect the original bytes.
                cursor.write_all(original_command_data)?;
                original_command_data.len()
            }
        };

        // For the commands we mutated ourselves, there may be more data after the
        // load command header. Write it out if present.
        cursor.write_all(&original_command_data[written_len..])?;
    }

    // If we didn't see a signature load command, write one out now.
    if !seen_signature_load_command {
        let command = LinkeditDataCommand {
            cmd: LC_CODE_SIGNATURE,
            cmdsize: SIZEOF_LINKEDIT_DATA_COMMAND as _,
            dataoff: macho.code_limit_binary_offset()? as _,
            datasize: signature_data.len() as _,
        };

        cursor.iowrite_with(command, ctx.le)?;
    }

    // Write out segments, updating the __LINKEDIT segment when we encounter it.
    for segment in macho.segments_by_file_offset() {
        // The initial __PAGEZERO segment contains no data (it is the magic and load
        // commands) and overlaps with the __TEXT segment, which has .fileoff =0, so
        // we ignore it.
        if matches!(segment.name(), Ok(SEG_PAGEZERO)) {
            continue;
        }

        match cursor.position().cmp(&segment.fileoff) {
            // Mach-O segments may have padding between them. In this case, copy these
            // bytes (presumably NULLs but that isn't guaranteed) to the output.
            Ordering::Less => {
                let padding = &macho.data[cursor.position() as usize..segment.fileoff as usize];
                debug!(
                    "copying {} bytes outside segment boundaries before segment {}",
                    padding.len(),
                    segment.name().unwrap_or("<unknown>")
                );
                cursor.write_all(padding)?;
            }
            // The __TEXT segment usually has .fileoff = 0, which has it overlapping with
            // already written data. Allow this special case through.
            Ordering::Greater if segment.fileoff == 0 => {}

            // The writer has overran into this segment. That means we screwed up on a
            // previous loop iteration.
            Ordering::Greater => {
                return Err(AppleCodesignError::MachOWrite(format!(
                    "Mach-O segment corruption: cursor at 0x{:x} but segment begins at 0x{:x} (please report this bug)",
                    cursor.position(),
                    segment.fileoff
                )));
            }
            Ordering::Equal => {}
        }

        assert!(segment.fileoff == 0 || segment.fileoff == cursor.position());

        match segment.name() {
            Ok(SEG_LINKEDIT) => {
                cursor.write_all(
                    macho
                        .linkedit_data_before_signature()
                        .expect("__LINKEDIT segment data should resolve"),
                )?;
                cursor.write_all(signature_data)?;
            }
            _ => {
                // At least the __TEXT segment has .fileoff = 0, which has it
                // overlapping with already written data. So only write segment
                // data new to the writer.
                if segment.fileoff < cursor.position() {
                    if segment.data.is_empty() {
                        continue;
                    }
                    let remaining =
                        &segment.data[cursor.position() as usize..segment.filesize as usize];
                    cursor.write_all(remaining)?;
                } else {
                    cursor.write_all(segment.data)?;
                }
            }
        }
    }

    Ok(cursor.into_inner())
}

Obtain Mach-O binary data to be digested in code digests.

Returns the raw data whose digests will be captured by the Code Directory code digests.

Examples found in repository?
src/macho.rs (line 253)
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    pub fn code_digests_size(
        &self,
        digest: DigestType,
        page_size: usize,
    ) -> Result<usize, AppleCodesignError> {
        let empty = digest.digest_data(b"")?;

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

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

        // Premature parallelism can be slower due to overhead of having to spin up threads.
        // So only do parallel digests if we have enough data to warrant it.
        if data.len() > 64 * 1024 * 1024 {
            data.par_chunks(page_size)
                .map(|c| digest.digest_data(c))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        } else {
            self.digested_code_data()?
                .chunks(page_size)
                .map(|chunk| digest.digest_data(chunk))
                .collect::<Result<Vec<_>, AppleCodesignError>>()
        }
    }

Obtain the size in bytes of all code digests given a digest type and page size.

Examples found in repository?
src/macho.rs (line 393)
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
    pub fn estimate_embedded_signature_size(
        &self,
        settings: &SigningSettings,
    ) -> Result<usize, AppleCodesignError> {
        let code_directory_count = 1 + settings
            .extra_digests(SettingsScope::Main)
            .map(|x| x.len())
            .unwrap_or_default();

        // Assume the common data structures are 1024 bytes.
        let mut size = 1024 * code_directory_count;

        // Reserve room for the code digests, which are proportional to binary size.
        // We could avoid doing the actual digesting work here. But until people
        // complain, don't worry about it.
        size += self.code_digests_size(*settings.digest_type(), 4096)?;

        if let Some(digests) = settings.extra_digests(SettingsScope::Main) {
            for digest in digests {
                size += self.code_digests_size(*digest, 4096)?;
            }
        }

        // Assume the CMS data will take a fixed size.
        if settings.signing_key().is_some() {
            size += 4096;
        }

        // Long certificate chains could blow up the size. Account for those.
        for cert in settings.certificate_chain() {
            size += cert.constructed_data().len();
        }

        // Add entitlements xml if needed.
        if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
            size += entitlements.as_bytes().len()
        }

        // Obtain an actual timestamp token of placeholder data and use its length.
        // This may be excessive to actually query the time-stamp server and issue
        // a token. But these operations should be "cheap."
        if let Some(timestamp_url) = settings.time_stamp_url() {
            let message = b"deadbeef".repeat(32);

            if let Ok(response) =
                time_stamp_message_http(timestamp_url.clone(), &message, DigestAlgorithm::Sha256)
            {
                if response.is_success() {
                    if let Some(l) = response.token_content_size() {
                        size += l;
                    } else {
                        size += 8192;
                    }
                } else {
                    size += 8192;
                }
            } else {
                size += 8192;
            }
        }

        // Align on 1k boundaries just because.
        size += 1024 - size % 1024;

        Ok(size)
    }

Compute digests over code in this binary.

Examples found in repository?
src/cli.rs (line 1015)
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
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(())
}
More examples
Hide additional examples
src/verify.rs (line 420)
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
fn verify_code_directory(
    macho: &MachOBinary,
    signature: &EmbeddedSignature,
    cd: &CodeDirectoryBlob,
    context: VerificationContext,
) -> Vec<VerificationProblem> {
    let mut problems = vec![];

    match cd.digest_type {
        DigestType::Sha256 | DigestType::Sha384 => {}
        hash_type => problems.push(VerificationProblem {
            context: context.clone(),
            problem: VerificationProblemType::CodeDirectoryOldDigestAlgorithm(hash_type),
        }),
    }

    match macho.code_digests(cd.digest_type, cd.page_size as _) {
        Ok(digests) => {
            let mut cd_iter = cd.code_digests.iter().enumerate();
            let mut actual_iter = digests.iter().enumerate();

            loop {
                match (cd_iter.next(), actual_iter.next()) {
                    (None, None) => {
                        break;
                    }
                    (Some((cd_index, cd_digest)), Some((_, actual_digest))) => {
                        if &cd_digest.data != actual_digest {
                            problems.push(VerificationProblem {
                                context: context.clone(),
                                problem: VerificationProblemType::CodeDigestMismatch(
                                    cd_index,
                                    cd_digest.to_vec(),
                                    actual_digest.clone(),
                                ),
                            });
                        }
                    }
                    (None, Some((actual_index, actual_digest))) => {
                        problems.push(VerificationProblem {
                            context: context.clone(),
                            problem: VerificationProblemType::CodeDigestMissingEntry(
                                actual_index,
                                actual_digest.clone(),
                            ),
                        });
                    }
                    (Some((cd_index, cd_digest)), None) => {
                        problems.push(VerificationProblem {
                            context: context.clone(),
                            problem: VerificationProblemType::CodeDigestExtraEntry(
                                cd_index,
                                cd_digest.to_vec(),
                            ),
                        });
                    }
                }
            }
        }
        Err(e) => {
            problems.push(VerificationProblem {
                context: context.clone(),
                problem: VerificationProblemType::CodeDigestError(e),
            });
        }
    }

    // All slots beneath some threshold should have a special hash.
    // It isn't clear where this threshold is. But the alternate code directory and
    // CMS slots appear to start at 0x1000. We set our limit at 32, which seems
    // reasonable considering there are ~10 defined slots starting at value 0.
    //
    // The code directory doesn't have a digest because one cannot hash self.
    for blob in &signature.blobs {
        let slot = blob.slot;

        if u32::from(slot) < 32
            && !cd.slot_digests().contains_key(&slot)
            && slot != CodeSigningSlot::CodeDirectory
        {
            problems.push(VerificationProblem {
                context: context.clone(),
                problem: VerificationProblemType::SlotDigestMissing(slot),
            });
        }
    }

    let max_slot = cd
        .slot_digests()
        .keys()
        .map(|slot| u32::from(*slot))
        .filter(|slot| *slot < 32)
        .max()
        .unwrap_or(0);

    let null_digest = b"\0".repeat(cd.digest_size as usize);

    // Verify the special/slot digests we do have match reality.
    for (slot, cd_digest) in cd.slot_digests().iter() {
        match signature.find_slot(*slot) {
            Some(entry) => match entry.digest_with(cd.digest_type) {
                Ok(actual_digest) => {
                    if actual_digest != cd_digest.to_vec() {
                        problems.push(VerificationProblem {
                            context: context.clone(),
                            problem: VerificationProblemType::SlotDigestMismatch(
                                *slot,
                                cd_digest.to_vec(),
                                actual_digest,
                            ),
                        });
                    }
                }
                Err(e) => {
                    problems.push(VerificationProblem {
                        context: context.clone(),
                        problem: VerificationProblemType::SlotDigestError(e),
                    });
                }
            },
            None => {
                // Some slots have external provided from somewhere that isn't a blob.
                if slot.has_external_content() {
                    // TODO need to validate this external content somewhere.
                }
                // But slots with a null digest (all 0s) exist as placeholders when there
                // is a higher numbered slot present.
                else if u32::from(*slot) >= max_slot || cd_digest.to_vec() != null_digest {
                    problems.push(VerificationProblem {
                        context: context.clone(),
                        problem: VerificationProblemType::ExtraSlotDigest(
                            *slot,
                            cd_digest.to_vec(),
                        ),
                    });
                }
            }
        }
    }

    // TODO verify code_limit[_64] is appropriate.
    // TODO verify exec_seg_base is appropriate.

    problems
}
src/macho_signing.rs (line 523)
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

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

        let mut flags = CodeSignatureFlags::empty();

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

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

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

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

        let platform = 0;
        let page_size = 4096u32;

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

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

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

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

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

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

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

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

        let mut special_hashes = HashMap::new();

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

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

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

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

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

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

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

        Ok(cd)
    }

Resolve the load command for the code signature.

Examples found in repository?
src/macho.rs (line 166)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    pub fn code_signature_linkedit_start_offset(&self) -> Option<u32> {
        let segment = self
            .macho
            .segments
            .iter()
            .find(|segment| matches!(segment.name(), Ok(SEG_LINKEDIT)));

        if let (Some(segment), Some(command)) = (segment, self.code_signature_load_command()) {
            Some((command.dataoff as u64 - segment.fileoff) as u32)
        } else {
            None
        }
    }

    /// The end offset of the code signature data within the __LINKEDIT segment.
    pub fn code_signature_linkedit_end_offset(&self) -> Option<u32> {
        let start_offset = self.code_signature_linkedit_start_offset()?;

        self.code_signature_load_command()
            .map(|command| start_offset + command.datasize)
    }
More examples
Hide additional examples
src/macho_signing.rs (line 79)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
fn create_macho_with_signature(
    macho: &MachOBinary,
    signature_data: &[u8],
) -> Result<Vec<u8>, AppleCodesignError> {
    // This should have already been called. But we do it again out of paranoia.
    macho.check_signing_capability()?;

    // The assumption made by checking_signing_capability() is that signature data
    // is at the end of the __LINKEDIT segment. So the replacement segment is the
    // existing segment truncated at the signature start followed by the new signature
    // data.
    let new_linkedit_segment_size = macho
        .linkedit_data_before_signature()
        .ok_or(AppleCodesignError::MissingLinkedit)?
        .len()
        + signature_data.len();

    // `codesign` rounds up the segment's vmsize to the nearest 16kb boundary.
    // We emulate that behavior.
    let remainder = new_linkedit_segment_size % 16384;
    let new_linkedit_segment_vmsize = if remainder == 0 {
        new_linkedit_segment_size
    } else {
        new_linkedit_segment_size + 16384 - remainder
    };

    assert!(new_linkedit_segment_vmsize >= new_linkedit_segment_size);
    assert_eq!(new_linkedit_segment_vmsize % 16384, 0);

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

    // Mach-O data structures are variable endian. So use the endian defined
    // by the magic when writing.
    let ctx = parse_magic_and_ctx(macho.data, 0)?
        .1
        .expect("context should have been parsed before");

    // If there isn't a code signature presently, we'll need to introduce a load
    // command for it.
    let mut header = macho.macho.header;
    if macho.code_signature_load_command().is_none() {
        header.ncmds += 1;
        header.sizeofcmds += SIZEOF_LINKEDIT_DATA_COMMAND as u32;
    }

    cursor.iowrite_with(header, ctx)?;

    // Following the header are load commands. We need to update load commands
    // to reflect changes to the signature size and __LINKEDIT segment size.

    let mut seen_signature_load_command = false;

    for load_command in &macho.macho.load_commands {
        let original_command_data =
            &macho.data[load_command.offset..load_command.offset + load_command.command.cmdsize()];

        let written_len = match &load_command.command {
            CommandVariant::CodeSignature(command) => {
                seen_signature_load_command = true;

                let mut command = *command;
                command.datasize = signature_data.len() as _;

                cursor.iowrite_with(command, ctx.le)?;

                LinkeditDataCommand::size_with(&ctx.le)
            }
            CommandVariant::Segment32(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand32::size_with(&ctx.le)
            }
            CommandVariant::Segment64(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand64::size_with(&ctx.le)
            }
            _ => {
                // Reflect the original bytes.
                cursor.write_all(original_command_data)?;
                original_command_data.len()
            }
        };

        // For the commands we mutated ourselves, there may be more data after the
        // load command header. Write it out if present.
        cursor.write_all(&original_command_data[written_len..])?;
    }

    // If we didn't see a signature load command, write one out now.
    if !seen_signature_load_command {
        let command = LinkeditDataCommand {
            cmd: LC_CODE_SIGNATURE,
            cmdsize: SIZEOF_LINKEDIT_DATA_COMMAND as _,
            dataoff: macho.code_limit_binary_offset()? as _,
            datasize: signature_data.len() as _,
        };

        cursor.iowrite_with(command, ctx.le)?;
    }

    // Write out segments, updating the __LINKEDIT segment when we encounter it.
    for segment in macho.segments_by_file_offset() {
        // The initial __PAGEZERO segment contains no data (it is the magic and load
        // commands) and overlaps with the __TEXT segment, which has .fileoff =0, so
        // we ignore it.
        if matches!(segment.name(), Ok(SEG_PAGEZERO)) {
            continue;
        }

        match cursor.position().cmp(&segment.fileoff) {
            // Mach-O segments may have padding between them. In this case, copy these
            // bytes (presumably NULLs but that isn't guaranteed) to the output.
            Ordering::Less => {
                let padding = &macho.data[cursor.position() as usize..segment.fileoff as usize];
                debug!(
                    "copying {} bytes outside segment boundaries before segment {}",
                    padding.len(),
                    segment.name().unwrap_or("<unknown>")
                );
                cursor.write_all(padding)?;
            }
            // The __TEXT segment usually has .fileoff = 0, which has it overlapping with
            // already written data. Allow this special case through.
            Ordering::Greater if segment.fileoff == 0 => {}

            // The writer has overran into this segment. That means we screwed up on a
            // previous loop iteration.
            Ordering::Greater => {
                return Err(AppleCodesignError::MachOWrite(format!(
                    "Mach-O segment corruption: cursor at 0x{:x} but segment begins at 0x{:x} (please report this bug)",
                    cursor.position(),
                    segment.fileoff
                )));
            }
            Ordering::Equal => {}
        }

        assert!(segment.fileoff == 0 || segment.fileoff == cursor.position());

        match segment.name() {
            Ok(SEG_LINKEDIT) => {
                cursor.write_all(
                    macho
                        .linkedit_data_before_signature()
                        .expect("__LINKEDIT segment data should resolve"),
                )?;
                cursor.write_all(signature_data)?;
            }
            _ => {
                // At least the __TEXT segment has .fileoff = 0, which has it
                // overlapping with already written data. So only write segment
                // data new to the writer.
                if segment.fileoff < cursor.position() {
                    if segment.data.is_empty() {
                        continue;
                    }
                    let remaining =
                        &segment.data[cursor.position() as usize..segment.filesize as usize];
                    cursor.write_all(remaining)?;
                } else {
                    cursor.write_all(segment.data)?;
                }
            }
        }
    }

    Ok(cursor.into_inner())
}

Attempt to locate embedded Info.plist data.

Examples found in repository?
src/signing_settings.rs (line 781)
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
    pub fn import_settings_from_macho(&mut self, data: &[u8]) -> Result<(), AppleCodesignError> {
        info!("inferring default signing settings from Mach-O binary");

        for macho in MachFile::parse(data)?.into_iter() {
            let index = macho.index.unwrap_or(0);

            let scope_main = SettingsScope::Main;
            let scope_index = SettingsScope::MultiArchIndex(index);
            let scope_arch = SettingsScope::MultiArchCpuType(macho.macho.header.cputype());

            // Older operating system versions don't have support for SHA-256 in
            // signatures. If the minimum version targeting in the binary doesn't
            // support SHA-256, we automatically change the digest targeting settings
            // so the binary will be signed correctly.
            if let Some(targeting) = macho.find_targeting()? {
                let sha256_version = targeting.platform.sha256_digest_support()?;

                if !sha256_version.matches(&targeting.minimum_os_version) {
                    info!(
                        "activating SHA-1 digests because minimum OS target {} is not {}",
                        targeting.minimum_os_version, sha256_version
                    );

                    // This logic is a bit wonky. We want SHA-1 to be present on all binaries
                    // within a fat binary. So if we need SHA-1 mode, we set the setting on the
                    // main scope and then clear any overrides on fat binary scopes so our
                    // settings are canonical.
                    self.set_digest_type(DigestType::Sha1);
                    self.add_extra_digest(scope_main.clone(), DigestType::Sha256);
                    self.extra_digests.remove(&scope_arch);
                    self.extra_digests.remove(&scope_index);
                }
            }

            // The Mach-O can have embedded Info.plist data. Use it if available and not
            // already defined in settings.
            if let Some(info_plist) = macho.embedded_info_plist()? {
                if self.info_plist_data(&scope_main).is_some()
                    || self.info_plist_data(&scope_index).is_some()
                    || self.info_plist_data(&scope_arch).is_some()
                {
                    info!("using Info.plist data from settings");
                } else {
                    info!("preserving Info.plist data already present in Mach-O");
                    self.set_info_plist_data(scope_index.clone(), info_plist);
                }
            }

            if let Some(sig) = macho.code_signature()? {
                if let Some(cd) = sig.code_directory()? {
                    if self.binary_identifier(&scope_main).is_some()
                        || self.binary_identifier(&scope_index).is_some()
                        || self.binary_identifier(&scope_arch).is_some()
                    {
                        info!("using binary identifier from settings");
                    } else {
                        info!("preserving existing binary identifier in Mach-O");
                        self.set_binary_identifier(scope_index.clone(), cd.ident);
                    }

                    if self.team_id.contains_key(&scope_main)
                        || self.team_id.contains_key(&scope_index)
                        || self.team_id.contains_key(&scope_arch)
                    {
                        info!("using team ID from settings");
                    } else if let Some(team_id) = cd.team_name {
                        info!("preserving team ID in existing Mach-O signature");
                        self.team_id
                            .insert(scope_index.clone(), team_id.to_string());
                    }

                    if self.code_signature_flags(&scope_main).is_some()
                        || self.code_signature_flags(&scope_index).is_some()
                        || self.code_signature_flags(&scope_arch).is_some()
                    {
                        info!("using code signature flags from settings");
                    } else if !cd.flags.is_empty() {
                        info!("preserving code signature flags in existing Mach-O signature");
                        self.set_code_signature_flags(scope_index.clone(), cd.flags);
                    }

                    if self.runtime_version(&scope_main).is_some()
                        || self.runtime_version(&scope_index).is_some()
                        || self.runtime_version(&scope_arch).is_some()
                    {
                        info!("using runtime version from settings");
                    } else if let Some(version) = cd.runtime {
                        info!("preserving runtime version in existing Mach-O signature");
                        self.set_runtime_version(
                            scope_index.clone(),
                            parse_version_nibbles(version),
                        );
                    }
                }

                if let Some(entitlements) = sig.entitlements()? {
                    if self.entitlements_plist(&scope_main).is_some()
                        || self.entitlements_plist(&scope_index).is_some()
                        || self.entitlements_plist(&scope_arch).is_some()
                    {
                        info!("using entitlements from settings");
                    } else {
                        info!("preserving existing entitlements in Mach-O");
                        self.set_entitlements_xml(
                            SettingsScope::MultiArchIndex(index),
                            entitlements.as_str(),
                        )?;
                    }
                }
            }
        }

        Ok(())
    }

Determines whether this crate is capable of signing a given Mach-O binary.

Code in this crate is limited in the amount of Mach-O binary manipulation it can perform (supporting rewriting all valid Mach-O binaries effectively requires low-level awareness of all Mach-O constructs in order to perform offset manipulation). This function can be used to test signing compatibility.

We currently only support signing Mach-O files already containing an embedded signature. Often linked binaries automatically contain an embedded signature containing just the code directory (without a cryptographically signed signature), so this limitation hopefully isn’t impactful.

Examples found in repository?
src/macho_signing.rs (line 44)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
fn create_macho_with_signature(
    macho: &MachOBinary,
    signature_data: &[u8],
) -> Result<Vec<u8>, AppleCodesignError> {
    // This should have already been called. But we do it again out of paranoia.
    macho.check_signing_capability()?;

    // The assumption made by checking_signing_capability() is that signature data
    // is at the end of the __LINKEDIT segment. So the replacement segment is the
    // existing segment truncated at the signature start followed by the new signature
    // data.
    let new_linkedit_segment_size = macho
        .linkedit_data_before_signature()
        .ok_or(AppleCodesignError::MissingLinkedit)?
        .len()
        + signature_data.len();

    // `codesign` rounds up the segment's vmsize to the nearest 16kb boundary.
    // We emulate that behavior.
    let remainder = new_linkedit_segment_size % 16384;
    let new_linkedit_segment_vmsize = if remainder == 0 {
        new_linkedit_segment_size
    } else {
        new_linkedit_segment_size + 16384 - remainder
    };

    assert!(new_linkedit_segment_vmsize >= new_linkedit_segment_size);
    assert_eq!(new_linkedit_segment_vmsize % 16384, 0);

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

    // Mach-O data structures are variable endian. So use the endian defined
    // by the magic when writing.
    let ctx = parse_magic_and_ctx(macho.data, 0)?
        .1
        .expect("context should have been parsed before");

    // If there isn't a code signature presently, we'll need to introduce a load
    // command for it.
    let mut header = macho.macho.header;
    if macho.code_signature_load_command().is_none() {
        header.ncmds += 1;
        header.sizeofcmds += SIZEOF_LINKEDIT_DATA_COMMAND as u32;
    }

    cursor.iowrite_with(header, ctx)?;

    // Following the header are load commands. We need to update load commands
    // to reflect changes to the signature size and __LINKEDIT segment size.

    let mut seen_signature_load_command = false;

    for load_command in &macho.macho.load_commands {
        let original_command_data =
            &macho.data[load_command.offset..load_command.offset + load_command.command.cmdsize()];

        let written_len = match &load_command.command {
            CommandVariant::CodeSignature(command) => {
                seen_signature_load_command = true;

                let mut command = *command;
                command.datasize = signature_data.len() as _;

                cursor.iowrite_with(command, ctx.le)?;

                LinkeditDataCommand::size_with(&ctx.le)
            }
            CommandVariant::Segment32(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand32::size_with(&ctx.le)
            }
            CommandVariant::Segment64(segment) => {
                let segment = match segment.name() {
                    Ok(SEG_LINKEDIT) => {
                        let mut segment = *segment;
                        segment.filesize = new_linkedit_segment_size as _;
                        segment.vmsize = new_linkedit_segment_vmsize as _;

                        segment
                    }
                    _ => *segment,
                };

                cursor.iowrite_with(segment, ctx.le)?;

                SegmentCommand64::size_with(&ctx.le)
            }
            _ => {
                // Reflect the original bytes.
                cursor.write_all(original_command_data)?;
                original_command_data.len()
            }
        };

        // For the commands we mutated ourselves, there may be more data after the
        // load command header. Write it out if present.
        cursor.write_all(&original_command_data[written_len..])?;
    }

    // If we didn't see a signature load command, write one out now.
    if !seen_signature_load_command {
        let command = LinkeditDataCommand {
            cmd: LC_CODE_SIGNATURE,
            cmdsize: SIZEOF_LINKEDIT_DATA_COMMAND as _,
            dataoff: macho.code_limit_binary_offset()? as _,
            datasize: signature_data.len() as _,
        };

        cursor.iowrite_with(command, ctx.le)?;
    }

    // Write out segments, updating the __LINKEDIT segment when we encounter it.
    for segment in macho.segments_by_file_offset() {
        // The initial __PAGEZERO segment contains no data (it is the magic and load
        // commands) and overlaps with the __TEXT segment, which has .fileoff =0, so
        // we ignore it.
        if matches!(segment.name(), Ok(SEG_PAGEZERO)) {
            continue;
        }

        match cursor.position().cmp(&segment.fileoff) {
            // Mach-O segments may have padding between them. In this case, copy these
            // bytes (presumably NULLs but that isn't guaranteed) to the output.
            Ordering::Less => {
                let padding = &macho.data[cursor.position() as usize..segment.fileoff as usize];
                debug!(
                    "copying {} bytes outside segment boundaries before segment {}",
                    padding.len(),
                    segment.name().unwrap_or("<unknown>")
                );
                cursor.write_all(padding)?;
            }
            // The __TEXT segment usually has .fileoff = 0, which has it overlapping with
            // already written data. Allow this special case through.
            Ordering::Greater if segment.fileoff == 0 => {}

            // The writer has overran into this segment. That means we screwed up on a
            // previous loop iteration.
            Ordering::Greater => {
                return Err(AppleCodesignError::MachOWrite(format!(
                    "Mach-O segment corruption: cursor at 0x{:x} but segment begins at 0x{:x} (please report this bug)",
                    cursor.position(),
                    segment.fileoff
                )));
            }
            Ordering::Equal => {}
        }

        assert!(segment.fileoff == 0 || segment.fileoff == cursor.position());

        match segment.name() {
            Ok(SEG_LINKEDIT) => {
                cursor.write_all(
                    macho
                        .linkedit_data_before_signature()
                        .expect("__LINKEDIT segment data should resolve"),
                )?;
                cursor.write_all(signature_data)?;
            }
            _ => {
                // At least the __TEXT segment has .fileoff = 0, which has it
                // overlapping with already written data. So only write segment
                // data new to the writer.
                if segment.fileoff < cursor.position() {
                    if segment.data.is_empty() {
                        continue;
                    }
                    let remaining =
                        &segment.data[cursor.position() as usize..segment.filesize as usize];
                    cursor.write_all(remaining)?;
                } else {
                    cursor.write_all(segment.data)?;
                }
            }
        }
    }

    Ok(cursor.into_inner())
}

Estimate the size in bytes of an embedded code signature.

Examples found in repository?
src/macho_signing.rs (line 309)
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    pub fn write_signed_binary(
        &self,
        settings: &SigningSettings,
        writer: &mut impl Write,
    ) -> Result<(), AppleCodesignError> {
        // Implementing a true streaming writer requires calculating final sizes
        // of all binaries so fat header offsets and sizes can be written first. We take
        // the easy road and buffer individual Mach-O binaries internally.

        let binaries = self
            .machos
            .iter()
            .enumerate()
            .map(|(index, original_macho)| {
                info!("signing Mach-O binary at index {}", index);
                let settings =
                    settings.as_nested_macho_settings(index, original_macho.macho.header.cputype());

                let signature_len = original_macho.estimate_embedded_signature_size(&settings)?;

                // Derive an intermediate Mach-O with placeholder NULLs for signature
                // data so Code Directory digests over the load commands are correct.
                let placeholder_signature_data = b"\0".repeat(signature_len);

                let intermediate_macho_data =
                    create_macho_with_signature(original_macho, &placeholder_signature_data)?;

                // A nice side-effect of this is that it catches bugs if we write malformed Mach-O!
                let intermediate_macho = MachOBinary::parse(&intermediate_macho_data)?;

                let mut signature_data = self.create_superblob(&settings, &intermediate_macho)?;
                info!("total signature size: {} bytes", signature_data.len());

                // The Mach-O writer adjusts load commands based on the signature length. So pad
                // with NULLs to get to our placeholder length.
                match signature_data.len().cmp(&placeholder_signature_data.len()) {
                    Ordering::Greater => {
                        return Err(AppleCodesignError::SignatureDataTooLarge);
                    }
                    Ordering::Equal => {}
                    Ordering::Less => {
                        signature_data.extend_from_slice(
                            &b"\0".repeat(placeholder_signature_data.len() - signature_data.len()),
                        );
                    }
                }

                create_macho_with_signature(&intermediate_macho, &signature_data)
            })
            .collect::<Result<Vec<_>, AppleCodesignError>>()?;

        if binaries.len() > 1 {
            create_universal_macho(writer, binaries.iter().map(|x| x.as_slice()))?;
        } else {
            writer.write_all(&binaries[0])?;
        }

        Ok(())
    }

Attempt to resolve the mach-o targeting settings.

Examples found in repository?
src/signing_settings.rs (line 759)
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
    pub fn import_settings_from_macho(&mut self, data: &[u8]) -> Result<(), AppleCodesignError> {
        info!("inferring default signing settings from Mach-O binary");

        for macho in MachFile::parse(data)?.into_iter() {
            let index = macho.index.unwrap_or(0);

            let scope_main = SettingsScope::Main;
            let scope_index = SettingsScope::MultiArchIndex(index);
            let scope_arch = SettingsScope::MultiArchCpuType(macho.macho.header.cputype());

            // Older operating system versions don't have support for SHA-256 in
            // signatures. If the minimum version targeting in the binary doesn't
            // support SHA-256, we automatically change the digest targeting settings
            // so the binary will be signed correctly.
            if let Some(targeting) = macho.find_targeting()? {
                let sha256_version = targeting.platform.sha256_digest_support()?;

                if !sha256_version.matches(&targeting.minimum_os_version) {
                    info!(
                        "activating SHA-1 digests because minimum OS target {} is not {}",
                        targeting.minimum_os_version, sha256_version
                    );

                    // This logic is a bit wonky. We want SHA-1 to be present on all binaries
                    // within a fat binary. So if we need SHA-1 mode, we set the setting on the
                    // main scope and then clear any overrides on fat binary scopes so our
                    // settings are canonical.
                    self.set_digest_type(DigestType::Sha1);
                    self.add_extra_digest(scope_main.clone(), DigestType::Sha256);
                    self.extra_digests.remove(&scope_arch);
                    self.extra_digests.remove(&scope_index);
                }
            }

            // The Mach-O can have embedded Info.plist data. Use it if available and not
            // already defined in settings.
            if let Some(info_plist) = macho.embedded_info_plist()? {
                if self.info_plist_data(&scope_main).is_some()
                    || self.info_plist_data(&scope_index).is_some()
                    || self.info_plist_data(&scope_arch).is_some()
                {
                    info!("using Info.plist data from settings");
                } else {
                    info!("preserving Info.plist data already present in Mach-O");
                    self.set_info_plist_data(scope_index.clone(), info_plist);
                }
            }

            if let Some(sig) = macho.code_signature()? {
                if let Some(cd) = sig.code_directory()? {
                    if self.binary_identifier(&scope_main).is_some()
                        || self.binary_identifier(&scope_index).is_some()
                        || self.binary_identifier(&scope_arch).is_some()
                    {
                        info!("using binary identifier from settings");
                    } else {
                        info!("preserving existing binary identifier in Mach-O");
                        self.set_binary_identifier(scope_index.clone(), cd.ident);
                    }

                    if self.team_id.contains_key(&scope_main)
                        || self.team_id.contains_key(&scope_index)
                        || self.team_id.contains_key(&scope_arch)
                    {
                        info!("using team ID from settings");
                    } else if let Some(team_id) = cd.team_name {
                        info!("preserving team ID in existing Mach-O signature");
                        self.team_id
                            .insert(scope_index.clone(), team_id.to_string());
                    }

                    if self.code_signature_flags(&scope_main).is_some()
                        || self.code_signature_flags(&scope_index).is_some()
                        || self.code_signature_flags(&scope_arch).is_some()
                    {
                        info!("using code signature flags from settings");
                    } else if !cd.flags.is_empty() {
                        info!("preserving code signature flags in existing Mach-O signature");
                        self.set_code_signature_flags(scope_index.clone(), cd.flags);
                    }

                    if self.runtime_version(&scope_main).is_some()
                        || self.runtime_version(&scope_index).is_some()
                        || self.runtime_version(&scope_arch).is_some()
                    {
                        info!("using runtime version from settings");
                    } else if let Some(version) = cd.runtime {
                        info!("preserving runtime version in existing Mach-O signature");
                        self.set_runtime_version(
                            scope_index.clone(),
                            parse_version_nibbles(version),
                        );
                    }
                }

                if let Some(entitlements) = sig.entitlements()? {
                    if self.entitlements_plist(&scope_main).is_some()
                        || self.entitlements_plist(&scope_index).is_some()
                        || self.entitlements_plist(&scope_arch).is_some()
                    {
                        info!("using entitlements from settings");
                    } else {
                        info!("preserving existing entitlements in Mach-O");
                        self.set_entitlements_xml(
                            SettingsScope::MultiArchIndex(index),
                            entitlements.as_str(),
                        )?;
                    }
                }
            }
        }

        Ok(())
    }
More examples
Hide additional examples
src/macho_signing.rs (line 417)
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    pub fn create_code_directory(
        &self,
        settings: &SigningSettings,
        macho: &MachOBinary,
    ) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
        // TODO support defining or filling in proper values for fields with
        // static values.

        let target = macho.find_targeting()?;

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

        let mut flags = CodeSignatureFlags::empty();

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

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

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

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

        let platform = 0;
        let page_size = 4096u32;

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

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

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

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

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

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

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

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

        let mut special_hashes = HashMap::new();

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

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

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

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

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

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

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

        Ok(cd)
    }
src/bundle_signing.rs (line 480)
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
    pub fn write_signed_bundle(
        &self,
        dest_dir: impl AsRef<Path>,
        settings: &SigningSettings,
    ) -> Result<DirectoryBundle, AppleCodesignError> {
        let dest_dir = dest_dir.as_ref();

        warn!(
            "signing bundle at {} into {}",
            self.bundle.root_dir().display(),
            dest_dir.display()
        );

        // Frameworks are a bit special.
        //
        // Modern frameworks typically have a `Versions/` directory containing directories
        // with the actual frameworks. These are the actual directories that are signed - not
        // the top-most directory. In fact, the top-most `.framework` directory doesn't have any
        // code signature elements at all and can effectively be ignored as far as signing
        // is concerned.
        //
        // But even if there is a `Versions/` directory with nested bundles to sign, the top-level
        // directory may have some symlinks. And those need to be preserved. In addition, there
        // may be symlinks in `Versions/`. `Versions/Current` is common.
        //
        // Of course, if there is no `Versions/` directory, the top-level directory could be
        // a valid framework warranting signing.
        if self.bundle.package_type() == BundlePackageType::Framework {
            if self.bundle.root_dir().join("Versions").is_dir() {
                warn!("found a versioned framework; each version will be signed as its own bundle");

                // But we still need to preserve files (hopefully just symlinks) outside the
                // nested bundles under `Versions/`. Since we don't nest into child bundles
                // here, it should be safe to handle each encountered file.
                let handler = SingleBundleHandler {
                    dest_dir: dest_dir.to_path_buf(),
                    settings,
                };

                for file in self
                    .bundle
                    .files(false)
                    .map_err(AppleCodesignError::DirectoryBundle)?
                {
                    handler.install_file(&file)?;
                }

                return DirectoryBundle::new_from_path(dest_dir)
                    .map_err(AppleCodesignError::DirectoryBundle);
            } else {
                warn!("found an unversioned framework; signing like normal");
            }
        }

        let dest_dir_root = dest_dir.to_path_buf();

        let dest_dir = if self.bundle.shallow() {
            dest_dir_root.clone()
        } else {
            dest_dir.join("Contents")
        };

        self.bundle
            .identifier()
            .map_err(AppleCodesignError::DirectoryBundle)?
            .ok_or_else(|| AppleCodesignError::BundleNoIdentifier(self.bundle.info_plist_path()))?;

        let mut resources_digests = settings.all_digests(SettingsScope::Main);

        // State in the main executable can influence signing settings of the bundle. So examine
        // it first.

        let main_exe = self
            .bundle
            .files(false)
            .map_err(AppleCodesignError::DirectoryBundle)?
            .into_iter()
            .find(|f| matches!(f.is_main_executable(), Ok(true)));

        if let Some(exe) = &main_exe {
            let macho_data = std::fs::read(exe.absolute_path())?;
            let mach = MachFile::parse(&macho_data)?;

            for macho in mach.iter_macho() {
                if let Some(targeting) = macho.find_targeting()? {
                    let sha256_version = targeting.platform.sha256_digest_support()?;

                    if !sha256_version.matches(&targeting.minimum_os_version)
                        && resources_digests != vec![DigestType::Sha1, DigestType::Sha256]
                    {
                        info!("main executable targets OS requiring SHA-1 signatures; activating SHA-1 + SHA-256 signing");
                        resources_digests = vec![DigestType::Sha1, DigestType::Sha256];
                        break;
                    }
                }
            }
        }

        warn!("collecting code resources files");

        // The set of rules to use is determined by whether the bundle *can* have a
        // `Resources/`, not whether it necessarily does. The exact rules for this are not
        // known. Essentially we want to test for the result of CFBundleCopyResourcesDirectoryURL().
        // We assume that we can use the resources rules when there is a `Resources` directory
        // (this seems obvious!) or when the bundle isn't shallow, as a non-shallow bundle should
        // be an app bundle and app bundles can always have resources (we think).
        let mut resources_builder =
            if self.bundle.resolve_path("Resources").is_dir() || !self.bundle.shallow() {
                CodeResourcesBuilder::default_resources_rules()?
            } else {
                CodeResourcesBuilder::default_no_resources_rules()?
            };

        // Ensure emitted digests match what we're configured to emit.
        resources_builder.set_digests(resources_digests.into_iter());

        // Exclude code signature files we'll write.
        resources_builder.add_exclusion_rule(CodeResourcesRule::new("^_CodeSignature/")?.exclude());
        // Ignore notarization ticket.
        resources_builder.add_exclusion_rule(CodeResourcesRule::new("^CodeResources$")?.exclude());

        let handler = SingleBundleHandler {
            dest_dir: dest_dir_root.clone(),
            settings,
        };

        let mut info_plist_data = None;

        // Iterate files in this bundle and register as code resources.
        //
        // Traversing into nested bundles seems wrong but it is correct. The resources builder
        // has rules to determine whether to process a path and assuming the rules and evaluation
        // of them is correct, it is able to decide for itself how to handle a path.
        //
        // Furthermore, this behavior is needed as bundles can encapsulate signatures for nested
        // bundles. For example, you could have a framework bundle with an embedded app bundle in
        // `Resources/MyApp.app`! In this case, the framework's CodeResources encapsulates the
        // content of `Resources/My.app` per the processing rules.
        for file in self
            .bundle
            .files(true)
            .map_err(AppleCodesignError::DirectoryBundle)?
        {
            // The main executable is special and handled below.
            if file
                .is_main_executable()
                .map_err(AppleCodesignError::DirectoryBundle)?
            {
                continue;
            } else if file.is_info_plist() {
                // The Info.plist is digested specially. But it may also be handled by
                // the resources handler. So always feed it through.
                info!(
                    "{} is the Info.plist file; handling specially",
                    file.relative_path().display()
                );
                resources_builder.process_file(&file, &handler)?;
                info_plist_data = Some(std::fs::read(file.absolute_path())?);
            } else {
                resources_builder.process_file(&file, &handler)?;
            }
        }

        // Seal code directory digests of any nested bundles.
        //
        // Apple's tooling seems to only do this for some bundle type combinations. I'm
        // not yet sure what the complete heuristic is. But we observed that frameworks
        // don't appear to include digests of any nested app bundles. So we add that
        // exclusion. iOS bundles don't seem to include digests for nested bundles either.
        // We should figure out what the actual rules here...
        if !self.bundle.shallow() {
            let dest_bundle = DirectoryBundle::new_from_path(&dest_dir)
                .map_err(AppleCodesignError::DirectoryBundle)?;

            for (rel_path, nested_bundle) in dest_bundle
                .nested_bundles(false)
                .map_err(AppleCodesignError::DirectoryBundle)?
            {
                resources_builder.process_nested_bundle(&rel_path, &nested_bundle)?;
            }
        }

        // The resources are now sealed. Write out that XML file.
        let code_resources_path = dest_dir.join("_CodeSignature").join("CodeResources");
        warn!(
            "writing sealed resources to {}",
            code_resources_path.display()
        );
        std::fs::create_dir_all(code_resources_path.parent().unwrap())?;
        let mut resources_data = Vec::<u8>::new();
        resources_builder.write_code_resources(&mut resources_data)?;

        {
            let mut fh = std::fs::File::create(&code_resources_path)?;
            fh.write_all(&resources_data)?;
        }

        // Seal the main executable.
        if let Some(exe) = main_exe {
            warn!("signing main executable {}", exe.relative_path().display());

            let macho_data = std::fs::read(exe.absolute_path())?;
            let signer = MachOSigner::new(&macho_data)?;

            let mut settings = settings.clone();

            // The identifier for the main executable is defined in the bundle's Info.plist.
            if let Some(ident) = self
                .bundle
                .identifier()
                .map_err(AppleCodesignError::DirectoryBundle)?
            {
                info!("setting main executable binary identifier to {} (derived from CFBundleIdentifier in Info.plist)", ident);
                settings.set_binary_identifier(SettingsScope::Main, ident);
            } else {
                info!("unable to determine binary identifier from bundle's Info.plist (CFBundleIdentifier not set?)");
            }

            settings.import_settings_from_macho(&macho_data)?;

            settings.set_code_resources_data(SettingsScope::Main, resources_data);

            if let Some(info_plist_data) = info_plist_data {
                settings.set_info_plist_data(SettingsScope::Main, info_plist_data);
            }

            let mut new_data = Vec::<u8>::with_capacity(macho_data.len() + 2_usize.pow(17));
            signer.write_signed_binary(&settings, &mut new_data)?;

            let dest_path = dest_dir_root.join(exe.relative_path());
            info!("writing signed main executable to {}", dest_path.display());
            write_macho_file(exe.absolute_path(), &dest_path, &new_data)?;
        } else {
            warn!("bundle has no main executable to sign specially");
        }

        DirectoryBundle::new_from_path(&dest_dir_root).map_err(AppleCodesignError::DirectoryBundle)
    }
src/cli.rs (line 1496)
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
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(())
}

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