use crate::acl::{AclBlob, TrustedApplication};
use crate::crypto::{self, BLOCK_SIZE, DbBlob, SALT_LEN, SecretBytes, Ssgp};
use crate::db::FOUR_CHAR_CODE_ATTRIBUTES;
use crate::db::KeychainFile;
use crate::error::{Error, Result};
use crate::format::Value;
use crate::schema::{AttributeFormat, RecordType};
use crate::secret::random_bytes;
#[derive(Debug, Clone, Default)]
pub struct ItemChanges {
pub label: Option<String>,
pub description: Option<String>,
pub comment: Option<String>,
pub generic: Option<Vec<u8>>,
pub security_domain: Option<String>,
pub attributes: Vec<(String, Value)>,
}
impl ItemChanges {
pub fn is_empty(&self) -> bool {
self.label.is_none()
&& self.description.is_none()
&& self.comment.is_none()
&& self.generic.is_none()
&& self.security_domain.is_none()
&& self.attributes.is_empty()
}
fn pairs(&self) -> Vec<(String, Value)> {
let mut pairs = Vec::new();
let mut text = |name: &str, value: &Option<String>| {
if let Some(value) = value {
pairs.push((name.to_string(), Value::Blob(value.as_bytes().to_vec())));
}
};
text("PrintName", &self.label);
text("desc", &self.description);
text("icmt", &self.comment);
text("sdmn", &self.security_domain);
if let Some(generic) = &self.generic {
pairs.push(("gena".to_string(), Value::Blob(generic.clone())));
}
pairs.extend(self.attributes.iter().cloned());
pairs
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Settings {
pub idle_timeout: u32,
pub lock_on_sleep: bool,
}
impl Settings {
pub const NO_TIMEOUT: u32 = 0x7fff_ffff;
pub fn never_times_out(&self) -> bool {
self.idle_timeout == Self::NO_TIMEOUT
}
fn validate(&self) -> Result<()> {
if self.idle_timeout == 0 || self.idle_timeout > Self::NO_TIMEOUT {
return Err(Error::other(format!(
"an idle timeout of {} is out of range; macOS accepts 1..={} \
seconds, where {} means never",
self.idle_timeout,
Self::NO_TIMEOUT,
Self::NO_TIMEOUT
)));
}
Ok(())
}
}
impl KeychainFile {
pub fn update_item(
&mut self,
record_type: RecordType,
record_number: u32,
changes: &ItemChanges,
secret: Option<&[u8]>,
timestamp: &str,
) -> Result<()> {
if changes.is_empty() && secret.is_none() {
return Err(Error::other("nothing to change"));
}
let relation = self
.schema()
.relation(record_type)
.ok_or_else(|| {
Error::format(format!("keychain has no 0x{:08x} relation", record_type.0))
})?
.clone();
let identity: Vec<u32> = self
.keychain()
.table(record_type)
.and_then(|table| table.unique_index_attribute_ids().map(<[u32]>::to_vec))
.unwrap_or_default();
let mut updates = Vec::new();
for (name, value) in changes.pairs() {
let position = relation.index_of(&name).ok_or_else(|| {
Error::other(format!(
"{} has no attribute named {name:?}",
record_type.name()
))
})?;
let attribute = &relation.attributes[position];
if identity.contains(&attribute.id) {
return Err(Error::other(format!(
"{name} identifies the item; change it by deleting and adding, not updating"
)));
}
updates.push((position, coerce(&name, value, attribute.format)?));
}
let payload = match secret {
None => None,
Some(secret) => {
let item = self
.items_of_type(record_type)
.into_iter()
.find(|item| item.number() == record_number)
.ok_or(Error::NoSuchItem)?;
let ssgp = Ssgp::parse(&item.record.key_data)?;
let key = self.item_key(&ssgp.label).ok_or_else(|| {
if self.is_unlocked() {
Error::MissingItemKey {
label: ssgp.label_hex(),
}
} else {
Error::Locked
}
})?;
let mut iv = [0u8; BLOCK_SIZE];
iv.copy_from_slice(&random_bytes(BLOCK_SIZE));
Some(Ssgp::seal(ssgp.label, iv, key.as_slice(), secret)?.to_bytes())
}
};
let modified = relation.index_of("mdat");
let keychain = self.keychain_mut();
keychain.bump_commit_version();
let version = keychain.commit_version.unwrap_or(1);
let table = keychain
.table_mut(record_type)
.ok_or(Error::MissingTable("item table"))?;
let record = table
.records_mut()
.find(|record| record.number == record_number)
.ok_or(Error::NoSuchItem)?;
for (position, value) in updates {
record.set_attribute(position, Some(value));
}
if let Some(position) = modified {
record.set_attribute(position, Some(Value::Date(date_bytes(timestamp))));
}
if let Some(payload) = payload {
record.key_data = payload;
}
record.version = version;
table.rebuild_indexes(&relation)?;
Ok(())
}
pub fn delete_item(&mut self, record_type: RecordType, record_number: u32) -> Result<usize> {
let item = self
.items_of_type(record_type)
.into_iter()
.find(|item| item.number() == record_number)
.ok_or(Error::NoSuchItem)?;
let label = Ssgp::parse(&item.record.key_data)
.ok()
.map(|ssgp| ssgp.label);
let key_record = label.and_then(|label| self.key_record_number(&label));
let schema = self.schema().clone();
let keychain = self.keychain_mut();
let mut removed = 0;
{
let table = keychain
.table_mut(record_type)
.ok_or(Error::MissingTable("item table"))?;
if table.delete(record_number) {
removed += 1;
}
if let Some(relation) = schema.relation(record_type) {
table.rebuild_indexes(relation)?;
}
}
if let Some(number) = key_record
&& let Some(table) = keychain.table_mut(RecordType::SYMMETRIC_KEY)
{
if table.delete(number) {
removed += 1;
}
if let Some(relation) = schema.relation(RecordType::SYMMETRIC_KEY) {
table.rebuild_indexes(relation)?;
}
}
for _ in 0..removed {
keychain.bump_commit_version();
}
if let Some(label) = label {
self.forget_item_key(&label);
}
Ok(removed)
}
pub fn delete_certificate(&mut self, public_key_hash: &[u8]) -> Result<usize> {
self.delete_identity_records(public_key_hash, false)
}
pub fn delete_identity(&mut self, public_key_hash: &[u8]) -> Result<usize> {
self.delete_identity_records(public_key_hash, true)
}
fn delete_identity_records(
&mut self,
public_key_hash: &[u8],
include_keys: bool,
) -> Result<usize> {
let mut targets: Vec<(RecordType, u32)> = Vec::new();
for record in self.records_of_type(RecordType::X509_CERTIFICATE) {
let matches = self
.schema()
.attribute(RecordType::X509_CERTIFICATE, record, "PublicKeyHash")
.and_then(Value::as_bytes)
.is_some_and(|hash| hash == public_key_hash);
if matches {
targets.push((RecordType::X509_CERTIFICATE, record.number));
}
}
for record_type in [RecordType::PRIVATE_KEY, RecordType::PUBLIC_KEY] {
if !include_keys {
break;
}
for record in self.records_of_type(record_type) {
let matches = self
.schema()
.attribute(record_type, record, "Label")
.and_then(Value::as_bytes)
.is_some_and(|label| label == public_key_hash);
if matches {
targets.push((record_type, record.number));
}
}
}
if targets.is_empty() {
return Err(Error::NoSuchItem);
}
let schema = self.schema().clone();
let keychain = self.keychain_mut();
let mut removed = 0;
for (record_type, number) in targets {
let Some(table) = keychain.table_mut(record_type) else {
continue;
};
if table.delete(number) {
removed += 1;
}
if let Some(relation) = schema.relation(record_type) {
table.rebuild_indexes(relation)?;
}
}
for _ in 0..removed {
keychain.bump_commit_version();
}
Ok(removed)
}
pub fn set_item_trust(
&mut self,
record_type: RecordType,
record_number: u32,
trusted: &[TrustedApplication],
) -> Result<()> {
let keys = self.keys().ok_or(Error::Locked)?;
let signing_key = SecretBytes::new(keys.signing_key.as_slice());
let item = self
.items_of_type(record_type)
.into_iter()
.find(|item| item.number() == record_number)
.ok_or(Error::NoSuchItem)?;
let label = Ssgp::parse(&item.record.key_data)?.label;
let number = self
.key_record_number(&label)
.ok_or_else(|| Error::MissingItemKey {
label: hex::encode(label),
})?;
let existing = self
.records_of_type(RecordType::SYMMETRIC_KEY)
.into_iter()
.find(|record| record.number == number)
.map(|record| crypto::KeyBlob::parse(&record.key_data))
.transpose()?
.ok_or(Error::NoSuchItem)?;
if existing.public_acl.item_name().is_none() {
return Err(Error::other(
"this item's access control is in a form this build does not parse; \
refusing to overwrite it",
));
}
let name = existing
.public_acl
.item_name()
.map(str::to_string)
.or_else(|| item.label())
.unwrap_or_default();
let acl = if trusted.is_empty() {
AclBlob::for_item(&name)
} else {
AclBlob::for_item_trusting(&name, trusted.to_vec())
};
let keychain = self.keychain_mut();
keychain.bump_commit_version();
let table = keychain
.table_mut(RecordType::SYMMETRIC_KEY)
.ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_SYMMETRIC_KEY"))?;
let record = table
.records_mut()
.find(|record| record.number == number)
.ok_or(Error::NoSuchItem)?;
let mut blob = crypto::KeyBlob::parse(&record.key_data)?;
blob.public_acl = crypto::PublicAcl::Parsed(acl);
blob.sign(signing_key.as_slice());
record.key_data = blob.to_bytes();
Ok(())
}
pub fn change_password(&mut self, old: &[u8], new: &[u8]) -> Result<()> {
let mut blob = self.db_blob()?;
let keys = blob.unlock(old)?;
blob.salt.copy_from_slice(&random_bytes(SALT_LEN));
blob.iv.copy_from_slice(&random_bytes(BLOCK_SIZE));
blob.seal(new, &keys)?;
self.replace_db_blob(&blob)?;
self.unlock(new)
}
pub fn settings(&self) -> Result<Settings> {
let blob = self.db_blob()?;
Ok(Settings {
idle_timeout: blob.idle_timeout,
lock_on_sleep: blob.lock_on_sleep,
})
}
pub fn set_settings(&mut self, settings: &Settings) -> Result<()> {
settings.validate()?;
let keys = self.keys().ok_or(Error::Locked)?;
let signing_key = SecretBytes::new(keys.signing_key.as_slice());
let mut blob = self.db_blob()?;
blob.idle_timeout = settings.idle_timeout;
blob.lock_on_sleep = settings.lock_on_sleep;
blob.sign(signing_key.as_slice());
self.replace_db_blob(&blob)
}
fn replace_db_blob(&mut self, blob: &DbBlob) -> Result<()> {
let bytes = blob.to_bytes();
let keychain = self.keychain_mut();
keychain.bump_commit_version();
let table = keychain
.table_mut(RecordType::METADATA)
.ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_METADATA"))?;
let record = table
.records_mut()
.next()
.ok_or_else(|| Error::format("metadata table has no record"))?;
record.key_data = bytes;
record.unknown3 = record.unknown3.wrapping_add(1);
Ok(())
}
fn key_record_number(&self, label: &[u8; 20]) -> Option<u32> {
self.records_of_type(RecordType::SYMMETRIC_KEY)
.into_iter()
.find(|record| {
self.schema()
.attribute(RecordType::SYMMETRIC_KEY, record, "Label")
.and_then(Value::as_bytes)
.is_some_and(|stored| stored == label)
})
.map(|record| record.number)
}
}
fn coerce(name: &str, value: Value, format: AttributeFormat) -> Result<Value> {
let bytes = match &value {
Value::Blob(bytes) | Value::String(bytes) => bytes.clone(),
Value::Uint32(_) | Value::Sint32(_) => {
return match format {
AttributeFormat::Uint32 | AttributeFormat::Sint32 => Ok(value),
_ => Err(Error::other(format!("{name} is not a number attribute"))),
};
}
Value::Date(_) => {
return match format {
AttributeFormat::TimeDate => Ok(value),
_ => Err(Error::other(format!("{name} is not a date attribute"))),
};
}
};
let text = String::from_utf8_lossy(&bytes).into_owned();
match format {
AttributeFormat::Blob | AttributeFormat::String => Ok(Value::Blob(bytes)),
AttributeFormat::Uint32 | AttributeFormat::Sint32 => {
if FOUR_CHAR_CODE_ATTRIBUTES.contains(&name) && bytes.len() == 4 {
let code = u32::from_be_bytes(bytes[..4].try_into().expect("four bytes"));
return Ok(Value::Uint32(code));
}
let number: i64 = text.trim().parse().map_err(|_| {
Error::other(format!(
"{name} is a number attribute; {text:?} is not a number"
))
})?;
match format {
AttributeFormat::Uint32 => u32::try_from(number)
.map(Value::Uint32)
.map_err(|_| Error::other(format!("{number} does not fit {name}"))),
_ => i32::try_from(number)
.map(Value::Sint32)
.map_err(|_| Error::other(format!("{number} does not fit {name}"))),
}
}
AttributeFormat::TimeDate => {
let trimmed = text.trim_end_matches('\0');
if trimmed.len() != 15 || !trimmed.ends_with('Z') {
return Err(Error::other(format!(
"{name} is a date; expected YYYYMMDDhhmmssZ, got {trimmed:?}"
)));
}
Ok(Value::Date(date_bytes(trimmed)))
}
other => Err(Error::other(format!(
"{name} has attribute format {other:?}, which this build cannot write"
))),
}
}
fn date_bytes(timestamp: &str) -> Vec<u8> {
let mut bytes = timestamp.as_bytes().to_vec();
bytes.resize(16, 0);
bytes
}
#[derive(Debug, Clone)]
pub struct StoredIdentity {
pub label: Option<String>,
pub public_key_hash: Vec<u8>,
pub certificate_record: u32,
pub certificate: Vec<u8>,
pub private_key_record: Option<u32>,
}
impl KeychainFile {
pub fn identities(&self) -> Vec<StoredIdentity> {
let mut key_by_label: Vec<(Vec<u8>, u32)> = Vec::new();
for record in self.records_of_type(RecordType::PRIVATE_KEY) {
if let Some(label) = self
.schema()
.attribute(RecordType::PRIVATE_KEY, record, "Label")
.and_then(Value::as_bytes)
{
key_by_label.push((label.to_vec(), record.number));
}
}
self.records_of_type(RecordType::X509_CERTIFICATE)
.into_iter()
.map(|record| {
let public_key_hash = self
.schema()
.attribute(RecordType::X509_CERTIFICATE, record, "PublicKeyHash")
.and_then(Value::as_bytes)
.unwrap_or_default()
.to_vec();
let label = self
.schema()
.attribute(RecordType::X509_CERTIFICATE, record, "PrintName")
.and_then(Value::as_bytes)
.map(|bytes| {
String::from_utf8_lossy(crate::format::trim_nul(bytes)).into_owned()
})
.filter(|name| !name.is_empty());
let private_key_record = key_by_label
.iter()
.find(|(key_label, _)| *key_label == public_key_hash)
.map(|(_, number)| *number);
StoredIdentity {
label,
public_key_hash,
certificate_record: record.number,
certificate: record.key_data.clone(),
private_key_record,
}
})
.collect()
}
pub fn private_key_pkcs8(&self, record_number: u32) -> Result<SecretBytes> {
let keys = self.keys().ok_or(Error::Locked)?;
let record = self
.records_of_type(RecordType::PRIVATE_KEY)
.into_iter()
.find(|record| record.number == record_number)
.ok_or(Error::NoSuchItem)?;
let blob = crypto::KeyBlob::parse(&record.key_data)?;
crypto::unwrap_blob(keys.encryption_key.as_slice(), &blob.iv, &blob.crypto_blob)
}
}