Struct apple_codesign::CodeDirectoryBlob
source · pub struct CodeDirectoryBlob<'a> {Show 25 fields
pub version: u32,
pub flags: CodeSignatureFlags,
pub code_limit: u32,
pub digest_size: u8,
pub digest_type: DigestType,
pub platform: u8,
pub page_size: u32,
pub spare2: u32,
pub scatter_offset: Option<u32>,
pub spare3: Option<u32>,
pub code_limit_64: Option<u64>,
pub exec_seg_base: Option<u64>,
pub exec_seg_limit: Option<u64>,
pub exec_seg_flags: Option<ExecutableSegmentFlags>,
pub runtime: Option<u32>,
pub pre_encrypt_offset: Option<u32>,
pub linkage_hash_type: Option<u8>,
pub linkage_truncated: Option<u8>,
pub spare4: Option<u16>,
pub linkage_offset: Option<u32>,
pub linkage_size: Option<u32>,
pub ident: Cow<'a, str>,
pub team_name: Option<Cow<'a, str>>,
pub code_digests: Vec<Digest<'a>>,
pub special_digests: HashMap<CodeSigningSlot, Digest<'a>>,
}
Expand description
Represents a code directory blob entry.
This struct is versioned and has been extended over time.
The struct here represents a superset of all fields in all versions.
The parser will set Option<T>
fields to None
for instances
where the version is lower than the version that field was introduced in.
Fields§
§version: u32
Compatibility version.
flags: CodeSignatureFlags
Setup and mode flags.
code_limit: u32
Limit to main image signature range.
This is the file-level offset to stop digesting code data at.
It likely corresponds to the file-offset offset where the
embedded signature data starts in the __LINKEDIT
segment.
digest_size: u8
Size of each slot/code digest in bytes.
digest_type: DigestType
Type of content digest being used.
platform: u8
Platform identifier. 0 if not platform binary.
page_size: u32
Page size in bytes. (stored as log u8)
spare2: u32
Unused (must be 0).
scatter_offset: Option<u32>
Offset of optional scatter vector.
spare3: Option<u32>
Unused (must be 0).
code_limit_64: Option<u64>
Limit to main image signature range, 64 bits.
exec_seg_base: Option<u64>
Offset of executable segment.
exec_seg_limit: Option<u64>
Limit of executable segment.
exec_seg_flags: Option<ExecutableSegmentFlags>
Executable segment flags.
runtime: Option<u32>
§pre_encrypt_offset: Option<u32>
§linkage_hash_type: Option<u8>
§linkage_truncated: Option<u8>
§spare4: Option<u16>
§linkage_offset: Option<u32>
§linkage_size: Option<u32>
§ident: Cow<'a, str>
§team_name: Option<Cow<'a, str>>
§code_digests: Vec<Digest<'a>>
§special_digests: HashMap<CodeSigningSlot, Digest<'a>>
Implementations§
source§impl<'a> CodeDirectoryBlob<'a>
impl<'a> CodeDirectoryBlob<'a>
sourcepub fn slot_digests(&self) -> &HashMap<CodeSigningSlot, Digest<'a>>
pub fn slot_digests(&self) -> &HashMap<CodeSigningSlot, Digest<'a>>
Obtain the mapping of slots to digests.
Examples found in repository?
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
fn try_from(cd: CodeDirectoryBlob<'a>) -> Result<Self, Self::Error> {
let mut temp = cd
.slot_digests()
.iter()
.map(|(slot, digest)| (slot, digest.as_hex()))
.collect::<Vec<_>>();
temp.sort_by(|(a, _), (b, _)| a.cmp(b));
let slot_digests = temp
.into_iter()
.map(|(slot, digest)| format!("{slot:?}: {digest}"))
.collect::<Vec<_>>();
Ok(Self {
version: format!("0x{:X}", cd.version),
flags: format!("{:?}", cd.flags),
identifier: cd.ident.to_string(),
team_name: cd.team_name.map(|x| x.to_string()),
signed_entity_size: cd.code_limit as _,
digest_type: format!("{}", cd.digest_type),
platform: cd.platform,
executable_segment_flags: cd.exec_seg_flags.map(|x| format!("{x:?}")),
runtime_version: cd
.runtime
.map(|x| format!("{}", crate::macho::parse_version_nibbles(x))),
code_digests_count: cd.code_digests.len(),
slot_digests,
})
}
More examples
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
}
sourcepub fn slot_digest(&self, slot: CodeSigningSlot) -> Option<&Digest<'a>>
pub fn slot_digest(&self, slot: CodeSigningSlot) -> Option<&Digest<'a>>
Obtain the recorded digest for a given CodeSigningSlot.
sourcepub fn set_slot_digest(
&mut self,
slot: CodeSigningSlot,
digest: impl Into<Digest<'a>>
) -> Result<(), AppleCodesignError>
pub fn set_slot_digest(
&mut self,
slot: CodeSigningSlot,
digest: impl Into<Digest<'a>>
) -> Result<(), AppleCodesignError>
Set the digest for a given slot.
Examples found in repository?
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
pub fn add_code_directory(
&mut self,
cd_slot: CodeSigningSlot,
mut cd: CodeDirectoryBlob<'a>,
) -> Result<&CodeDirectoryBlob, AppleCodesignError> {
if matches!(self.state, BlobsState::SignatureAdded) {
return Err(AppleCodesignError::SignatureBuilder(
"cannot add code directory after signature data added",
));
}
for (slot, blob) in &self.blobs {
// Not all slots are expressible in the cd specials list!
if !slot.is_code_directory_specials_expressible() {
continue;
}
let digest = blob.digest_with(cd.digest_type)?;
cd.set_slot_digest(*slot, digest)?;
}
self.blobs.insert(cd_slot, cd.into());
self.state = BlobsState::CodeDirectoryAdded;
Ok(self.code_directory().expect("we just inserted this key"))
}
More examples
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
pub fn create_code_directory<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
let reader = DmgReader::new(fh)?;
let mut flags = settings
.code_signature_flags(SettingsScope::Main)
.unwrap_or_else(CodeSignatureFlags::empty);
if settings.signing_key().is_some() {
flags -= CodeSignatureFlags::ADHOC;
} else {
flags |= CodeSignatureFlags::ADHOC;
}
warn!("using code signature flags: {:?}", flags);
let ident = Cow::Owned(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
warn!("using identifier {}", ident);
let code_hashes = vec![reader.digest_content_with(*settings.digest_type(), fh)?];
let koly_digest = reader
.koly()
.digest_for_code_directory(*settings.digest_type())?;
let mut cd = CodeDirectoryBlob {
version: 0x20100,
flags,
code_limit: reader.koly().offset_after_plist() as u32,
digest_size: settings.digest_type().hash_len()? as u8,
digest_type: *settings.digest_type(),
page_size: 1,
ident,
code_digests: code_hashes,
..Default::default()
};
cd.set_slot_digest(CodeSigningSlot::RepSpecific, koly_digest)?;
Ok(cd)
}
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)
}
sourcepub fn adjust_version(&mut self, target: Option<MachoTarget>) -> u32
pub fn adjust_version(&mut self, target: Option<MachoTarget>) -> u32
Adjust the version of the data structure according to what fields are set.
Returns the old version.
Examples found in repository?
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)
}
sourcepub fn clear_newer_fields(&mut self)
pub fn clear_newer_fields(&mut self)
Clears optional fields that are newer than the current version.
The C structure is versioned and our Rust struct is a superset of all versions. While our serializer should omit too new fields for a given version, it is possible for some optional fields to be set when they wouldn’t get serialized.
Calling this function will set fields not present in the current version to None.
Examples found in repository?
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)
}
pub fn to_owned(&self) -> CodeDirectoryBlob<'static>
Trait Implementations§
source§impl<'a> Blob<'a> for CodeDirectoryBlob<'a>
impl<'a> Blob<'a> for CodeDirectoryBlob<'a>
source§fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>
source§fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>
source§fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError>
fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError>
source§fn digest_with(
&self,
hash_type: DigestType
) -> Result<Vec<u8>, AppleCodesignError>
fn digest_with(
&self,
hash_type: DigestType
) -> Result<Vec<u8>, AppleCodesignError>
source§impl<'a> Debug for CodeDirectoryBlob<'a>
impl<'a> Debug for CodeDirectoryBlob<'a>
source§impl<'a> Default for CodeDirectoryBlob<'a>
impl<'a> Default for CodeDirectoryBlob<'a>
source§fn default() -> CodeDirectoryBlob<'a>
fn default() -> CodeDirectoryBlob<'a>
source§impl<'a> From<CodeDirectoryBlob<'a>> for BlobData<'a>
impl<'a> From<CodeDirectoryBlob<'a>> for BlobData<'a>
source§fn from(b: CodeDirectoryBlob<'a>) -> Self
fn from(b: CodeDirectoryBlob<'a>) -> Self
source§impl<'a> TryFrom<CodeDirectoryBlob<'a>> for CodeDirectory
impl<'a> TryFrom<CodeDirectoryBlob<'a>> for CodeDirectory
§type Error = AppleCodesignError
type Error = AppleCodesignError
Auto Trait Implementations§
impl<'a> RefUnwindSafe for CodeDirectoryBlob<'a>
impl<'a> Send for CodeDirectoryBlob<'a>
impl<'a> Sync for CodeDirectoryBlob<'a>
impl<'a> Unpin for CodeDirectoryBlob<'a>
impl<'a> UnwindSafe for CodeDirectoryBlob<'a>
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§impl<T> Conv for T
impl<T> Conv for T
§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
self
, then passes self.as_ref()
into the pipe function.§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
self
, then passes self.as_mut()
into the pipe
function.§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Borrow<B>
of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
BorrowMut<B>
of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
AsRef<R>
view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
AsMut<R>
view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
Deref::Target
of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
Deref::Target
of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
.tap_borrow()
only in debug builds, and is erased in release
builds.§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
.tap_ref()
only in debug builds, and is erased in release
builds.§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
.tap_ref_mut()
only in debug builds, and is erased in release
builds.