Struct apple_codesign::SigningSettings
source · pub struct SigningSettings<'key> { /* private fields */ }Expand description
Represents code signing settings.
This type holds settings related to a single logical signing operation. Some settings (such as the signing key-pair are global). Other settings (such as the entitlements or designated requirement) can be applied on a more granular, scoped basis. The scoping of these lower-level settings is controlled via SettingsScope. If a setting is specified with a scope, it only applies to that scope. See that type’s documentation for more.
An instance of this type is bound to a signing operation. When the signing operation traverses into nested primitives (e.g. when traversing into the individual Mach-O binaries in a fat/universal binary or when traversing into nested bundles or non-main binaries within a bundle), a new instance of this type is transparently constructed by merging global settings with settings for the target scope. This allows granular control over which signing settings apply to which entity and enables a signing operation over a complex primitive to be configured/performed via a single SigningSettings and signing operation.
Implementations§
source§impl<'key> SigningSettings<'key>
impl<'key> SigningSettings<'key>
sourcepub fn digest_type(&self) -> &DigestType
pub fn digest_type(&self) -> &DigestType
Obtain the digest type to use.
Examples found in repository?
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
pub fn create_code_directory<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
let reader = DmgReader::new(fh)?;
let mut flags = settings
.code_signature_flags(SettingsScope::Main)
.unwrap_or_else(CodeSignatureFlags::empty);
if settings.signing_key().is_some() {
flags -= CodeSignatureFlags::ADHOC;
} else {
flags |= CodeSignatureFlags::ADHOC;
}
warn!("using code signature flags: {:?}", flags);
let ident = Cow::Owned(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
warn!("using identifier {}", ident);
let code_hashes = vec![reader.digest_content_with(*settings.digest_type(), fh)?];
let koly_digest = reader
.koly()
.digest_for_code_directory(*settings.digest_type())?;
let mut cd = CodeDirectoryBlob {
version: 0x20100,
flags,
code_limit: reader.koly().offset_after_plist() as u32,
digest_size: settings.digest_type().hash_len()? as u8,
digest_type: *settings.digest_type(),
page_size: 1,
ident,
code_digests: code_hashes,
..Default::default()
};
cd.set_slot_digest(CodeSigningSlot::RepSpecific, koly_digest)?;
Ok(cd)
}More examples
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)
}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 set_digest_type(&mut self, digest_type: DigestType)
pub fn set_digest_type(&mut self, digest_type: DigestType)
Set the content digest to use.
The default is SHA-256. Changing this to SHA-1 can weaken security of digital signatures and may prevent the binary from running in environments that enforce more modern signatures.
Examples found in repository?
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
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()
}More examples
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(())
}2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn signing_key(
&self
) -> Option<(&'key dyn KeyInfoSigner, &CapturedX509Certificate)>
pub fn signing_key(
&self
) -> Option<(&'key dyn KeyInfoSigner, &CapturedX509Certificate)>
Obtain the signing key to use.
Examples found in repository?
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
pub fn create_superblob<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<Vec<u8>, AppleCodesignError> {
let mut builder = EmbeddedSignatureBuilder::default();
for (slot, blob) in self.create_special_blobs()? {
builder.add_blob(slot, blob)?;
}
builder.add_code_directory(
CodeSigningSlot::CodeDirectory,
self.create_code_directory(settings, fh)?,
)?;
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 code directory data structure that is part of the embedded signature.
///
/// This won't be the final data structure state that is serialized, as it may be
/// amended to in other functions.
pub fn create_code_directory<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
let reader = DmgReader::new(fh)?;
let mut flags = settings
.code_signature_flags(SettingsScope::Main)
.unwrap_or_else(CodeSignatureFlags::empty);
if settings.signing_key().is_some() {
flags -= CodeSignatureFlags::ADHOC;
} else {
flags |= CodeSignatureFlags::ADHOC;
}
warn!("using code signature flags: {:?}", flags);
let ident = Cow::Owned(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
warn!("using identifier {}", ident);
let code_hashes = vec![reader.digest_content_with(*settings.digest_type(), fh)?];
let koly_digest = reader
.koly()
.digest_for_code_directory(*settings.digest_type())?;
let mut cd = CodeDirectoryBlob {
version: 0x20100,
flags,
code_limit: reader.koly().offset_after_plist() as u32,
digest_size: settings.digest_type().hash_len()? as u8,
digest_type: *settings.digest_type(),
page_size: 1,
ident,
code_digests: code_hashes,
..Default::default()
};
cd.set_slot_digest(CodeSigningSlot::RepSpecific, koly_digest)?;
Ok(cd)
}More examples
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
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)
}
/// Create blobs that need to be written given the current configuration.
///
/// This emits all blobs except `CodeDirectory` and `Signature`, which are
/// special since they are derived from the blobs emitted here.
///
/// The goal of this function is to emit data to facilitate the creation of
/// a `CodeDirectory`, which requires hashing blobs.
pub fn create_special_blobs(
&self,
settings: &SigningSettings,
is_executable: bool,
) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
let mut res = Vec::new();
let mut requirements = CodeRequirements::default();
match settings.designated_requirement(SettingsScope::Main) {
DesignatedRequirementMode::Auto => {
// If we are using an Apple-issued cert, this should automatically
// derive appropriate designated requirements.
if let Some((_, cert)) = settings.signing_key() {
info!("attempting to derive code requirements from signing certificate");
let identifier = Some(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
if let Some(expr) = derive_designated_requirements(cert, identifier)? {
requirements.push(expr);
}
}
}
DesignatedRequirementMode::Explicit(exprs) => {
info!("using provided code requirements");
for expr in exprs {
requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
}
}
}
// Always emit a RequirementSet blob, even if empty. Without it, validation fails
// with `the sealed resource directory is invalid`.
let mut blob = RequirementSetBlob::default();
if !requirements.is_empty() {
info!("code requirements: {}", requirements);
requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
}
res.push((CodeSigningSlot::RequirementSet, blob.into()));
if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
info!("adding entitlements XML");
let blob = EntitlementsBlob::from_string(&entitlements);
res.push((CodeSigningSlot::Entitlements, blob.into()));
}
// The DER encoded entitlements weren't always present in the signature. The feature
// appears to have been introduced in macOS 10.14 and is the default behavior as of
// macOS 12 "when signing for all platforms." `codesign` appears to add the DER
// representation whenever entitlements are present, but only if the current binary is
// an executable (.filetype == MH_EXECUTE).
if is_executable {
if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
info!("adding entitlements DER");
let blob = EntitlementsDerBlob::from_plist(value)?;
res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
}
}
Ok(res)
}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
pub fn sign_xar(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
// The XAR can get corrupted if we sign into place. So we always go through a temporary
// file. We could potentially avoid the overhead if we're not signing in place...
let output_path_temp =
output_path.with_file_name(if let Some(file_name) = output_path.file_name() {
file_name.to_string_lossy().to_string() + ".tmp"
} else {
"xar.tmp".to_string()
});
warn!(
"signing XAR pkg installer at {} to {}",
input_path.display(),
output_path_temp.display()
);
let (signing_key, signing_cert) = self
.settings
.signing_key()
.ok_or(AppleCodesignError::XarNoAdhoc)?;
{
let reader = XarReader::new(File::open(input_path)?)?;
let mut signer = XarSigner::new(reader);
let mut fh = File::create(&output_path_temp)?;
signer.sign(
&mut fh,
signing_key,
signing_cert,
self.settings.time_stamp_url(),
self.settings.certificate_chain().iter().cloned(),
)?;
}
if output_path.exists() {
warn!("removing existing {}", output_path.display());
std::fs::remove_file(output_path)?;
}
warn!(
"renaming {} -> {}",
output_path_temp.display(),
output_path.display()
);
std::fs::rename(&output_path_temp, output_path)?;
Ok(())
}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)
}sourcepub fn set_signing_key(
&mut self,
private: &'key dyn KeyInfoSigner,
public: CapturedX509Certificate
)
pub fn set_signing_key(
&mut self,
private: &'key dyn KeyInfoSigner,
public: CapturedX509Certificate
)
Set the signing key-pair for producing a cryptographic signature over code.
If this is not called, signing will lack a cryptographic signature and will only contain digests of content. This is known as “ad-hoc” mode. Binaries lacking a cryptographic signature or signed without a key-pair issued/signed by Apple may not run in all environments.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn certificate_chain(&self) -> &[CapturedX509Certificate]
pub fn certificate_chain(&self) -> &[CapturedX509Certificate]
Obtain the certificate chain.
Examples found in repository?
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
pub fn create_superblob<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<Vec<u8>, AppleCodesignError> {
let mut builder = EmbeddedSignatureBuilder::default();
for (slot, blob) in self.create_special_blobs()? {
builder.add_blob(slot, blob)?;
}
builder.add_code_directory(
CodeSigningSlot::CodeDirectory,
self.create_code_directory(settings, fh)?,
)?;
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()
}More examples
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
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()
}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
pub fn sign_xar(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
// The XAR can get corrupted if we sign into place. So we always go through a temporary
// file. We could potentially avoid the overhead if we're not signing in place...
let output_path_temp =
output_path.with_file_name(if let Some(file_name) = output_path.file_name() {
file_name.to_string_lossy().to_string() + ".tmp"
} else {
"xar.tmp".to_string()
});
warn!(
"signing XAR pkg installer at {} to {}",
input_path.display(),
output_path_temp.display()
);
let (signing_key, signing_cert) = self
.settings
.signing_key()
.ok_or(AppleCodesignError::XarNoAdhoc)?;
{
let reader = XarReader::new(File::open(input_path)?)?;
let mut signer = XarSigner::new(reader);
let mut fh = File::create(&output_path_temp)?;
signer.sign(
&mut fh,
signing_key,
signing_cert,
self.settings.time_stamp_url(),
self.settings.certificate_chain().iter().cloned(),
)?;
}
if output_path.exists() {
warn!("removing existing {}", output_path.display());
std::fs::remove_file(output_path)?;
}
warn!(
"renaming {} -> {}",
output_path_temp.display(),
output_path.display()
);
std::fs::rename(&output_path_temp, output_path)?;
Ok(())
}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)
}sourcepub fn chain_apple_certificates(
&mut self
) -> Option<Vec<CapturedX509Certificate>>
pub fn chain_apple_certificates(
&mut self
) -> Option<Vec<CapturedX509Certificate>>
Attempt to chain Apple CA certificates from a loaded Apple signed signing key.
If you are calling set_signing_key(), you probably want to call this immediately
afterwards, as it will automatically register Apple CA certificates if you are
using an Apple signed code signing certificate.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn chain_certificate(&mut self, cert: CapturedX509Certificate)
pub fn chain_certificate(&mut self, cert: CapturedX509Certificate)
Add a parsed certificate to the signing certificate chain.
When producing a cryptographic signature (see SigningSettings::set_signing_key), information about the signing key-pair is included in the signature. The signing key’s public certificate is always included. This function can be used to define additional X.509 public certificates to include. Typically, the signing chain of the signing key-pair up until the root Certificate Authority (CA) is added so clients have access to the full certificate chain for validation purposes.
This setting has no effect if SigningSettings::set_signing_key is not called.
Examples found in repository?
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
pub fn chain_certificate_der(
&mut self,
data: impl AsRef<[u8]>,
) -> Result<(), AppleCodesignError> {
self.chain_certificate(CapturedX509Certificate::from_der(data.as_ref())?);
Ok(())
}
/// Add a PEM encoded X.509 public certificate to the signing certificate chain.
///
/// This is like [Self::chain_certificate] except the certificate is
/// specified as PEM encoded data. This is a human readable string like
/// `-----BEGIN CERTIFICATE-----` and is a common method for encoding certificate data.
/// (PEM is effectively base64 encoded DER data.)
///
/// Only a single certificate is read from the PEM data.
pub fn chain_certificate_pem(
&mut self,
data: impl AsRef<[u8]>,
) -> Result<(), AppleCodesignError> {
self.chain_certificate(CapturedX509Certificate::from_pem(data.as_ref())?);
Ok(())
}More examples
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn chain_certificate_der(
&mut self,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
pub fn chain_certificate_der(
&mut self,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
Add a DER encoded X.509 public certificate to the signing certificate chain.
This is like Self::chain_certificate except the certificate data is provided in its binary, DER encoded form.
sourcepub fn chain_certificate_pem(
&mut self,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
pub fn chain_certificate_pem(
&mut self,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
Add a PEM encoded X.509 public certificate to the signing certificate chain.
This is like Self::chain_certificate except the certificate is
specified as PEM encoded data. This is a human readable string like
-----BEGIN CERTIFICATE----- and is a common method for encoding certificate data.
(PEM is effectively base64 encoded DER data.)
Only a single certificate is read from the PEM data.
sourcepub fn time_stamp_url(&self) -> Option<&Url>
pub fn time_stamp_url(&self) -> Option<&Url>
Obtain the Time-Stamp Protocol server URL.
Examples found in repository?
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
pub fn create_superblob<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<Vec<u8>, AppleCodesignError> {
let mut builder = EmbeddedSignatureBuilder::default();
for (slot, blob) in self.create_special_blobs()? {
builder.add_blob(slot, blob)?;
}
builder.add_code_directory(
CodeSigningSlot::CodeDirectory,
self.create_code_directory(settings, fh)?,
)?;
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()
}More examples
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
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()
}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
pub fn sign_xar(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
// The XAR can get corrupted if we sign into place. So we always go through a temporary
// file. We could potentially avoid the overhead if we're not signing in place...
let output_path_temp =
output_path.with_file_name(if let Some(file_name) = output_path.file_name() {
file_name.to_string_lossy().to_string() + ".tmp"
} else {
"xar.tmp".to_string()
});
warn!(
"signing XAR pkg installer at {} to {}",
input_path.display(),
output_path_temp.display()
);
let (signing_key, signing_cert) = self
.settings
.signing_key()
.ok_or(AppleCodesignError::XarNoAdhoc)?;
{
let reader = XarReader::new(File::open(input_path)?)?;
let mut signer = XarSigner::new(reader);
let mut fh = File::create(&output_path_temp)?;
signer.sign(
&mut fh,
signing_key,
signing_cert,
self.settings.time_stamp_url(),
self.settings.certificate_chain().iter().cloned(),
)?;
}
if output_path.exists() {
warn!("removing existing {}", output_path.display());
std::fs::remove_file(output_path)?;
}
warn!(
"renaming {} -> {}",
output_path_temp.display(),
output_path.display()
);
std::fs::rename(&output_path_temp, output_path)?;
Ok(())
}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)
}sourcepub fn set_time_stamp_url(
&mut self,
url: impl IntoUrl
) -> Result<(), AppleCodesignError>
pub fn set_time_stamp_url(
&mut self,
url: impl IntoUrl
) -> Result<(), AppleCodesignError>
Set the Time-Stamp Protocol server URL to use to generate a Time-Stamp Token.
When set and a signing key-pair is defined, the server will be contacted during signing and a Time-Stamp Token will be embedded in the cryptographic signature. This Time-Stamp Token is a cryptographic proof that someone in possession of the signing key-pair produced the cryptographic signature at a given time. It facilitates validation of the signing time via an independent (presumably trusted) entity.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn team_id(&self) -> Option<&str>
pub fn team_id(&self) -> Option<&str>
Obtain the team identifier for signed binaries.
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 set_team_id(&mut self, value: impl ToString)
pub fn set_team_id(&mut self, value: impl ToString)
Set the team identifier for signed binaries.
Examples found in repository?
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
pub fn set_team_id_from_signing_certificate(&mut self) -> Option<&str> {
if let Some((_, cert)) = &self.signing_key {
if let Some(team_id) = cert.apple_team_id() {
self.set_team_id(team_id);
Some(
self.team_id
.get(&SettingsScope::Main)
.expect("we just set a team id"),
)
} else {
None
}
} else {
None
}
}More examples
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn set_team_id_from_signing_certificate(&mut self) -> Option<&str>
pub fn set_team_id_from_signing_certificate(&mut self) -> Option<&str>
Attempt to set the team ID from the signing certificate.
Apple signing certificates have the team ID embedded within the certificate. By calling this method, the team ID embedded within the certificate will be propagated to the code signature.
Callers will typically want to call this after registering the signing certificate with Self::set_signing_key() but before specifying an explicit team ID via Self::set_team_id().
Calling this will replace a registered team IDs if the signing certificate contains a team ID. If no signing certificate is registered or it doesn’t contain a team ID, no changes will be made.
Returns Some if a team ID was set from the signing certificate or None
otherwise.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn path_exclusion_patterns(&self) -> &[Pattern]
pub fn path_exclusion_patterns(&self) -> &[Pattern]
Return relative paths that should be excluded from signing.
Values are glob pattern matches as defined the by glob crate.
Examples found in repository?
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
pub fn write_signed_bundle(
&self,
dest_dir: impl AsRef<Path>,
settings: &SigningSettings,
) -> Result<DirectoryBundle, AppleCodesignError> {
let dest_dir = dest_dir.as_ref();
// We need to sign the leaf-most bundles first since a parent bundle may need
// to record information about the child in its signature.
let mut bundles = self
.bundles
.iter()
.filter_map(|(rel, bundle)| rel.as_ref().map(|rel| (rel, bundle)))
.collect::<Vec<_>>();
// This won't preserve alphabetical order. But since the input was stable, output
// should be deterministic.
bundles.sort_by(|(a, _), (b, _)| b.len().cmp(&a.len()));
warn!(
"signing {} nested bundles in the following order:",
bundles.len()
);
for bundle in &bundles {
warn!("{}", bundle.0);
}
for (rel, nested) in bundles {
let nested_dest_dir = dest_dir.join(rel);
info!(
"entering nested bundle {}",
nested.bundle.root_dir().display(),
);
// If we excluded this bundle from signing, just copy all the files.
if settings
.path_exclusion_patterns()
.iter()
.any(|pattern| pattern.matches(rel))
{
warn!("bundle is in exclusion list; it will be copied instead of signed");
copy_bundle(&nested.bundle, &nested_dest_dir)?;
} else {
nested.write_signed_bundle(
nested_dest_dir,
&settings.as_nested_bundle_settings(rel),
)?;
}
info!(
"leaving nested bundle {}",
nested.bundle.root_dir().display()
);
}
let main = self
.bundles
.get(&None)
.expect("main bundle should have a key");
main.write_signed_bundle(dest_dir, settings)
}sourcepub fn add_path_exclusion(&mut self, v: &str) -> Result<(), AppleCodesignError>
pub fn add_path_exclusion(&mut self, v: &str) -> Result<(), AppleCodesignError>
Add a path to the exclusions list.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn binary_identifier(&self, scope: impl AsRef<SettingsScope>) -> Option<&str>
pub fn binary_identifier(&self, scope: impl AsRef<SettingsScope>) -> Option<&str>
Obtain the binary identifier string for a given scope.
Examples found in repository?
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
pub fn sign_macho(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
warn!("signing {} as a Mach-O binary", input_path.display());
let macho_data = std::fs::read(input_path)?;
let mut settings = self.settings.clone();
settings.import_settings_from_macho(&macho_data)?;
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = input_path
.file_name()
.ok_or_else(|| {
AppleCodesignError::CliGeneralError(
"unable to resolve file name of binary".into(),
)
})?
.to_string_lossy();
warn!("setting binary identifier to {}", identifier);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
warn!("parsing Mach-O");
let signer = MachOSigner::new(&macho_data)?;
let mut macho_data = vec![];
signer.write_signed_binary(&settings, &mut macho_data)?;
warn!("writing Mach-O to {}", output_path.display());
write_macho_file(input_path, output_path, &macho_data)?;
Ok(())
}
/// Sign a `.dmg` file.
pub fn sign_dmg(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
warn!("signing {} as a DMG", input_path.display());
// There must be a binary identifier on the DMG. So try to derive one
// from the filename if one isn't present in the settings.
let mut settings = self.settings.clone();
if settings.binary_identifier(SettingsScope::Main).is_none() {
let file_name = input_path
.file_stem()
.ok_or_else(|| {
AppleCodesignError::CliGeneralError("unable to resolve file name of DMG".into())
})?
.to_string_lossy();
warn!(
"setting binary identifier to {} (derived from file name)",
file_name
);
settings.set_binary_identifier(SettingsScope::Main, file_name);
}
// The DMG signer signs in place because it needs a `File` handle. So if
// the output path is different, copy the DMG first.
// This is not robust same file detection.
if input_path != output_path {
info!(
"copying {} to {} in preparation for signing",
input_path.display(),
output_path.display()
);
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(input_path, output_path)?;
}
let signer = DmgSigner::default();
let mut fh = std::fs::File::options()
.read(true)
.write(true)
.open(output_path)?;
signer.sign_file(&settings, &mut fh)?;
Ok(())
}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)
}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
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError> {
info!("signing Mach-O file {}", file.relative_path().display());
let macho_data = std::fs::read(file.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = self
.settings
.as_bundle_macho_settings(file.relative_path().to_string_lossy().as_ref());
settings.import_settings_from_macho(&macho_data)?;
// If there isn't a defined binary identifier, derive one from the file name so one is set
// and we avoid a signing error due to missing identifier.
// TODO do we need to check the nested Mach-O settings?
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = file
.relative_path()
.file_name()
.expect("failure to extract filename (this should never happen)")
.to_string_lossy();
let identifier = identifier
.strip_suffix(".dylib")
.unwrap_or_else(|| identifier.as_ref());
info!(
"Mach-O is missing binary identifier; setting to {} based on file name",
identifier
);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
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 = self.dest_dir.join(file.relative_path());
info!("writing Mach-O to {}", dest_path.display());
write_macho_file(file.absolute_path(), &dest_path, &new_data)?;
SignedMachOInfo::parse_data(&new_data)
}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(())
}409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
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)
}
/// Create blobs that need to be written given the current configuration.
///
/// This emits all blobs except `CodeDirectory` and `Signature`, which are
/// special since they are derived from the blobs emitted here.
///
/// The goal of this function is to emit data to facilitate the creation of
/// a `CodeDirectory`, which requires hashing blobs.
pub fn create_special_blobs(
&self,
settings: &SigningSettings,
is_executable: bool,
) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
let mut res = Vec::new();
let mut requirements = CodeRequirements::default();
match settings.designated_requirement(SettingsScope::Main) {
DesignatedRequirementMode::Auto => {
// If we are using an Apple-issued cert, this should automatically
// derive appropriate designated requirements.
if let Some((_, cert)) = settings.signing_key() {
info!("attempting to derive code requirements from signing certificate");
let identifier = Some(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
if let Some(expr) = derive_designated_requirements(cert, identifier)? {
requirements.push(expr);
}
}
}
DesignatedRequirementMode::Explicit(exprs) => {
info!("using provided code requirements");
for expr in exprs {
requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
}
}
}
// Always emit a RequirementSet blob, even if empty. Without it, validation fails
// with `the sealed resource directory is invalid`.
let mut blob = RequirementSetBlob::default();
if !requirements.is_empty() {
info!("code requirements: {}", requirements);
requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
}
res.push((CodeSigningSlot::RequirementSet, blob.into()));
if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
info!("adding entitlements XML");
let blob = EntitlementsBlob::from_string(&entitlements);
res.push((CodeSigningSlot::Entitlements, blob.into()));
}
// The DER encoded entitlements weren't always present in the signature. The feature
// appears to have been introduced in macOS 10.14 and is the default behavior as of
// macOS 12 "when signing for all platforms." `codesign` appears to add the DER
// representation whenever entitlements are present, but only if the current binary is
// an executable (.filetype == MH_EXECUTE).
if is_executable {
if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
info!("adding entitlements DER");
let blob = EntitlementsDerBlob::from_plist(value)?;
res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
}
}
Ok(res)
}sourcepub fn set_binary_identifier(
&mut self,
scope: SettingsScope,
value: impl ToString
)
pub fn set_binary_identifier(
&mut self,
scope: SettingsScope,
value: impl ToString
)
Set the binary identifier string for a binary at a path.
This only has an effect when signing an individual Mach-O file (use the None path)
or the non-main executable in a bundle: when signing the main executable in a bundle,
the binary’s identifier is retrieved from the mandatory CFBundleIdentifier value in
the bundle’s Info.plist file.
The binary identifier should be a DNS-like name and should uniquely identify the
binary. e.g. com.example.my_program
Examples found in repository?
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
pub fn sign_macho(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
warn!("signing {} as a Mach-O binary", input_path.display());
let macho_data = std::fs::read(input_path)?;
let mut settings = self.settings.clone();
settings.import_settings_from_macho(&macho_data)?;
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = input_path
.file_name()
.ok_or_else(|| {
AppleCodesignError::CliGeneralError(
"unable to resolve file name of binary".into(),
)
})?
.to_string_lossy();
warn!("setting binary identifier to {}", identifier);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
warn!("parsing Mach-O");
let signer = MachOSigner::new(&macho_data)?;
let mut macho_data = vec![];
signer.write_signed_binary(&settings, &mut macho_data)?;
warn!("writing Mach-O to {}", output_path.display());
write_macho_file(input_path, output_path, &macho_data)?;
Ok(())
}
/// Sign a `.dmg` file.
pub fn sign_dmg(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
warn!("signing {} as a DMG", input_path.display());
// There must be a binary identifier on the DMG. So try to derive one
// from the filename if one isn't present in the settings.
let mut settings = self.settings.clone();
if settings.binary_identifier(SettingsScope::Main).is_none() {
let file_name = input_path
.file_stem()
.ok_or_else(|| {
AppleCodesignError::CliGeneralError("unable to resolve file name of DMG".into())
})?
.to_string_lossy();
warn!(
"setting binary identifier to {} (derived from file name)",
file_name
);
settings.set_binary_identifier(SettingsScope::Main, file_name);
}
// The DMG signer signs in place because it needs a `File` handle. So if
// the output path is different, copy the DMG first.
// This is not robust same file detection.
if input_path != output_path {
info!(
"copying {} to {} in preparation for signing",
input_path.display(),
output_path.display()
);
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(input_path, output_path)?;
}
let signer = DmgSigner::default();
let mut fh = std::fs::File::options()
.read(true)
.write(true)
.open(output_path)?;
signer.sign_file(&settings, &mut fh)?;
Ok(())
}More examples
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError> {
info!("signing Mach-O file {}", file.relative_path().display());
let macho_data = std::fs::read(file.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = self
.settings
.as_bundle_macho_settings(file.relative_path().to_string_lossy().as_ref());
settings.import_settings_from_macho(&macho_data)?;
// If there isn't a defined binary identifier, derive one from the file name so one is set
// and we avoid a signing error due to missing identifier.
// TODO do we need to check the nested Mach-O settings?
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = file
.relative_path()
.file_name()
.expect("failure to extract filename (this should never happen)")
.to_string_lossy();
let identifier = identifier
.strip_suffix(".dylib")
.unwrap_or_else(|| identifier.as_ref());
info!(
"Mach-O is missing binary identifier; setting to {} based on file name",
identifier
);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
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 = self.dest_dir.join(file.relative_path());
info!("writing Mach-O to {}", dest_path.display());
write_macho_file(file.absolute_path(), &dest_path, &new_data)?;
SignedMachOInfo::parse_data(&new_data)
}
}
/// A primitive for signing a single Apple bundle.
///
/// Unlike [BundleSigner], this type only signs a single bundle and is ignorant
/// about nested bundles. You probably want to use [BundleSigner] as the interface
/// for signing bundles, as failure to account for nested bundles can result in
/// signature verification errors.
pub struct SingleBundleSigner {
/// The bundle being signed.
bundle: DirectoryBundle,
}
impl SingleBundleSigner {
/// Construct a new instance.
pub fn new(bundle: DirectoryBundle) -> Self {
Self { bundle }
}
/// Write a signed bundle to the given directory.
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)
}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(())
}2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn entitlements_plist(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&Value>
pub fn entitlements_plist(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&Value>
Obtain the entitlements plist as a plist::Value.
The value should be a plist::Value::Dictionary variant.
Examples found in repository?
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
pub fn entitlements_xml(
&self,
scope: impl AsRef<SettingsScope>,
) -> Result<Option<String>, AppleCodesignError> {
if let Some(value) = self.entitlements_plist(scope) {
let mut buffer = vec![];
let writer = std::io::Cursor::new(&mut buffer);
value
.to_writer_xml(writer)
.map_err(AppleCodesignError::PlistSerializeXml)?;
Ok(Some(
String::from_utf8(buffer).expect("plist XML serialization should produce UTF-8"),
))
} else {
Ok(None)
}
}
/// Set the entitlements to sign via an XML string.
///
/// The value should be an XML plist. The value is parsed and stored as
/// a native plist value.
pub fn set_entitlements_xml(
&mut self,
scope: SettingsScope,
value: impl ToString,
) -> Result<(), AppleCodesignError> {
let cursor = std::io::Cursor::new(value.to_string().into_bytes());
let value =
plist::Value::from_reader_xml(cursor).map_err(AppleCodesignError::PlistParseXml)?;
self.entitlements.insert(scope, value);
Ok(())
}
/// Obtain the designated requirements for a given scope.
pub fn designated_requirement(
&self,
scope: impl AsRef<SettingsScope>,
) -> &DesignatedRequirementMode {
self.designated_requirement
.get(scope.as_ref())
.unwrap_or(&DesignatedRequirementMode::Auto)
}
/// Set the designated requirement for a Mach-O binary given a [CodeRequirementExpression].
///
/// The designated requirement (also known as "code requirements") specifies run-time
/// requirements for the binary. e.g. you can stipulate that the binary must be
/// signed by a certificate issued/signed/chained to Apple. The designated requirement
/// is embedded in Mach-O binaries and signed.
pub fn set_designated_requirement_expression(
&mut self,
scope: SettingsScope,
expr: &CodeRequirementExpression,
) -> Result<(), AppleCodesignError> {
self.designated_requirement.insert(
scope,
DesignatedRequirementMode::Explicit(vec![expr.to_bytes()?]),
);
Ok(())
}
/// Set the designated requirement expression for a Mach-O binary given serialized bytes.
///
/// This is like [SigningSettings::set_designated_requirement_expression] except the
/// designated requirement expression is given as serialized bytes. The bytes passed are
/// the value that would be produced by compiling a code requirement expression via
/// `csreq -b`.
pub fn set_designated_requirement_bytes(
&mut self,
scope: SettingsScope,
data: impl AsRef<[u8]>,
) -> Result<(), AppleCodesignError> {
let blob = RequirementBlob::from_blob_bytes(data.as_ref())?;
self.designated_requirement.insert(
scope,
DesignatedRequirementMode::Explicit(
blob.parse_expressions()?
.iter()
.map(|x| x.to_bytes())
.collect::<Result<Vec<_>, AppleCodesignError>>()?,
),
);
Ok(())
}
/// Set the designated requirement mode to auto, which will attempt to derive requirements
/// automatically.
///
/// This setting recognizes when code signing is being performed with Apple issued code signing
/// certificates and automatically applies appropriate settings for the certificate being
/// used and the entity being signed.
///
/// Not all combinations may be supported. If you get an error, you will need to
/// provide your own explicit requirement expression.
pub fn set_auto_designated_requirement(&mut self, scope: SettingsScope) {
self.designated_requirement
.insert(scope, DesignatedRequirementMode::Auto);
}
/// Obtain the code signature flags for a given scope.
pub fn code_signature_flags(
&self,
scope: impl AsRef<SettingsScope>,
) -> Option<CodeSignatureFlags> {
self.code_signature_flags.get(scope.as_ref()).copied()
}
/// Set code signature flags for signed Mach-O binaries.
///
/// The incoming flags will replace any already-defined flags.
pub fn set_code_signature_flags(&mut self, scope: SettingsScope, flags: CodeSignatureFlags) {
self.code_signature_flags.insert(scope, flags);
}
/// Add code signature flags.
///
/// The incoming flags will be ORd with any existing flags for the path
/// specified. The new flags will be returned.
pub fn add_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags,
) -> CodeSignatureFlags {
let existing = self
.code_signature_flags
.get(&scope)
.copied()
.unwrap_or_else(CodeSignatureFlags::empty);
let new = existing | flags;
self.code_signature_flags.insert(scope, new);
new
}
/// Remove code signature flags.
///
/// The incoming flags will be removed from any existing flags for the path
/// specified. The new flags will be returned.
pub fn remove_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags,
) -> CodeSignatureFlags {
let existing = self
.code_signature_flags
.get(&scope)
.copied()
.unwrap_or_else(CodeSignatureFlags::empty);
let new = existing - flags;
self.code_signature_flags.insert(scope, new);
new
}
/// Obtain the `Info.plist` data registered to a given scope.
pub fn info_plist_data(&self, scope: impl AsRef<SettingsScope>) -> Option<&[u8]> {
self.info_plist_data
.get(scope.as_ref())
.map(|x| x.as_slice())
}
/// Obtain the runtime version for a given scope.
///
/// The runtime version represents an OS version.
pub fn runtime_version(&self, scope: impl AsRef<SettingsScope>) -> Option<&semver::Version> {
self.runtime_version.get(scope.as_ref())
}
/// Set the runtime version to use in the code directory for a given scope.
///
/// The runtime version corresponds to an OS version. The runtime version is usually
/// derived from the SDK version used to build the binary.
pub fn set_runtime_version(&mut self, scope: SettingsScope, version: semver::Version) {
self.runtime_version.insert(scope, version);
}
/// Define the `Info.plist` content.
///
/// Signatures can reference the digest of an external `Info.plist` file in
/// the bundle the binary is located in.
///
/// This function registers the raw content of that file is so that the
/// content can be digested and the digest can be included in the code directory.
///
/// The value passed here should be the raw content of the `Info.plist` XML file.
///
/// When signing bundles, this function is called automatically with the `Info.plist`
/// from the bundle. This function exists for cases where you are signing
/// individual Mach-O binaries and the `Info.plist` cannot be automatically
/// discovered.
pub fn set_info_plist_data(&mut self, scope: SettingsScope, data: Vec<u8>) {
self.info_plist_data.insert(scope, data);
}
/// Obtain the `CodeResources` XML file data registered to a given scope.
pub fn code_resources_data(&self, scope: impl AsRef<SettingsScope>) -> Option<&[u8]> {
self.code_resources_data
.get(scope.as_ref())
.map(|x| x.as_slice())
}
/// Define the `CodeResources` XML file content for a given scope.
///
/// Bundles may contain a `CodeResources` XML file which defines additional
/// resource files and binaries outside the bundle's main executable. The code
/// directory of the main executable contains a digest of this file to establish
/// a chain of trust of the content of this XML file.
///
/// This function defines the content of this external file so that the content
/// can be digested and that digest included in the code directory of the
/// binary being signed.
///
/// When signing bundles, this function is called automatically with the content
/// of the `CodeResources` XML file, if present. This function exists for cases
/// where you are signing individual Mach-O binaries and the `CodeResources` XML
/// file cannot be automatically discovered.
pub fn set_code_resources_data(&mut self, scope: SettingsScope, data: Vec<u8>) {
self.code_resources_data.insert(scope, data);
}
/// Obtain extra digests to include in signatures.
pub fn extra_digests(&self, scope: impl AsRef<SettingsScope>) -> Option<&BTreeSet<DigestType>> {
self.extra_digests.get(scope.as_ref())
}
/// Register an addition content digest to use in signatures.
///
/// Extra digests supplement the primary registered digest when the signer supports
/// it. Calling this likely results in an additional code directory being included
/// in embedded signatures.
///
/// A common use case for this is to have the primary digest contain a legacy
/// digest type (namely SHA-1) but include stronger digests as well. This enables
/// signatures to have compatibility with older operating systems but still be modern.
pub fn add_extra_digest(&mut self, scope: SettingsScope, digest_type: DigestType) {
self.extra_digests
.entry(scope)
.or_default()
.insert(digest_type);
}
/// Obtain all configured digests for a scope.
pub fn all_digests(&self, scope: SettingsScope) -> Vec<DigestType> {
let mut res = vec![self.digest_type];
if let Some(extra) = self.extra_digests(scope) {
res.extend(extra.iter());
}
res
}
/// Import existing state from Mach-O data.
///
/// This will synchronize the signing settings with the state in the Mach-O file.
///
/// If existing settings are explicitly set, they will be honored. Otherwise the state from
/// the Mach-O is imported into the settings.
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
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
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)
}
/// Create blobs that need to be written given the current configuration.
///
/// This emits all blobs except `CodeDirectory` and `Signature`, which are
/// special since they are derived from the blobs emitted here.
///
/// The goal of this function is to emit data to facilitate the creation of
/// a `CodeDirectory`, which requires hashing blobs.
pub fn create_special_blobs(
&self,
settings: &SigningSettings,
is_executable: bool,
) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
let mut res = Vec::new();
let mut requirements = CodeRequirements::default();
match settings.designated_requirement(SettingsScope::Main) {
DesignatedRequirementMode::Auto => {
// If we are using an Apple-issued cert, this should automatically
// derive appropriate designated requirements.
if let Some((_, cert)) = settings.signing_key() {
info!("attempting to derive code requirements from signing certificate");
let identifier = Some(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
if let Some(expr) = derive_designated_requirements(cert, identifier)? {
requirements.push(expr);
}
}
}
DesignatedRequirementMode::Explicit(exprs) => {
info!("using provided code requirements");
for expr in exprs {
requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
}
}
}
// Always emit a RequirementSet blob, even if empty. Without it, validation fails
// with `the sealed resource directory is invalid`.
let mut blob = RequirementSetBlob::default();
if !requirements.is_empty() {
info!("code requirements: {}", requirements);
requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
}
res.push((CodeSigningSlot::RequirementSet, blob.into()));
if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
info!("adding entitlements XML");
let blob = EntitlementsBlob::from_string(&entitlements);
res.push((CodeSigningSlot::Entitlements, blob.into()));
}
// The DER encoded entitlements weren't always present in the signature. The feature
// appears to have been introduced in macOS 10.14 and is the default behavior as of
// macOS 12 "when signing for all platforms." `codesign` appears to add the DER
// representation whenever entitlements are present, but only if the current binary is
// an executable (.filetype == MH_EXECUTE).
if is_executable {
if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
info!("adding entitlements DER");
let blob = EntitlementsDerBlob::from_plist(value)?;
res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
}
}
Ok(res)
}sourcepub fn entitlements_xml(
&self,
scope: impl AsRef<SettingsScope>
) -> Result<Option<String>, AppleCodesignError>
pub fn entitlements_xml(
&self,
scope: impl AsRef<SettingsScope>
) -> Result<Option<String>, AppleCodesignError>
Obtain the entitlements XML string for a given scope.
Examples found in repository?
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)
}More examples
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
pub fn create_special_blobs(
&self,
settings: &SigningSettings,
is_executable: bool,
) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
let mut res = Vec::new();
let mut requirements = CodeRequirements::default();
match settings.designated_requirement(SettingsScope::Main) {
DesignatedRequirementMode::Auto => {
// If we are using an Apple-issued cert, this should automatically
// derive appropriate designated requirements.
if let Some((_, cert)) = settings.signing_key() {
info!("attempting to derive code requirements from signing certificate");
let identifier = Some(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
if let Some(expr) = derive_designated_requirements(cert, identifier)? {
requirements.push(expr);
}
}
}
DesignatedRequirementMode::Explicit(exprs) => {
info!("using provided code requirements");
for expr in exprs {
requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
}
}
}
// Always emit a RequirementSet blob, even if empty. Without it, validation fails
// with `the sealed resource directory is invalid`.
let mut blob = RequirementSetBlob::default();
if !requirements.is_empty() {
info!("code requirements: {}", requirements);
requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
}
res.push((CodeSigningSlot::RequirementSet, blob.into()));
if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
info!("adding entitlements XML");
let blob = EntitlementsBlob::from_string(&entitlements);
res.push((CodeSigningSlot::Entitlements, blob.into()));
}
// The DER encoded entitlements weren't always present in the signature. The feature
// appears to have been introduced in macOS 10.14 and is the default behavior as of
// macOS 12 "when signing for all platforms." `codesign` appears to add the DER
// representation whenever entitlements are present, but only if the current binary is
// an executable (.filetype == MH_EXECUTE).
if is_executable {
if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
info!("adding entitlements DER");
let blob = EntitlementsDerBlob::from_plist(value)?;
res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
}
}
Ok(res)
}sourcepub fn set_entitlements_xml(
&mut self,
scope: SettingsScope,
value: impl ToString
) -> Result<(), AppleCodesignError>
pub fn set_entitlements_xml(
&mut self,
scope: SettingsScope,
value: impl ToString
) -> Result<(), AppleCodesignError>
Set the entitlements to sign via an XML string.
The value should be an XML plist. The value is parsed and stored as a native plist value.
Examples found in repository?
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
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn designated_requirement(
&self,
scope: impl AsRef<SettingsScope>
) -> &DesignatedRequirementMode
pub fn designated_requirement(
&self,
scope: impl AsRef<SettingsScope>
) -> &DesignatedRequirementMode
Obtain the designated requirements for a given scope.
Examples found in repository?
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
pub fn create_special_blobs(
&self,
settings: &SigningSettings,
is_executable: bool,
) -> Result<Vec<(CodeSigningSlot, BlobData<'static>)>, AppleCodesignError> {
let mut res = Vec::new();
let mut requirements = CodeRequirements::default();
match settings.designated_requirement(SettingsScope::Main) {
DesignatedRequirementMode::Auto => {
// If we are using an Apple-issued cert, this should automatically
// derive appropriate designated requirements.
if let Some((_, cert)) = settings.signing_key() {
info!("attempting to derive code requirements from signing certificate");
let identifier = Some(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
if let Some(expr) = derive_designated_requirements(cert, identifier)? {
requirements.push(expr);
}
}
}
DesignatedRequirementMode::Explicit(exprs) => {
info!("using provided code requirements");
for expr in exprs {
requirements.push(CodeRequirementExpression::from_bytes(expr)?.0);
}
}
}
// Always emit a RequirementSet blob, even if empty. Without it, validation fails
// with `the sealed resource directory is invalid`.
let mut blob = RequirementSetBlob::default();
if !requirements.is_empty() {
info!("code requirements: {}", requirements);
requirements.add_to_requirement_set(&mut blob, RequirementType::Designated)?;
}
res.push((CodeSigningSlot::RequirementSet, blob.into()));
if let Some(entitlements) = settings.entitlements_xml(SettingsScope::Main)? {
info!("adding entitlements XML");
let blob = EntitlementsBlob::from_string(&entitlements);
res.push((CodeSigningSlot::Entitlements, blob.into()));
}
// The DER encoded entitlements weren't always present in the signature. The feature
// appears to have been introduced in macOS 10.14 and is the default behavior as of
// macOS 12 "when signing for all platforms." `codesign` appears to add the DER
// representation whenever entitlements are present, but only if the current binary is
// an executable (.filetype == MH_EXECUTE).
if is_executable {
if let Some(value) = settings.entitlements_plist(SettingsScope::Main) {
info!("adding entitlements DER");
let blob = EntitlementsDerBlob::from_plist(value)?;
res.push((CodeSigningSlot::EntitlementsDer, blob.into()));
}
}
Ok(res)
}sourcepub fn set_designated_requirement_expression(
&mut self,
scope: SettingsScope,
expr: &CodeRequirementExpression<'_>
) -> Result<(), AppleCodesignError>
pub fn set_designated_requirement_expression(
&mut self,
scope: SettingsScope,
expr: &CodeRequirementExpression<'_>
) -> Result<(), AppleCodesignError>
Set the designated requirement for a Mach-O binary given a CodeRequirementExpression.
The designated requirement (also known as “code requirements”) specifies run-time requirements for the binary. e.g. you can stipulate that the binary must be signed by a certificate issued/signed/chained to Apple. The designated requirement is embedded in Mach-O binaries and signed.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn set_designated_requirement_bytes(
&mut self,
scope: SettingsScope,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
pub fn set_designated_requirement_bytes(
&mut self,
scope: SettingsScope,
data: impl AsRef<[u8]>
) -> Result<(), AppleCodesignError>
Set the designated requirement expression for a Mach-O binary given serialized bytes.
This is like SigningSettings::set_designated_requirement_expression except the
designated requirement expression is given as serialized bytes. The bytes passed are
the value that would be produced by compiling a code requirement expression via
csreq -b.
sourcepub fn set_auto_designated_requirement(&mut self, scope: SettingsScope)
pub fn set_auto_designated_requirement(&mut self, scope: SettingsScope)
Set the designated requirement mode to auto, which will attempt to derive requirements automatically.
This setting recognizes when code signing is being performed with Apple issued code signing certificates and automatically applies appropriate settings for the certificate being used and the entity being signed.
Not all combinations may be supported. If you get an error, you will need to provide your own explicit requirement expression.
sourcepub fn code_signature_flags(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<CodeSignatureFlags>
pub fn code_signature_flags(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<CodeSignatureFlags>
Obtain the code signature flags for a given scope.
Examples found in repository?
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
pub fn create_code_directory<F: Read + Write + Seek>(
&self,
settings: &SigningSettings,
fh: &mut F,
) -> Result<CodeDirectoryBlob<'static>, AppleCodesignError> {
let reader = DmgReader::new(fh)?;
let mut flags = settings
.code_signature_flags(SettingsScope::Main)
.unwrap_or_else(CodeSignatureFlags::empty);
if settings.signing_key().is_some() {
flags -= CodeSignatureFlags::ADHOC;
} else {
flags |= CodeSignatureFlags::ADHOC;
}
warn!("using code signature flags: {:?}", flags);
let ident = Cow::Owned(
settings
.binary_identifier(SettingsScope::Main)
.ok_or(AppleCodesignError::NoIdentifier)?
.to_string(),
);
warn!("using identifier {}", ident);
let code_hashes = vec![reader.digest_content_with(*settings.digest_type(), fh)?];
let koly_digest = reader
.koly()
.digest_for_code_directory(*settings.digest_type())?;
let mut cd = CodeDirectoryBlob {
version: 0x20100,
flags,
code_limit: reader.koly().offset_after_plist() as u32,
digest_size: settings.digest_type().hash_len()? as u8,
digest_type: *settings.digest_type(),
page_size: 1,
ident,
code_digests: code_hashes,
..Default::default()
};
cd.set_slot_digest(CodeSigningSlot::RepSpecific, koly_digest)?;
Ok(cd)
}More examples
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(())
}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 set_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
)
pub fn set_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
)
Set code signature flags for signed Mach-O binaries.
The incoming flags will replace any already-defined flags.
Examples found in repository?
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
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn add_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
) -> CodeSignatureFlags
pub fn add_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
) -> CodeSignatureFlags
Add code signature flags.
The incoming flags will be ORd with any existing flags for the path specified. The new flags will be returned.
sourcepub fn remove_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
) -> CodeSignatureFlags
pub fn remove_code_signature_flags(
&mut self,
scope: SettingsScope,
flags: CodeSignatureFlags
) -> CodeSignatureFlags
Remove code signature flags.
The incoming flags will be removed from any existing flags for the path specified. The new flags will be returned.
sourcepub fn info_plist_data(&self, scope: impl AsRef<SettingsScope>) -> Option<&[u8]>
pub fn info_plist_data(&self, scope: impl AsRef<SettingsScope>) -> Option<&[u8]>
Obtain the Info.plist data registered to a given scope.
Examples found in repository?
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
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 runtime_version(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&Version>
pub fn runtime_version(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&Version>
Obtain the runtime version for a given scope.
The runtime version represents an OS version.
Examples found in repository?
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
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 set_runtime_version(&mut self, scope: SettingsScope, version: Version)
pub fn set_runtime_version(&mut self, scope: SettingsScope, version: Version)
Set the runtime version to use in the code directory for a given scope.
The runtime version corresponds to an OS version. The runtime version is usually derived from the SDK version used to build the binary.
Examples found in repository?
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
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn set_info_plist_data(&mut self, scope: SettingsScope, data: Vec<u8>)
pub fn set_info_plist_data(&mut self, scope: SettingsScope, data: Vec<u8>)
Define the Info.plist content.
Signatures can reference the digest of an external Info.plist file in
the bundle the binary is located in.
This function registers the raw content of that file is so that the content can be digested and the digest can be included in the code directory.
The value passed here should be the raw content of the Info.plist XML file.
When signing bundles, this function is called automatically with the Info.plist
from the bundle. This function exists for cases where you are signing
individual Mach-O binaries and the Info.plist cannot be automatically
discovered.
Examples found in repository?
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
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}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)
}sourcepub fn code_resources_data(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&[u8]>
pub fn code_resources_data(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&[u8]>
Obtain the CodeResources XML file data registered to a given scope.
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 set_code_resources_data(&mut self, scope: SettingsScope, data: Vec<u8>)
pub fn set_code_resources_data(&mut self, scope: SettingsScope, data: Vec<u8>)
Define the CodeResources XML file content for a given scope.
Bundles may contain a CodeResources XML file which defines additional
resource files and binaries outside the bundle’s main executable. The code
directory of the main executable contains a digest of this file to establish
a chain of trust of the content of this XML file.
This function defines the content of this external file so that the content can be digested and that digest included in the code directory of the binary being signed.
When signing bundles, this function is called automatically with the content
of the CodeResources XML file, if present. This function exists for cases
where you are signing individual Mach-O binaries and the CodeResources XML
file cannot be automatically discovered.
Examples found in repository?
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}More examples
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)
}sourcepub fn extra_digests(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&BTreeSet<DigestType>>
pub fn extra_digests(
&self,
scope: impl AsRef<SettingsScope>
) -> Option<&BTreeSet<DigestType>>
Obtain extra digests to include in signatures.
Examples found in repository?
More examples
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
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()
}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)
}sourcepub fn add_extra_digest(&mut self, scope: SettingsScope, digest_type: DigestType)
pub fn add_extra_digest(&mut self, scope: SettingsScope, digest_type: DigestType)
Register an addition content digest to use in signatures.
Extra digests supplement the primary registered digest when the signer supports it. Calling this likely results in an additional code directory being included in embedded signatures.
A common use case for this is to have the primary digest contain a legacy digest type (namely SHA-1) but include stronger digests as well. This enables signatures to have compatibility with older operating systems but still be modern.
Examples found in repository?
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
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let mut settings = SigningSettings::default();
let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;
if private_keys.len() > 1 {
error!("at most 1 PRIVATE KEY can be present; aborting");
return Err(AppleCodesignError::CliBadArgument);
}
let private = if private_keys.is_empty() {
None
} else {
Some(&private_keys[0])
};
if let Some(signing_key) = &private {
if public_certificates.is_empty() {
error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
return Err(AppleCodesignError::CliBadArgument);
}
let cert = public_certificates.remove(0);
warn!("registering signing key");
settings.set_signing_key(signing_key.as_key_info_signer(), cert);
if let Some(certs) = settings.chain_apple_certificates() {
for cert in certs {
warn!(
"automatically registered Apple CA certificate: {}",
cert.subject_common_name()
.unwrap_or_else(|| "default".into())
);
}
}
if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
if timestamp_url != "none" {
warn!("using time-stamp protocol server {}", timestamp_url);
settings.set_time_stamp_url(timestamp_url)?;
}
}
}
if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
warn!(
"automatically setting team ID from signing certificate: {}",
team_id
);
}
for cert in public_certificates {
warn!("registering extra X.509 certificate");
settings.chain_certificate(cert);
}
if let Some(team_name) = args.get_one::<String>("team_name") {
settings.set_team_id(team_name);
}
if let Some(value) = args.get_one::<String>("digest") {
let digest_type = DigestType::try_from(value.as_str())?;
settings.set_digest_type(digest_type);
}
if let Some(values) = args.get_many::<String>("extra_digest") {
for value in values {
let (scope, digest_type) = parse_scoped_value(value)?;
let digest_type = DigestType::try_from(digest_type)?;
settings.add_extra_digest(scope, digest_type);
}
}
if let Some(values) = args.get_many::<String>("exclude") {
for pattern in values {
settings.add_path_exclusion(pattern)?;
}
}
if let Some(values) = args.get_many::<String>("binary_identifier") {
for value in values {
let (scope, identifier) = parse_scoped_value(value)?;
settings.set_binary_identifier(scope, identifier);
}
}
if let Some(values) = args.get_many::<String>("code_requirements_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
let code_requirements_data = std::fs::read(path)?;
let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
for expr in reqs.iter() {
warn!(
"setting designated code requirements for {}: {}",
scope, expr
);
settings.set_designated_requirement_expression(scope.clone(), expr)?;
}
}
}
if let Some(values) = args.get_many::<String>("code_resources") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!(
"setting code resources data for {} from path {}",
scope, path
);
let code_resources_data = std::fs::read(path)?;
settings.set_code_resources_data(scope, code_resources_data);
}
}
if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let flags = CodeSignatureFlags::from_str(value)?;
settings.set_code_signature_flags(scope, flags);
}
}
if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
for value in values {
let (scope, path) = parse_scoped_value(value)?;
warn!("setting entitlments XML for {} from path {}", scope, path);
let entitlements_data = std::fs::read_to_string(path)?;
settings.set_entitlements_xml(scope, entitlements_data)?;
}
}
if let Some(values) = args.get_many::<String>("runtime_version") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let version = semver::Version::parse(value)?;
settings.set_runtime_version(scope, version);
}
}
if let Some(values) = args.get_many::<String>("info_plist_path") {
for value in values {
let (scope, value) = parse_scoped_value(value)?;
let content = std::fs::read(value)?;
settings.set_info_plist_data(scope, content);
}
}
let input_path = PathBuf::from(
args.get_one::<String>("input_path")
.expect("input_path presence should have been validated by clap"),
);
let output_path = args.get_one::<String>("output_path");
let signer = UnifiedSigner::new(settings);
if let Some(output_path) = output_path {
warn!("signing {} to {}", input_path.display(), output_path);
signer.sign_path(input_path, output_path)?;
} else {
warn!("signing {} in place", input_path.display());
signer.sign_path_in_place(input_path)?;
}
if let Some(private) = &private {
private.finish()?;
}
Ok(())
}sourcepub fn all_digests(&self, scope: SettingsScope) -> Vec<DigestType> ⓘ
pub fn all_digests(&self, scope: SettingsScope) -> Vec<DigestType> ⓘ
Obtain all configured digests for a scope.
Examples found in repository?
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)
}sourcepub fn import_settings_from_macho(
&mut self,
data: &[u8]
) -> Result<(), AppleCodesignError>
pub fn import_settings_from_macho(
&mut self,
data: &[u8]
) -> Result<(), AppleCodesignError>
Import existing state from Mach-O data.
This will synchronize the signing settings with the state in the Mach-O file.
If existing settings are explicitly set, they will be honored. Otherwise the state from the Mach-O is imported into the settings.
Examples found in repository?
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
pub fn sign_macho(
&self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Result<(), AppleCodesignError> {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
warn!("signing {} as a Mach-O binary", input_path.display());
let macho_data = std::fs::read(input_path)?;
let mut settings = self.settings.clone();
settings.import_settings_from_macho(&macho_data)?;
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = input_path
.file_name()
.ok_or_else(|| {
AppleCodesignError::CliGeneralError(
"unable to resolve file name of binary".into(),
)
})?
.to_string_lossy();
warn!("setting binary identifier to {}", identifier);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
warn!("parsing Mach-O");
let signer = MachOSigner::new(&macho_data)?;
let mut macho_data = vec![];
signer.write_signed_binary(&settings, &mut macho_data)?;
warn!("writing Mach-O to {}", output_path.display());
write_macho_file(input_path, output_path, &macho_data)?;
Ok(())
}More examples
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError> {
info!("signing Mach-O file {}", file.relative_path().display());
let macho_data = std::fs::read(file.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = self
.settings
.as_bundle_macho_settings(file.relative_path().to_string_lossy().as_ref());
settings.import_settings_from_macho(&macho_data)?;
// If there isn't a defined binary identifier, derive one from the file name so one is set
// and we avoid a signing error due to missing identifier.
// TODO do we need to check the nested Mach-O settings?
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = file
.relative_path()
.file_name()
.expect("failure to extract filename (this should never happen)")
.to_string_lossy();
let identifier = identifier
.strip_suffix(".dylib")
.unwrap_or_else(|| identifier.as_ref());
info!(
"Mach-O is missing binary identifier; setting to {} based on file name",
identifier
);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
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 = self.dest_dir.join(file.relative_path());
info!("writing Mach-O to {}", dest_path.display());
write_macho_file(file.absolute_path(), &dest_path, &new_data)?;
SignedMachOInfo::parse_data(&new_data)
}
}
/// A primitive for signing a single Apple bundle.
///
/// Unlike [BundleSigner], this type only signs a single bundle and is ignorant
/// about nested bundles. You probably want to use [BundleSigner] as the interface
/// for signing bundles, as failure to account for nested bundles can result in
/// signature verification errors.
pub struct SingleBundleSigner {
/// The bundle being signed.
bundle: DirectoryBundle,
}
impl SingleBundleSigner {
/// Construct a new instance.
pub fn new(bundle: DirectoryBundle) -> Self {
Self { bundle }
}
/// Write a signed bundle to the given directory.
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)
}sourcepub fn as_nested_bundle_settings(&self, bundle_path: &str) -> Self
pub fn as_nested_bundle_settings(&self, bundle_path: &str) -> Self
Convert this instance to settings appropriate for a nested bundle.
Examples found in repository?
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
pub fn write_signed_bundle(
&self,
dest_dir: impl AsRef<Path>,
settings: &SigningSettings,
) -> Result<DirectoryBundle, AppleCodesignError> {
let dest_dir = dest_dir.as_ref();
// We need to sign the leaf-most bundles first since a parent bundle may need
// to record information about the child in its signature.
let mut bundles = self
.bundles
.iter()
.filter_map(|(rel, bundle)| rel.as_ref().map(|rel| (rel, bundle)))
.collect::<Vec<_>>();
// This won't preserve alphabetical order. But since the input was stable, output
// should be deterministic.
bundles.sort_by(|(a, _), (b, _)| b.len().cmp(&a.len()));
warn!(
"signing {} nested bundles in the following order:",
bundles.len()
);
for bundle in &bundles {
warn!("{}", bundle.0);
}
for (rel, nested) in bundles {
let nested_dest_dir = dest_dir.join(rel);
info!(
"entering nested bundle {}",
nested.bundle.root_dir().display(),
);
// If we excluded this bundle from signing, just copy all the files.
if settings
.path_exclusion_patterns()
.iter()
.any(|pattern| pattern.matches(rel))
{
warn!("bundle is in exclusion list; it will be copied instead of signed");
copy_bundle(&nested.bundle, &nested_dest_dir)?;
} else {
nested.write_signed_bundle(
nested_dest_dir,
&settings.as_nested_bundle_settings(rel),
)?;
}
info!(
"leaving nested bundle {}",
nested.bundle.root_dir().display()
);
}
let main = self
.bundles
.get(&None)
.expect("main bundle should have a key");
main.write_signed_bundle(dest_dir, settings)
}sourcepub fn as_bundle_macho_settings(&self, path: &str) -> Self
pub fn as_bundle_macho_settings(&self, path: &str) -> Self
Convert this instance to settings appropriate for a Mach-O binary in a bundle.
Examples found in repository?
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
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError> {
info!("signing Mach-O file {}", file.relative_path().display());
let macho_data = std::fs::read(file.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = self
.settings
.as_bundle_macho_settings(file.relative_path().to_string_lossy().as_ref());
settings.import_settings_from_macho(&macho_data)?;
// If there isn't a defined binary identifier, derive one from the file name so one is set
// and we avoid a signing error due to missing identifier.
// TODO do we need to check the nested Mach-O settings?
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = file
.relative_path()
.file_name()
.expect("failure to extract filename (this should never happen)")
.to_string_lossy();
let identifier = identifier
.strip_suffix(".dylib")
.unwrap_or_else(|| identifier.as_ref());
info!(
"Mach-O is missing binary identifier; setting to {} based on file name",
identifier
);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
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 = self.dest_dir.join(file.relative_path());
info!("writing Mach-O to {}", dest_path.display());
write_macho_file(file.absolute_path(), &dest_path, &new_data)?;
SignedMachOInfo::parse_data(&new_data)
}sourcepub fn as_nested_macho_settings(&self, index: usize, cpu_type: CpuType) -> Self
pub fn as_nested_macho_settings(&self, index: usize, cpu_type: CpuType) -> Self
Convert this instance to settings appropriate for a nested Mach-O binary.
It is assumed the main scope of these settings is already targeted for a Mach-O binary. Any scoped settings for the Mach-O binary index and CPU type will be applied. CPU type settings take precedence over index scoped settings.
Examples found in repository?
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(())
}Trait Implementations§
source§impl<'key> Clone for SigningSettings<'key>
impl<'key> Clone for SigningSettings<'key>
source§fn clone(&self) -> SigningSettings<'key>
fn clone(&self) -> SigningSettings<'key>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moresource§impl<'key> Default for SigningSettings<'key>
impl<'key> Default for SigningSettings<'key>
source§fn default() -> SigningSettings<'key>
fn default() -> SigningSettings<'key>
Auto Trait Implementations§
impl<'key> !RefUnwindSafe for SigningSettings<'key>
impl<'key> !Send for SigningSettings<'key>
impl<'key> !Sync for SigningSettings<'key>
impl<'key> Unpin for SigningSettings<'key>
impl<'key> !UnwindSafe for SigningSettings<'key>
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.