Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 119 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion apple-codesign/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ num-traits = "0.2.19"
object = { version = "0.38.1", features = ["write"] }
oid-registry = "0.8.1"
once_cell = "1.21.3"
p12 = "0.6.3"
p12-keystore = "=0.2.0"
p256 = { version = "0.13.2", default-features = false, features = ["arithmetic", "pkcs8", "std"] }
pem = "3.0.6"
pkcs1 = { version = "0.7.5", features = ["alloc", "std", "pkcs8"] }
Expand Down
31 changes: 22 additions & 9 deletions apple-codesign/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,14 +603,27 @@ impl CliCommand for GenerateSelfSignedCertificate {
if let Some(path) = &self.p12_path {
let password = get_pkcs12_password(self.p12_password.clone(), None::<PathBuf>)?;

let pfx = p12::PFX::new(
&cert.encode_der()?,
&key_pair.to_pkcs8_one_asymmetric_key_der(),
None,
&password,
"code-signing",
)
.ok_or_else(|| {
let chain = vec![p12_keystore::Certificate::from_der(&cert.encode_der()?).map_err(|e| {
AppleCodesignError::CliGeneralError(format!("error processing certificate: {e:?}").into())
})?];

let local_key_id = {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(&key_pair.to_pkcs8_one_asymmetric_key_der());
let hash = hasher.finalize();
hash[..8].to_vec()
};

let keychain = p12_keystore::PrivateKeyChain::new(&key_pair.to_pkcs8_one_asymmetric_key_der(), local_key_id, chain);

let entry = p12_keystore::KeyStoreEntry::PrivateKeyChain(keychain);

let mut keystore = p12_keystore::KeyStore::new();
keystore.add_entry("code-signing", entry);
let writer = keystore.writer(&password);

let pfx = writer.write().map_err(|_e| {
AppleCodesignError::CliGeneralError("failed to create PFX structure".into())
})?;

Expand All @@ -619,7 +632,7 @@ impl CliCommand for GenerateSelfSignedCertificate {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, pfx.to_der())?;
std::fs::write(path, pfx)?;

wrote_file = true;
}
Expand Down
108 changes: 19 additions & 89 deletions apple-codesign/src/cryptography.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,19 +682,19 @@ impl MultiDigest {
}
}

fn bmp_string(s: &str) -> Vec<u8> {
let utf16: Vec<u16> = s.encode_utf16().collect();
// fn bmp_string(s: &str) -> Vec<u8> {
// let utf16: Vec<u16> = s.encode_utf16().collect();

let mut bytes = Vec::with_capacity(utf16.len() * 2 + 2);
for c in utf16 {
bytes.push((c / 256) as u8);
bytes.push((c % 256) as u8);
}
bytes.push(0x00);
bytes.push(0x00);
// let mut bytes = Vec::with_capacity(utf16.len() * 2 + 2);
// for c in utf16 {
// bytes.push((c / 256) as u8);
// bytes.push((c % 256) as u8);
// }
// bytes.push(0x00);
// bytes.push(0x00);

bytes
}
// bytes
// }

/// Parse PFX data into a key pair.
///
Expand All @@ -708,93 +708,23 @@ pub fn parse_pfx_data(
data: &[u8],
password: &str,
) -> Result<(CapturedX509Certificate, InMemoryPrivateKey), AppleCodesignError> {
let pfx = p12::PFX::parse(data).map_err(|e| {
AppleCodesignError::PfxParseError(format!("data does not appear to be PFX: {e:?}"))
let keystore = p12_keystore::KeyStore::from_pkcs12(data, password).map_err(|e| {
AppleCodesignError::PfxParseError(format!("error when processing p12: {e:?}"))
})?;

if !pfx.verify_mac(password) {
return Err(AppleCodesignError::PfxBadPassword);
}

// Apple's certificate export format consists of regular data content info
// with inner ContentInfo components holding the key and certificate.
let data = match pfx.auth_safe {
p12::ContentInfo::Data(data) => data,
_ => {
// with chain variable holding the key and certificate.
let chain = match keystore.private_key_chain() {
Some((_alias, chain)) => chain,
None => {
return Err(AppleCodesignError::PfxParseError(
"unexpected PFX content info".to_string(),
));
}
};

let content_infos = yasna::parse_der(&data, |reader| {
reader.collect_sequence_of(p12::ContentInfo::parse)
})
.map_err(|e| {
AppleCodesignError::PfxParseError(format!("failed parsing inner ContentInfo: {e:?}"))
})?;

let bmp_password = bmp_string(password);

let mut certificate = None;
let mut signing_key = None;

for content in content_infos {
let bags_data = match content {
p12::ContentInfo::Data(inner) => inner,
p12::ContentInfo::EncryptedData(encrypted) => {
encrypted.data(&bmp_password).ok_or_else(|| {
AppleCodesignError::PfxParseError(
"failed decrypting inner EncryptedData".to_string(),
)
})?
}
p12::ContentInfo::OtherContext(_) => {
return Err(AppleCodesignError::PfxParseError(
"unexpected OtherContent content in inner PFX data".to_string(),
));
}
};

let bags = yasna::parse_ber(&bags_data, |reader| {
reader.collect_sequence_of(p12::SafeBag::parse)
})
.map_err(|e| {
AppleCodesignError::PfxParseError(format!(
"failed parsing SafeBag within inner Data: {e:?}"
))
})?;

for bag in bags {
match bag.bag {
p12::SafeBagKind::CertBag(cert_bag) => match cert_bag {
p12::CertBag::X509(cert_data) => {
certificate = Some(CapturedX509Certificate::from_der(cert_data)?);
}
p12::CertBag::SDSI(_) => {
return Err(AppleCodesignError::PfxParseError(
"unexpected SDSI certificate data".to_string(),
));
}
},
p12::SafeBagKind::Pkcs8ShroudedKeyBag(key_bag) => {
let decrypted = key_bag.decrypt(&bmp_password).ok_or_else(|| {
AppleCodesignError::PfxParseError(
"error decrypting PKCS8 shrouded key bag; is the password correct?"
.to_string(),
)
})?;

signing_key = Some(InMemoryPrivateKey::from_pkcs8_der(decrypted)?);
}
p12::SafeBagKind::OtherBagKind(_) => {
return Err(AppleCodesignError::PfxParseError(
"unexpected bag type in inner PFX content".to_string(),
));
}
}
}
}
let certificate = Some(CapturedX509Certificate::from_der(chain.chain()[0].as_der())?);
let signing_key = Some(InMemoryPrivateKey::from_pkcs8_der(chain.key())?);

match (certificate, signing_key) {
(Some(certificate), Some(signing_key)) => Ok((certificate, signing_key)),
Expand Down
Loading