Trait apple_codesign::embedded_signature::Blob
source · pub trait Blob<'a>where
Self: Sized,{
fn magic() -> u32;
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>;
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>;
fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> { ... }
fn digest_with(
&self,
hash_type: DigestType
) -> Result<Vec<u8>, AppleCodesignError> { ... }
}Expand description
Provides common features for a parsed blob type.
Required Methods§
sourcefn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError>
Attempt to construct an instance by parsing a bytes slice.
The slice begins with the 8 byte blob header denoting the magic and length.
sourcefn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError>
Serialize the payload of this blob to bytes.
Does not include the magic or length header fields common to blobs.
Provided Methods§
sourcefn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError>
fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError>
Serialize this blob to bytes.
This is Blob::serialize_payload with the blob magic and length prepended.
Examples found in repository?
src/embedded_signature.rs (line 671)
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
fn digest_with(&self, hash_type: DigestType) -> Result<Vec<u8>, AppleCodesignError> {
hash_type.digest_data(&self.to_blob_bytes()?)
}
}
/// Represents a Requirement blob.
///
/// `csreq -b` will emit instances of this blob, header magic and all. So data generated
/// by `csreq -b` can be fed into [RequirementBlob.from_blob_bytes] to obtain an instance.
pub struct RequirementBlob<'a> {
pub data: Cow<'a, [u8]>,
}
impl<'a> Blob<'a> for RequirementBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::Requirement)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
let data = read_and_validate_blob_header(data, Self::magic(), "requirement blob")?;
Ok(Self { data: data.into() })
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
}
impl<'a> std::fmt::Debug for RequirementBlob<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("RequirementBlob({})", hex::encode(&self.data)))
}
}
impl<'a> RequirementBlob<'a> {
pub fn to_owned(&self) -> RequirementBlob<'static> {
RequirementBlob {
data: Cow::Owned(self.data.clone().into_owned()),
}
}
/// Parse the binary data in this blob into Code Requirement expressions.
pub fn parse_expressions(&self) -> Result<CodeRequirements, AppleCodesignError> {
Ok(CodeRequirements::parse_binary(&self.data)?.0)
}
}
/// Represents a Requirement set blob.
///
/// A Requirement set blob contains nested Requirement blobs.
#[derive(Debug, Default)]
pub struct RequirementSetBlob<'a> {
pub requirements: HashMap<RequirementType, RequirementBlob<'a>>,
}
impl<'a> Blob<'a> for RequirementSetBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::RequirementSet)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
read_and_validate_blob_header(data, Self::magic(), "requirement set blob")?;
// There are other blobs nested within. A u32 denotes how many there are.
// Then there is an array of N (u32, u32) denoting the type and
// offset of each.
let offset = &mut 8;
let count = data.gread_with::<u32>(offset, scroll::BE)?;
let mut indices = Vec::with_capacity(count as usize);
for _ in 0..count {
indices.push((
data.gread_with::<u32>(offset, scroll::BE)?,
data.gread_with::<u32>(offset, scroll::BE)?,
));
}
let mut requirements = HashMap::with_capacity(indices.len());
for (i, (flavor, offset)) in indices.iter().enumerate() {
let typ = RequirementType::from(*flavor);
let end_offset = if i == indices.len() - 1 {
data.len()
} else {
indices[i + 1].1 as usize
};
let requirement_data = &data[*offset as usize..end_offset];
requirements.insert(typ, RequirementBlob::from_blob_bytes(requirement_data)?);
}
Ok(Self { requirements })
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
let mut res = Vec::new();
// The index contains blob relative offsets. To know what the start offset will
// be, we calculate the total index size.
let data_start_offset = 8 + 4 + (8 * self.requirements.len() as u32);
let mut written_requirements_data = 0;
res.iowrite_with(self.requirements.len() as u32, scroll::BE)?;
// Write an index of all nested requirement blobs.
for (typ, requirement) in &self.requirements {
res.iowrite_with(u32::from(*typ), scroll::BE)?;
res.iowrite_with(data_start_offset + written_requirements_data, scroll::BE)?;
written_requirements_data += requirement.to_blob_bytes()?.len() as u32;
}
// Now write every requirement's raw data.
for requirement in self.requirements.values() {
res.write_all(&requirement.to_blob_bytes()?)?;
}
Ok(res)
}
}
impl<'a> RequirementSetBlob<'a> {
pub fn to_owned(&self) -> RequirementSetBlob<'static> {
RequirementSetBlob {
requirements: self
.requirements
.iter()
.map(|(flavor, blob)| (*flavor, blob.to_owned()))
.collect::<HashMap<_, _>>(),
}
}
/// Set the requirements for a given [RequirementType].
pub fn set_requirements(&mut self, slot: RequirementType, blob: RequirementBlob<'a>) {
self.requirements.insert(slot, blob);
}
}
/// Represents an embedded signature.
#[derive(Debug)]
pub struct EmbeddedSignatureBlob<'a> {
data: &'a [u8],
}
impl<'a> Blob<'a> for EmbeddedSignatureBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::EmbeddedSignature)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
Ok(Self {
data: read_and_validate_blob_header(data, Self::magic(), "embedded signature blob")?,
})
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
}
/// An old embedded signature.
#[derive(Debug)]
pub struct EmbeddedSignatureOldBlob<'a> {
data: &'a [u8],
}
impl<'a> Blob<'a> for EmbeddedSignatureOldBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::EmbeddedSignatureOld)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
Ok(Self {
data: read_and_validate_blob_header(
data,
Self::magic(),
"old embedded signature blob",
)?,
})
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
}
/// Represents an Entitlements blob.
///
/// An entitlements blob contains an XML plist with a dict. Keys are
/// strings of the entitlements being requested and values appear to be
/// simple bools.
#[derive(Debug)]
pub struct EntitlementsBlob<'a> {
plist: Cow<'a, str>,
}
impl<'a> Blob<'a> for EntitlementsBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::Entitlements)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
let data = read_and_validate_blob_header(data, Self::magic(), "entitlements blob")?;
let s = std::str::from_utf8(data).map_err(AppleCodesignError::EntitlementsBadUtf8)?;
Ok(Self { plist: s.into() })
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.plist.as_bytes().to_vec())
}
}
impl<'a> EntitlementsBlob<'a> {
/// Construct an instance using any string as the payload.
pub fn from_string(s: &(impl ToString + ?Sized)) -> Self {
Self {
plist: s.to_string().into(),
}
}
/// Obtain the plist representation as a string.
pub fn as_str(&self) -> &str {
&self.plist
}
}
impl<'a> std::fmt::Display for EntitlementsBlob<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.plist)
}
}
#[derive(Debug)]
pub struct EntitlementsDerBlob<'a> {
der: Cow<'a, [u8]>,
}
impl<'a> Blob<'a> for EntitlementsDerBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::EntitlementsDer)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
let der = read_and_validate_blob_header(data, Self::magic(), "DER entitlements blob")?;
Ok(Self { der: der.into() })
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.der.to_vec())
}
}
impl<'a> EntitlementsDerBlob<'a> {
/// Construct an instance from a [plist::Value].
///
/// Not all plists can be encoded to this blob as not all plist value types can
/// be encoded to DER. If a plist with an illegal value is passed in, this
/// function will error, as DER encoding is performed immediately.
///
/// The outermost plist value should be a dictionary.
pub fn from_plist(v: &plist::Value) -> Result<Self, AppleCodesignError> {
let der = crate::entitlements::der_encode_entitlements_plist(v)?;
Ok(Self { der: der.into() })
}
}
/// A detached signature.
#[derive(Debug)]
pub struct DetachedSignatureBlob<'a> {
data: &'a [u8],
}
impl<'a> Blob<'a> for DetachedSignatureBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::DetachedSignature)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
Ok(Self {
data: read_and_validate_blob_header(data, Self::magic(), "detached signature blob")?,
})
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
}
/// Represents a generic blob wrapper.
pub struct BlobWrapperBlob<'a> {
data: Cow<'a, [u8]>,
}
impl<'a> Blob<'a> for BlobWrapperBlob<'a> {
fn magic() -> u32 {
u32::from(CodeSigningMagic::BlobWrapper)
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
Ok(Self {
data: read_and_validate_blob_header(data, Self::magic(), "blob wrapper blob")?.into(),
})
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
}
impl<'a> std::fmt::Debug for BlobWrapperBlob<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}", hex::encode(&self.data)))
}
}
impl<'a> BlobWrapperBlob<'a> {
/// Construct an instance where the payload (post blob header) is given data.
pub fn from_data_borrowed(data: &'a [u8]) -> BlobWrapperBlob<'a> {
Self { data: data.into() }
}
}
impl BlobWrapperBlob<'static> {
/// Construct an instance with payload data.
pub fn from_data_owned(data: Vec<u8>) -> BlobWrapperBlob<'static> {
Self { data: data.into() }
}
}
/// Represents an unknown blob type.
pub struct OtherBlob<'a> {
pub magic: u32,
pub data: &'a [u8],
}
impl<'a> Blob<'a> for OtherBlob<'a> {
fn magic() -> u32 {
// Use a placeholder magic value because there is no self bind here.
u32::MAX
}
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
let (magic, _, data) = read_blob_header(data)?;
Ok(Self { magic, data })
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
Ok(self.data.to_vec())
}
// We need to implement this for custom magic serialization.
fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
let mut res = Vec::with_capacity(self.data.len() + 8);
res.iowrite_with(self.magic, scroll::BE)?;
res.iowrite_with(self.data.len() as u32 + 8, scroll::BE)?;
res.write_all(self.data)?;
Ok(res)
}
}
impl<'a> std::fmt::Debug for OtherBlob<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}", hex::encode(self.data)))
}
}
/// Represents a single, parsed Blob entry/slot.
///
/// Each variant corresponds to a [CodeSigningMagic] blob type.
#[derive(Debug)]
pub enum BlobData<'a> {
Requirement(Box<RequirementBlob<'a>>),
RequirementSet(Box<RequirementSetBlob<'a>>),
CodeDirectory(Box<CodeDirectoryBlob<'a>>),
EmbeddedSignature(Box<EmbeddedSignatureBlob<'a>>),
EmbeddedSignatureOld(Box<EmbeddedSignatureOldBlob<'a>>),
Entitlements(Box<EntitlementsBlob<'a>>),
EntitlementsDer(Box<EntitlementsDerBlob<'a>>),
DetachedSignature(Box<DetachedSignatureBlob<'a>>),
BlobWrapper(Box<BlobWrapperBlob<'a>>),
Other(Box<OtherBlob<'a>>),
}
impl<'a> Blob<'a> for BlobData<'a> {
fn magic() -> u32 {
u32::MAX
}
/// Parse blob data by reading its magic and feeding into magic-specific parser.
fn from_blob_bytes(data: &'a [u8]) -> Result<Self, AppleCodesignError> {
let (magic, length, _) = read_blob_header(data)?;
// This should be a no-op. But it could (correctly) cause a panic if the
// advertised length is incorrect and we would incur a buffer overrun.
let data = &data[0..length];
let magic = CodeSigningMagic::from(magic);
Ok(match magic {
CodeSigningMagic::Requirement => {
Self::Requirement(Box::new(RequirementBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::RequirementSet => {
Self::RequirementSet(Box::new(RequirementSetBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::CodeDirectory => {
Self::CodeDirectory(Box::new(CodeDirectoryBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::EmbeddedSignature => {
Self::EmbeddedSignature(Box::new(EmbeddedSignatureBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::EmbeddedSignatureOld => Self::EmbeddedSignatureOld(Box::new(
EmbeddedSignatureOldBlob::from_blob_bytes(data)?,
)),
CodeSigningMagic::Entitlements => {
Self::Entitlements(Box::new(EntitlementsBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::EntitlementsDer => {
Self::EntitlementsDer(Box::new(EntitlementsDerBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::DetachedSignature => {
Self::DetachedSignature(Box::new(DetachedSignatureBlob::from_blob_bytes(data)?))
}
CodeSigningMagic::BlobWrapper => {
Self::BlobWrapper(Box::new(BlobWrapperBlob::from_blob_bytes(data)?))
}
_ => Self::Other(Box::new(OtherBlob::from_blob_bytes(data)?)),
})
}
fn serialize_payload(&self) -> Result<Vec<u8>, AppleCodesignError> {
match self {
Self::Requirement(b) => b.serialize_payload(),
Self::RequirementSet(b) => b.serialize_payload(),
Self::CodeDirectory(b) => b.serialize_payload(),
Self::EmbeddedSignature(b) => b.serialize_payload(),
Self::EmbeddedSignatureOld(b) => b.serialize_payload(),
Self::Entitlements(b) => b.serialize_payload(),
Self::EntitlementsDer(b) => b.serialize_payload(),
Self::DetachedSignature(b) => b.serialize_payload(),
Self::BlobWrapper(b) => b.serialize_payload(),
Self::Other(b) => b.serialize_payload(),
}
}
fn to_blob_bytes(&self) -> Result<Vec<u8>, AppleCodesignError> {
match self {
Self::Requirement(b) => b.to_blob_bytes(),
Self::RequirementSet(b) => b.to_blob_bytes(),
Self::CodeDirectory(b) => b.to_blob_bytes(),
Self::EmbeddedSignature(b) => b.to_blob_bytes(),
Self::EmbeddedSignatureOld(b) => b.to_blob_bytes(),
Self::Entitlements(b) => b.to_blob_bytes(),
Self::EntitlementsDer(b) => b.to_blob_bytes(),
Self::DetachedSignature(b) => b.to_blob_bytes(),
Self::BlobWrapper(b) => b.to_blob_bytes(),
Self::Other(b) => b.to_blob_bytes(),
}
}More examples
src/bundle_signing.rs (line 180)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
pub fn parse_data(data: &[u8]) -> Result<Self, AppleCodesignError> {
// Initial Mach-O's signature data is used.
let mach = MachFile::parse(data)?;
let macho = mach.nth_macho(0)?;
let signature = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
let code_directory_blob = signature.preferred_code_directory()?.to_blob_bytes()?;
let designated_code_requirement = if let Some(requirements) =
signature.code_requirements()?
{
if let Some(designated) = requirements.requirements.get(&RequirementType::Designated) {
let req = designated.parse_expressions()?;
Some(format!("{}", req[0]))
} else {
// In case no explicit requirements has been set, we use current file cdhashes.
let mut requirement_expr = None;
for macho in mach.iter_macho() {
let cd = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?
.preferred_code_directory()?;
let digest_type = if cd.digest_type == DigestType::Sha256 {
DigestType::Sha256Truncated
} else {
cd.digest_type
};
let digest = digest_type.digest_data(&cd.to_blob_bytes()?)?;
let expression = Box::new(CodeRequirementExpression::CodeDirectoryHash(
Cow::from(digest),
));
if let Some(left_part) = requirement_expr {
requirement_expr = Some(Box::new(CodeRequirementExpression::Or(
left_part, expression,
)))
} else {
requirement_expr = Some(expression);
}
}
Some(format!(
"{}",
requirement_expr.expect("a Mach-O should have been present")
))
}
} else {
None
};
Ok(SignedMachOInfo {
code_directory_blob,
designated_code_requirement,
})
}src/embedded_signature_builder.rs (line 273)
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
pub fn create_cms_signature(
&mut self,
signing_key: &dyn KeyInfoSigner,
signing_cert: &CapturedX509Certificate,
time_stamp_url: Option<&Url>,
certificates: impl Iterator<Item = CapturedX509Certificate>,
) -> Result<(), AppleCodesignError> {
let main_cd = self
.code_directory()
.ok_or(AppleCodesignError::SignatureBuilder(
"cannot create CMS signature unless code directory is present",
))?;
if let Some(cn) = signing_cert.subject_common_name() {
warn!("creating cryptographic signature with certificate {}", cn);
}
let mut cdhashes = vec![];
let mut attributes = vec![];
for (slot, blob) in &self.blobs {
if *slot == CodeSigningSlot::CodeDirectory || slot.is_alternative_code_directory() {
if let BlobData::CodeDirectory(cd) = blob {
// plist digests use the native digest of the code directory but always
// truncated at 20 bytes.
let mut digest = cd.digest_with(cd.digest_type)?;
digest.truncate(20);
cdhashes.push(plist::Value::Data(digest));
// ASN.1 values are a SEQUENCE of (OID, OctetString) with the native
// digest.
let digest = cd.digest_with(cd.digest_type)?;
let alg = DigestAlgorithm::try_from(cd.digest_type)?;
attributes.push(AttributeValue::new(bcder::Captured::from_values(
bcder::Mode::Der,
bcder::encode::sequence((
Oid::from(alg).encode_ref(),
bcder::OctetString::new(digest.into()).encode_ref(),
)),
)));
} else {
return Err(AppleCodesignError::SignatureBuilder(
"unexpected blob type in code directory slot",
));
}
}
}
let mut plist_dict = plist::Dictionary::new();
plist_dict.insert("cdhashes".to_string(), plist::Value::Array(cdhashes));
let mut plist_xml = vec![];
plist::Value::from(plist_dict)
.to_writer_xml(&mut plist_xml)
.map_err(AppleCodesignError::CodeDirectoryPlist)?;
// We also need to include a trailing newline to conform with Apple's XML
// writer.
plist_xml.push(b'\n');
let signer = SignerBuilder::new(signing_key, signing_cert.clone())
.message_id_content(main_cd.to_blob_bytes()?)
.signed_attribute_octet_string(
Oid(Bytes::copy_from_slice(CD_DIGESTS_PLIST_OID.as_ref())),
&plist_xml,
);
let signer = signer.signed_attribute(Oid(CD_DIGESTS_OID.as_ref().into()), attributes);
let signer = if let Some(time_stamp_url) = time_stamp_url {
info!("Using time-stamp server {}", time_stamp_url);
signer.time_stamp_url(time_stamp_url.clone())?
} else {
signer
};
let der = SignedDataBuilder::default()
// The default is `signed-data`. But Apple appears to use the `data` content-type,
// in violation of RFC 5652 Section 5, which says `signed-data` should be
// used when there are signatures.
.content_type(Oid(OID_ID_DATA.as_ref().into()))
.signer(signer)
.certificates(certificates)
.build_der()?;
self.blobs.insert(
CodeSigningSlot::Signature,
BlobData::BlobWrapper(Box::new(BlobWrapperBlob::from_data_owned(der))),
);
self.state = BlobsState::SignatureAdded;
Ok(())
}
/// Add notarization ticket data.
///
/// This will register a new ticket slot holding the notarization ticket data.
pub fn add_notarization_ticket(
&mut self,
ticket_data: Vec<u8>,
) -> Result<(), AppleCodesignError> {
self.blobs.insert(
CodeSigningSlot::Ticket,
BlobData::BlobWrapper(Box::new(BlobWrapperBlob::from_data_owned(ticket_data))),
);
self.state = BlobsState::TicketAdded;
Ok(())
}
/// Create the embedded signature "superblob" data.
pub fn create_superblob(&self) -> Result<Vec<u8>, AppleCodesignError> {
if matches!(self.state, BlobsState::Empty | BlobsState::SpecialAdded) {
return Err(AppleCodesignError::SignatureBuilder(
"code directory required in order to materialize superblob",
));
}
let blobs = self
.blobs
.iter()
.map(|(slot, blob)| {
let data = blob.to_blob_bytes()?;
Ok((*slot, data))
})
.collect::<Result<Vec<_>, AppleCodesignError>>()?;
create_superblob(CodeSigningMagic::EmbeddedSignature, blobs.iter())
}src/cli.rs (line 1319)
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
fn command_extract(args: &ArgMatches) -> Result<(), AppleCodesignError> {
let path = args
.get_one::<String>("path")
.ok_or(AppleCodesignError::CliBadArgument)?;
let format = args
.get_one::<String>("data")
.ok_or(AppleCodesignError::CliBadArgument)?;
let index = args.get_one::<String>("universal_index").unwrap();
let index = usize::from_str(index).map_err(|_| AppleCodesignError::CliBadArgument)?;
let data = std::fs::read(path)?;
let mach = MachFile::parse(&data)?;
let macho = mach.nth_macho(index)?;
match format.as_str() {
"blobs" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
for blob in embedded.blobs {
let parsed = blob.into_parsed_blob()?;
println!("{parsed:#?}");
}
}
"cms-info" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(cms) = embedded.signature_data()? {
let signed_data = SignedData::parse_ber(cms)?;
let cd_data = if let Ok(Some(blob)) = embedded.code_directory() {
Some(blob.to_blob_bytes()?)
} else {
None
};
print_signed_data("", &signed_data, cd_data)?;
} else {
eprintln!("no CMS data");
}
}
"cms-pem" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(cms) = embedded.signature_data()? {
print!(
"{}",
pem::encode(&pem::Pem {
tag: "PKCS7".to_string(),
contents: cms.to_vec(),
})
);
} else {
eprintln!("no CMS data");
}
}
"cms-raw" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(cms) = embedded.signature_data()? {
std::io::stdout().write_all(cms)?;
} else {
eprintln!("no CMS data");
}
}
"cms" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(signed_data) = embedded.signed_data()? {
println!("{signed_data:#?}");
} else {
eprintln!("no CMS data");
}
}
"code-directory-raw" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(blob) = embedded.find_slot(CodeSigningSlot::CodeDirectory) {
std::io::stdout().write_all(blob.data)?;
} else {
eprintln!("no code directory");
}
}
"code-directory-serialized-raw" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Ok(Some(cd)) = embedded.code_directory() {
std::io::stdout().write_all(&cd.to_blob_bytes()?)?;
} else {
eprintln!("no code directory");
}
}
"code-directory-serialized" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Ok(Some(cd)) = embedded.code_directory() {
let serialized = cd.to_blob_bytes()?;
println!("{:#?}", CodeDirectoryBlob::from_blob_bytes(&serialized)?);
}
}
"code-directory" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(cd) = embedded.code_directory()? {
println!("{cd:#?}");
} else {
eprintln!("no code directory");
}
}
"linkedit-info" => {
let sig = macho
.find_signature_data()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
println!("__LINKEDIT segment index: {}", sig.linkedit_segment_index);
println!(
"__LINKEDIT segment start offset: {}",
sig.linkedit_segment_start_offset
);
println!(
"__LINKEDIT segment end offset: {}",
sig.linkedit_segment_end_offset
);
println!(
"__LINKEDIT segment size: {}",
sig.linkedit_segment_data.len()
);
println!(
"__LINKEDIT signature global start offset: {}",
sig.linkedit_signature_start_offset
);
println!(
"__LINKEDIT signature global end offset: {}",
sig.linkedit_signature_end_offset
);
println!(
"__LINKEDIT signature local segment start offset: {}",
sig.signature_start_offset
);
println!(
"__LINKEDIT signature local segment end offset: {}",
sig.signature_end_offset
);
println!("__LINKEDIT signature size: {}", sig.signature_data.len());
}
"linkedit-segment-raw" => {
let sig = macho
.find_signature_data()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
std::io::stdout().write_all(sig.linkedit_segment_data)?;
}
"macho-load-commands" => {
println!("load command count: {}", macho.macho.load_commands.len());
for command in &macho.macho.load_commands {
println!(
"{}; offsets=0x{:x}-0x{:x} ({}-{}); size={}",
goblin::mach::load_command::cmd_to_str(command.command.cmd()),
command.offset,
command.offset + command.command.cmdsize(),
command.offset,
command.offset + command.command.cmdsize(),
command.command.cmdsize(),
);
}
}
"macho-segments" => {
println!("segments count: {}", macho.macho.segments.len());
for (segment_index, segment) in macho.macho.segments.iter().enumerate() {
let sections = segment.sections()?;
println!(
"segment #{}; {}; offsets=0x{:x}-0x{:x}; vm/file size {}/{}; section count {}",
segment_index,
segment.name()?,
segment.fileoff,
segment.fileoff as usize + segment.data.len(),
segment.vmsize,
segment.filesize,
sections.len()
);
for (section_index, (section, _)) in sections.into_iter().enumerate() {
println!(
"segment #{}; section #{}: {}; segment offsets=0x{:x}-0x{:x} size {}",
segment_index,
section_index,
section.name()?,
section.offset,
section.offset as u64 + section.size,
section.size
);
}
}
}
"macho-target" => {
if let Some(target) = macho.find_targeting()? {
println!("Platform: {}", target.platform);
println!("Minimum OS: {}", target.minimum_os_version);
println!("SDK: {}", target.sdk_version);
} else {
println!("Unable to resolve Mach-O targeting from load commands");
}
}
"requirements-raw" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(blob) = embedded.find_slot(CodeSigningSlot::RequirementSet) {
std::io::stdout().write_all(blob.data)?;
} else {
eprintln!("no requirements");
}
}
"requirements-rust" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(reqs) = embedded.code_requirements()? {
for (typ, req) in &reqs.requirements {
for expr in req.parse_expressions()?.iter() {
println!("{typ} => {expr:#?}");
}
}
} else {
eprintln!("no requirements");
}
}
"requirements-serialized-raw" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(reqs) = embedded.code_requirements()? {
std::io::stdout().write_all(&reqs.to_blob_bytes()?)?;
} else {
eprintln!("no requirements");
}
}
"requirements-serialized" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(reqs) = embedded.code_requirements()? {
let serialized = reqs.to_blob_bytes()?;
println!("{:#?}", RequirementSetBlob::from_blob_bytes(&serialized)?);
} else {
eprintln!("no requirements");
}
}
"requirements" => {
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
if let Some(reqs) = embedded.code_requirements()? {
for (typ, req) in &reqs.requirements {
for expr in req.parse_expressions()?.iter() {
println!("{typ} => {expr}");
}
}
} else {
eprintln!("no requirements");
}
}
"signature-raw" => {
let sig = macho
.find_signature_data()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
std::io::stdout().write_all(sig.signature_data)?;
}
"superblob" => {
let sig = macho
.find_signature_data()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
let embedded = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
println!("file start offset: {}", sig.linkedit_signature_start_offset);
println!("file end offset: {}", sig.linkedit_signature_end_offset);
println!("__LINKEDIT start offset: {}", sig.signature_start_offset);
println!("__LINKEDIT end offset: {}", sig.signature_end_offset);
println!("length: {}", embedded.length);
println!("blob count: {}", embedded.count);
println!("blobs:");
for blob in embedded.blobs {
println!("- index: {}", blob.index);
println!(
" offsets: 0x{:x}-0x{:x} ({}-{})",
blob.offset,
blob.offset + blob.length - 1,
blob.offset,
blob.offset + blob.length - 1
);
println!(" length: {}", blob.length);
println!(" slot: {:?}", blob.slot);
println!(" magic: {:?} (0x{:x})", blob.magic, u32::from(blob.magic));
println!(
" sha1: {}",
hex::encode(blob.digest_with(DigestType::Sha1)?)
);
println!(
" sha256: {}",
hex::encode(blob.digest_with(DigestType::Sha256)?)
);
println!(
" sha256-truncated: {}",
hex::encode(blob.digest_with(DigestType::Sha256Truncated)?)
);
println!(
" sha384: {}",
hex::encode(blob.digest_with(DigestType::Sha384)?),
);
println!(
" sha512: {}",
hex::encode(blob.digest_with(DigestType::Sha512)?),
);
println!(
" sha1-base64: {}",
base64::encode(blob.digest_with(DigestType::Sha1)?)
);
println!(
" sha256-base64: {}",
base64::encode(blob.digest_with(DigestType::Sha256)?)
);
println!(
" sha256-truncated-base64: {}",
base64::encode(blob.digest_with(DigestType::Sha256Truncated)?)
);
println!(
" sha384-base64: {}",
base64::encode(blob.digest_with(DigestType::Sha384)?)
);
println!(
" sha512-base64: {}",
base64::encode(blob.digest_with(DigestType::Sha512)?)
);
}
}
_ => panic!("unhandled format: {format}"),
}
Ok(())
}sourcefn digest_with(
&self,
hash_type: DigestType
) -> Result<Vec<u8>, AppleCodesignError>
fn digest_with(
&self,
hash_type: DigestType
) -> Result<Vec<u8>, AppleCodesignError>
Obtain the digest of the blob using the specified hasher.
Default implementation calls Blob::to_blob_bytes and digests that, which should always be correct.
Examples found in repository?
src/bundle_signing.rs (line 251)
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
pub fn notarization_ticket_record_name(&self) -> Result<String, AppleCodesignError> {
let cd = self.code_directory()?;
let digest_type: u8 = cd.digest_type.into();
let mut digest = cd.digest_with(cd.digest_type)?;
// Digests appear to be truncated at 20 bytes / 40 characters.
digest.truncate(20);
let digest = hex::encode(digest);
// Unsure what the leading `2/` means.
Ok(format!("2/{digest_type}/{digest}"))
}More examples
src/stapling.rs (line 197)
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
pub fn lookup_ticket_for_dmg(&self, dmg: &DmgReader) -> Result<Vec<u8>, AppleCodesignError> {
// The ticket is derived from the code directory digest from the signature in the
// DMG.
let signature = dmg
.embedded_signature()?
.ok_or(AppleCodesignError::DmgStapleNoSignature)?;
let cd = signature
.code_directory()?
.ok_or(AppleCodesignError::DmgStapleNoSignature)?;
let mut digest = cd.digest_with(cd.digest_type)?;
digest.truncate(20);
let digest = hex::encode(digest);
let digest_type: u8 = cd.digest_type.into();
let record_name = format!("2/{digest_type}/{digest}");
let response = lookup_notarization_ticket(&self.client, &record_name)?;
response.signed_ticket(&record_name)
}src/embedded_signature_builder.rs (line 165)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
pub fn add_code_directory(
&mut self,
cd_slot: CodeSigningSlot,
mut cd: CodeDirectoryBlob<'a>,
) -> Result<&CodeDirectoryBlob, AppleCodesignError> {
if matches!(self.state, BlobsState::SignatureAdded) {
return Err(AppleCodesignError::SignatureBuilder(
"cannot add code directory after signature data added",
));
}
for (slot, blob) in &self.blobs {
// Not all slots are expressible in the cd specials list!
if !slot.is_code_directory_specials_expressible() {
continue;
}
let digest = blob.digest_with(cd.digest_type)?;
cd.set_slot_digest(*slot, digest)?;
}
self.blobs.insert(cd_slot, cd.into());
self.state = BlobsState::CodeDirectoryAdded;
Ok(self.code_directory().expect("we just inserted this key"))
}
/// Add an alternative code directory.
///
/// This is a wrapper for [Self::add_code_directory()] that has logic for determining the
/// appropriate slot for the code directory.
pub fn add_alternative_code_directory(
&mut self,
cd: CodeDirectoryBlob<'a>,
) -> Result<&CodeDirectoryBlob, AppleCodesignError> {
let mut our_slot = CodeSigningSlot::AlternateCodeDirectory0;
for slot in self.blobs.keys() {
if slot.is_alternative_code_directory() {
our_slot = CodeSigningSlot::from(u32::from(*slot) + 1);
if !our_slot.is_alternative_code_directory() {
return Err(AppleCodesignError::SignatureBuilder(
"no more available alternative code directory slots",
));
}
}
}
self.add_code_directory(our_slot, cd)
}
/// The a CMS signature and register its signature blob.
///
/// `signing_key` and `signing_cert` denote the keypair being used to produce a
/// cryptographic signature.
///
/// `time_stamp_url` is an optional time-stamp protocol server to use to record
/// the signature in.
///
/// `certificates` are extra X.509 certificates to register in the signing chain.
///
/// This method errors if called before a code directory is registered.
pub fn create_cms_signature(
&mut self,
signing_key: &dyn KeyInfoSigner,
signing_cert: &CapturedX509Certificate,
time_stamp_url: Option<&Url>,
certificates: impl Iterator<Item = CapturedX509Certificate>,
) -> Result<(), AppleCodesignError> {
let main_cd = self
.code_directory()
.ok_or(AppleCodesignError::SignatureBuilder(
"cannot create CMS signature unless code directory is present",
))?;
if let Some(cn) = signing_cert.subject_common_name() {
warn!("creating cryptographic signature with certificate {}", cn);
}
let mut cdhashes = vec![];
let mut attributes = vec![];
for (slot, blob) in &self.blobs {
if *slot == CodeSigningSlot::CodeDirectory || slot.is_alternative_code_directory() {
if let BlobData::CodeDirectory(cd) = blob {
// plist digests use the native digest of the code directory but always
// truncated at 20 bytes.
let mut digest = cd.digest_with(cd.digest_type)?;
digest.truncate(20);
cdhashes.push(plist::Value::Data(digest));
// ASN.1 values are a SEQUENCE of (OID, OctetString) with the native
// digest.
let digest = cd.digest_with(cd.digest_type)?;
let alg = DigestAlgorithm::try_from(cd.digest_type)?;
attributes.push(AttributeValue::new(bcder::Captured::from_values(
bcder::Mode::Der,
bcder::encode::sequence((
Oid::from(alg).encode_ref(),
bcder::OctetString::new(digest.into()).encode_ref(),
)),
)));
} else {
return Err(AppleCodesignError::SignatureBuilder(
"unexpected blob type in code directory slot",
));
}
}
}
let mut plist_dict = plist::Dictionary::new();
plist_dict.insert("cdhashes".to_string(), plist::Value::Array(cdhashes));
let mut plist_xml = vec![];
plist::Value::from(plist_dict)
.to_writer_xml(&mut plist_xml)
.map_err(AppleCodesignError::CodeDirectoryPlist)?;
// We also need to include a trailing newline to conform with Apple's XML
// writer.
plist_xml.push(b'\n');
let signer = SignerBuilder::new(signing_key, signing_cert.clone())
.message_id_content(main_cd.to_blob_bytes()?)
.signed_attribute_octet_string(
Oid(Bytes::copy_from_slice(CD_DIGESTS_PLIST_OID.as_ref())),
&plist_xml,
);
let signer = signer.signed_attribute(Oid(CD_DIGESTS_OID.as_ref().into()), attributes);
let signer = if let Some(time_stamp_url) = time_stamp_url {
info!("Using time-stamp server {}", time_stamp_url);
signer.time_stamp_url(time_stamp_url.clone())?
} else {
signer
};
let der = SignedDataBuilder::default()
// The default is `signed-data`. But Apple appears to use the `data` content-type,
// in violation of RFC 5652 Section 5, which says `signed-data` should be
// used when there are signatures.
.content_type(Oid(OID_ID_DATA.as_ref().into()))
.signer(signer)
.certificates(certificates)
.build_der()?;
self.blobs.insert(
CodeSigningSlot::Signature,
BlobData::BlobWrapper(Box::new(BlobWrapperBlob::from_data_owned(der))),
);
self.state = BlobsState::SignatureAdded;
Ok(())
}