1use crate::acl::{AclBlob, ApplicationAccess, TrustedApplication};
18use crate::crypto::{self, BLOCK_SIZE, DbBlob, SALT_LEN, SecretBytes, Ssgp};
19use crate::db::FOUR_CHAR_CODE_ATTRIBUTES;
20use crate::db::KeychainFile;
21use crate::error::{Error, Result};
22use crate::format::Value;
23use crate::schema::{AttributeFormat, RecordType};
24use crate::secret::random_bytes;
25
26#[derive(Debug, Clone, Default)]
32pub struct ItemChanges {
33 pub label: Option<String>,
35 pub description: Option<String>,
37 pub comment: Option<String>,
39 pub generic: Option<Vec<u8>>,
41 pub security_domain: Option<String>,
43 pub attributes: Vec<(String, Value)>,
49}
50
51impl ItemChanges {
52 pub fn is_empty(&self) -> bool {
54 self.label.is_none()
55 && self.description.is_none()
56 && self.comment.is_none()
57 && self.generic.is_none()
58 && self.security_domain.is_none()
59 && self.attributes.is_empty()
60 }
61
62 fn pairs(&self) -> Vec<(String, Value)> {
64 let mut pairs = Vec::new();
65 let mut text = |name: &str, value: &Option<String>| {
66 if let Some(value) = value {
67 pairs.push((name.to_string(), Value::Blob(value.as_bytes().to_vec())));
68 }
69 };
70 text("PrintName", &self.label);
71 text("desc", &self.description);
72 text("icmt", &self.comment);
73 text("sdmn", &self.security_domain);
74 if let Some(generic) = &self.generic {
75 pairs.push(("gena".to_string(), Value::Blob(generic.clone())));
76 }
77 pairs.extend(self.attributes.iter().cloned());
78 pairs
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct Settings {
85 pub idle_timeout: u32,
89 pub lock_on_sleep: bool,
90}
91
92impl Settings {
93 pub const NO_TIMEOUT: u32 = 0x7fff_ffff;
95
96 pub fn never_times_out(&self) -> bool {
98 self.idle_timeout == Self::NO_TIMEOUT
99 }
100
101 fn validate(&self) -> Result<()> {
106 if self.idle_timeout == 0 || self.idle_timeout > Self::NO_TIMEOUT {
107 return Err(Error::other(format!(
108 "an idle timeout of {} is out of range; macOS accepts 1..={} \
109 seconds, where {} means never",
110 self.idle_timeout,
111 Self::NO_TIMEOUT,
112 Self::NO_TIMEOUT
113 )));
114 }
115 Ok(())
116 }
117}
118
119impl KeychainFile {
120 pub fn update_item(
128 &mut self,
129 record_type: RecordType,
130 record_number: u32,
131 changes: &ItemChanges,
132 secret: Option<&[u8]>,
133 timestamp: &str,
134 ) -> Result<()> {
135 if changes.is_empty() && secret.is_none() {
136 return Err(Error::other("nothing to change"));
137 }
138
139 let relation = self
140 .schema()
141 .relation(record_type)
142 .ok_or_else(|| {
143 Error::format(format!("keychain has no 0x{:08x} relation", record_type.0))
144 })?
145 .clone();
146
147 let identity: Vec<u32> = self
151 .keychain()
152 .table(record_type)
153 .and_then(|table| table.unique_index_attribute_ids().map(<[u32]>::to_vec))
154 .unwrap_or_default();
155 let mut updates = Vec::new();
156 for (name, value) in changes.pairs() {
157 let position = relation.index_of(&name).ok_or_else(|| {
158 Error::other(format!(
159 "{} has no attribute named {name:?}",
160 record_type.name()
161 ))
162 })?;
163 let attribute = &relation.attributes[position];
164 if identity.contains(&attribute.id) {
165 return Err(Error::other(format!(
166 "{name} identifies the item; change it by deleting and adding, not updating"
167 )));
168 }
169 updates.push((position, coerce(&name, value, attribute.format)?));
170 }
171
172 let payload = match secret {
174 None => None,
175 Some(secret) => {
176 let item = self
177 .items_of_type(record_type)
178 .into_iter()
179 .find(|item| item.number() == record_number)
180 .ok_or(Error::NoSuchItem)?;
181 let ssgp = Ssgp::parse(&item.record.key_data)?;
182 let key = self.item_key(&ssgp.label).ok_or_else(|| {
183 if self.is_unlocked() {
184 Error::MissingItemKey {
185 label: ssgp.label_hex(),
186 }
187 } else {
188 Error::Locked
189 }
190 })?;
191 let mut iv = [0u8; BLOCK_SIZE];
192 iv.copy_from_slice(&random_bytes(BLOCK_SIZE));
193 Some(Ssgp::seal(ssgp.label, iv, key.as_slice(), secret)?.to_bytes())
194 }
195 };
196
197 let modified = relation.index_of("mdat");
198 let keychain = self.keychain_mut();
199 keychain.bump_commit_version();
200 let version = keychain.commit_version.unwrap_or(1);
201
202 let table = keychain
203 .table_mut(record_type)
204 .ok_or(Error::MissingTable("item table"))?;
205 let record = table
206 .records_mut()
207 .find(|record| record.number == record_number)
208 .ok_or(Error::NoSuchItem)?;
209
210 for (position, value) in updates {
211 record.set_attribute(position, Some(value));
212 }
213 if let Some(position) = modified {
214 record.set_attribute(position, Some(Value::Date(date_bytes(timestamp))));
215 }
216 if let Some(payload) = payload {
217 record.key_data = payload;
218 }
219 record.version = version;
220
221 table.rebuild_indexes(&relation)?;
222 Ok(())
223 }
224
225 pub fn delete_item(&mut self, record_type: RecordType, record_number: u32) -> Result<usize> {
233 let item = self
234 .items_of_type(record_type)
235 .into_iter()
236 .find(|item| item.number() == record_number)
237 .ok_or(Error::NoSuchItem)?;
238 let label = Ssgp::parse(&item.record.key_data)
240 .ok()
241 .map(|ssgp| ssgp.label);
242
243 let key_record = label.and_then(|label| self.key_record_number(&label));
244
245 let schema = self.schema().clone();
246 let keychain = self.keychain_mut();
247
248 let mut removed = 0;
251 {
252 let table = keychain
253 .table_mut(record_type)
254 .ok_or(Error::MissingTable("item table"))?;
255 if table.delete(record_number) {
256 removed += 1;
257 }
258 if let Some(relation) = schema.relation(record_type) {
259 table.rebuild_indexes(relation)?;
260 }
261 }
262 if let Some(number) = key_record
263 && let Some(table) = keychain.table_mut(RecordType::SYMMETRIC_KEY)
264 {
265 if table.delete(number) {
266 removed += 1;
267 }
268 if let Some(relation) = schema.relation(RecordType::SYMMETRIC_KEY) {
269 table.rebuild_indexes(relation)?;
270 }
271 }
272 for _ in 0..removed {
273 keychain.bump_commit_version();
274 }
275 if let Some(label) = label {
276 self.forget_item_key(&label);
277 }
278 Ok(removed)
279 }
280
281 pub fn delete_certificate(&mut self, public_key_hash: &[u8]) -> Result<usize> {
287 self.delete_identity_records(public_key_hash, false)
288 }
289
290 pub fn delete_identity(&mut self, public_key_hash: &[u8]) -> Result<usize> {
294 self.delete_identity_records(public_key_hash, true)
295 }
296
297 fn delete_identity_records(
298 &mut self,
299 public_key_hash: &[u8],
300 include_keys: bool,
301 ) -> Result<usize> {
302 let mut targets: Vec<(RecordType, u32)> = Vec::new();
303
304 for record in self.records_of_type(RecordType::X509_CERTIFICATE) {
305 let matches = self
306 .schema()
307 .attribute(RecordType::X509_CERTIFICATE, record, "PublicKeyHash")
308 .and_then(Value::as_bytes)
309 .is_some_and(|hash| hash == public_key_hash);
310 if matches {
311 targets.push((RecordType::X509_CERTIFICATE, record.number));
312 }
313 }
314 for record_type in [RecordType::PRIVATE_KEY, RecordType::PUBLIC_KEY] {
315 if !include_keys {
316 break;
317 }
318 for record in self.records_of_type(record_type) {
319 let matches = self
320 .schema()
321 .attribute(record_type, record, "Label")
322 .and_then(Value::as_bytes)
323 .is_some_and(|label| label == public_key_hash);
324 if matches {
325 targets.push((record_type, record.number));
326 }
327 }
328 }
329 if targets.is_empty() {
330 return Err(Error::NoSuchItem);
331 }
332
333 let schema = self.schema().clone();
334 let keychain = self.keychain_mut();
335
336 let mut removed = 0;
337 for (record_type, number) in targets {
338 let Some(table) = keychain.table_mut(record_type) else {
339 continue;
340 };
341 if table.delete(number) {
342 removed += 1;
343 }
344 if let Some(relation) = schema.relation(record_type) {
345 table.rebuild_indexes(relation)?;
346 }
347 }
348 for _ in 0..removed {
349 keychain.bump_commit_version();
350 }
351 Ok(removed)
352 }
353
354 pub fn set_item_trust(
360 &mut self,
361 record_type: RecordType,
362 record_number: u32,
363 trusted: &[TrustedApplication],
364 ) -> Result<()> {
365 let access = if trusted.is_empty() {
366 ApplicationAccess::AllowAny
367 } else {
368 ApplicationAccess::TrustedApplications(trusted.to_vec())
369 };
370 self.set_item_access(record_type, record_number, &access)
371 }
372
373 pub fn set_item_access(
375 &mut self,
376 record_type: RecordType,
377 record_number: u32,
378 access: &ApplicationAccess,
379 ) -> Result<()> {
380 let item = self
381 .items_of_type(record_type)
382 .into_iter()
383 .find(|item| item.number() == record_number)
384 .ok_or(Error::NoSuchItem)?;
385 let label = Ssgp::parse(&item.record.key_data)?.label;
386 let number = self
387 .key_record_number(&label)
388 .ok_or_else(|| Error::MissingItemKey {
389 label: hex::encode(label),
390 })?;
391 let name = item.label().unwrap_or_default();
392 self.set_key_record_access(RecordType::SYMMETRIC_KEY, number, &name, access)
393 }
394
395 pub fn set_private_key_trust(
399 &mut self,
400 record_number: u32,
401 trusted: &[TrustedApplication],
402 ) -> Result<()> {
403 let access = if trusted.is_empty() {
404 ApplicationAccess::AllowAny
405 } else {
406 ApplicationAccess::TrustedApplications(trusted.to_vec())
407 };
408 self.set_private_key_access(record_number, &access)
409 }
410
411 pub fn set_private_key_access(
413 &mut self,
414 record_number: u32,
415 access: &ApplicationAccess,
416 ) -> Result<()> {
417 let record = self
418 .records_of_type(RecordType::PRIVATE_KEY)
419 .into_iter()
420 .find(|record| record.number == record_number)
421 .ok_or(Error::NoSuchItem)?;
422 let name = self
423 .schema()
424 .attribute(RecordType::PRIVATE_KEY, record, "PrintName")
425 .and_then(Value::as_bytes)
426 .map(|bytes| String::from_utf8_lossy(crate::format::trim_nul(bytes)).into_owned())
427 .unwrap_or_default();
428 self.set_key_record_access(RecordType::PRIVATE_KEY, record_number, &name, access)
429 }
430
431 pub fn item_application_access(
433 &self,
434 record_type: RecordType,
435 record_number: u32,
436 ) -> Result<Option<ApplicationAccess>> {
437 let item = self
438 .items_of_type(record_type)
439 .into_iter()
440 .find(|item| item.number() == record_number)
441 .ok_or(Error::NoSuchItem)?;
442 let label = Ssgp::parse(&item.record.key_data)?.label;
443 let number = self
444 .key_record_number(&label)
445 .ok_or_else(|| Error::MissingItemKey {
446 label: hex::encode(label),
447 })?;
448 self.key_record_application_access(RecordType::SYMMETRIC_KEY, number)
449 }
450
451 pub fn private_key_application_access(
453 &self,
454 record_number: u32,
455 ) -> Result<Option<ApplicationAccess>> {
456 self.key_record_application_access(RecordType::PRIVATE_KEY, record_number)
457 }
458
459 pub fn item_trusted_applications(
465 &self,
466 record_type: RecordType,
467 record_number: u32,
468 ) -> Result<Option<Vec<TrustedApplication>>> {
469 let item = self
470 .items_of_type(record_type)
471 .into_iter()
472 .find(|item| item.number() == record_number)
473 .ok_or(Error::NoSuchItem)?;
474 let label = Ssgp::parse(&item.record.key_data)?.label;
475 let number = self
476 .key_record_number(&label)
477 .ok_or_else(|| Error::MissingItemKey {
478 label: hex::encode(label),
479 })?;
480 self.key_record_trusted_applications(RecordType::SYMMETRIC_KEY, number)
481 }
482
483 pub fn private_key_trusted_applications(
485 &self,
486 record_number: u32,
487 ) -> Result<Option<Vec<TrustedApplication>>> {
488 self.key_record_trusted_applications(RecordType::PRIVATE_KEY, record_number)
489 }
490
491 fn key_record_trusted_applications(
492 &self,
493 record_type: RecordType,
494 record_number: u32,
495 ) -> Result<Option<Vec<TrustedApplication>>> {
496 let blob = self
497 .records_of_type(record_type)
498 .into_iter()
499 .find(|record| record.number == record_number)
500 .map(|record| crypto::KeyBlob::parse(&record.key_data))
501 .transpose()?
502 .ok_or(Error::NoSuchItem)?;
503 Ok(blob.public_acl.trusted_applications().map(<[_]>::to_vec))
504 }
505
506 fn key_record_application_access(
507 &self,
508 record_type: RecordType,
509 record_number: u32,
510 ) -> Result<Option<ApplicationAccess>> {
511 let blob = self
512 .records_of_type(record_type)
513 .into_iter()
514 .find(|record| record.number == record_number)
515 .map(|record| crypto::KeyBlob::parse(&record.key_data))
516 .transpose()?
517 .ok_or(Error::NoSuchItem)?;
518 Ok(blob.public_acl.application_access())
519 }
520
521 fn set_key_record_access(
522 &mut self,
523 record_type: RecordType,
524 record_number: u32,
525 fallback_name: &str,
526 access: &ApplicationAccess,
527 ) -> Result<()> {
528 let keys = self.keys().ok_or(Error::Locked)?;
529 let signing_key = SecretBytes::new(keys.signing_key.as_slice());
530
531 let existing = self
535 .records_of_type(record_type)
536 .into_iter()
537 .find(|record| record.number == record_number)
538 .map(|record| crypto::KeyBlob::parse(&record.key_data))
539 .transpose()?
540 .ok_or(Error::NoSuchItem)?;
541 if existing.public_acl.item_name().is_none() {
542 return Err(Error::other(
543 "this item's access control is in a form this build does not parse; \
544 refusing to overwrite it",
545 ));
546 }
547 let name = existing
550 .public_acl
551 .item_name()
552 .map(str::to_string)
553 .unwrap_or_else(|| fallback_name.to_string());
554
555 let acl = AclBlob::for_item_access(&name, access);
556
557 let keychain = self.keychain_mut();
558 keychain.bump_commit_version();
559 let table = keychain
560 .table_mut(record_type)
561 .ok_or(Error::MissingTable("key record table"))?;
562 let record = table
563 .records_mut()
564 .find(|record| record.number == record_number)
565 .ok_or(Error::NoSuchItem)?;
566
567 let mut blob = crypto::KeyBlob::parse(&record.key_data)?;
568 blob.public_acl = crypto::PublicAcl::Parsed(acl);
569 blob.sign(signing_key.as_slice());
570 record.key_data = blob.to_bytes();
571 Ok(())
572 }
573
574 pub fn change_password(&mut self, old: &[u8], new: &[u8]) -> Result<()> {
581 let mut blob = self.db_blob()?;
582 let keys = blob.unlock(old)?;
583
584 blob.salt.copy_from_slice(&random_bytes(SALT_LEN));
585 blob.iv.copy_from_slice(&random_bytes(BLOCK_SIZE));
586 blob.seal(new, &keys)?;
587
588 self.replace_db_blob(&blob)?;
589 self.unlock(new)
592 }
593
594 pub fn settings(&self) -> Result<Settings> {
596 let blob = self.db_blob()?;
597 Ok(Settings {
598 idle_timeout: blob.idle_timeout,
599 lock_on_sleep: blob.lock_on_sleep,
600 })
601 }
602
603 pub fn set_settings(&mut self, settings: &Settings) -> Result<()> {
608 settings.validate()?;
609 let keys = self.keys().ok_or(Error::Locked)?;
610 let signing_key = SecretBytes::new(keys.signing_key.as_slice());
611
612 let mut blob = self.db_blob()?;
613 blob.idle_timeout = settings.idle_timeout;
614 blob.lock_on_sleep = settings.lock_on_sleep;
615 blob.sign(signing_key.as_slice());
616 self.replace_db_blob(&blob)
617 }
618
619 fn replace_db_blob(&mut self, blob: &DbBlob) -> Result<()> {
625 let bytes = blob.to_bytes();
626 let keychain = self.keychain_mut();
627 keychain.bump_commit_version();
628 let table = keychain
629 .table_mut(RecordType::METADATA)
630 .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_METADATA"))?;
631 let record = table
632 .records_mut()
633 .next()
634 .ok_or_else(|| Error::format("metadata table has no record"))?;
635 record.key_data = bytes;
636 record.unknown3 = record.unknown3.wrapping_add(1);
637 Ok(())
638 }
639
640 fn key_record_number(&self, label: &[u8; 20]) -> Option<u32> {
642 self.records_of_type(RecordType::SYMMETRIC_KEY)
643 .into_iter()
644 .find(|record| {
645 self.schema()
646 .attribute(RecordType::SYMMETRIC_KEY, record, "Label")
647 .and_then(Value::as_bytes)
648 .is_some_and(|stored| stored == label)
649 })
650 .map(|record| record.number)
651 }
652}
653
654fn coerce(name: &str, value: Value, format: AttributeFormat) -> Result<Value> {
662 let bytes = match &value {
663 Value::Blob(bytes) | Value::String(bytes) => bytes.clone(),
664 Value::Uint32(_) | Value::Sint32(_) => {
666 return match format {
667 AttributeFormat::Uint32 | AttributeFormat::Sint32 => Ok(value),
668 _ => Err(Error::other(format!("{name} is not a number attribute"))),
669 };
670 }
671 Value::Date(_) => {
672 return match format {
673 AttributeFormat::TimeDate => Ok(value),
674 _ => Err(Error::other(format!("{name} is not a date attribute"))),
675 };
676 }
677 };
678 let text = String::from_utf8_lossy(&bytes).into_owned();
679
680 match format {
681 AttributeFormat::Blob | AttributeFormat::String => Ok(Value::Blob(bytes)),
682 AttributeFormat::Uint32 | AttributeFormat::Sint32 => {
683 if FOUR_CHAR_CODE_ATTRIBUTES.contains(&name) && bytes.len() == 4 {
686 let code = u32::from_be_bytes(bytes[..4].try_into().expect("four bytes"));
687 return Ok(Value::Uint32(code));
688 }
689 let number: i64 = text.trim().parse().map_err(|_| {
690 Error::other(format!(
691 "{name} is a number attribute; {text:?} is not a number"
692 ))
693 })?;
694 match format {
695 AttributeFormat::Uint32 => u32::try_from(number)
696 .map(Value::Uint32)
697 .map_err(|_| Error::other(format!("{number} does not fit {name}"))),
698 _ => i32::try_from(number)
699 .map(Value::Sint32)
700 .map_err(|_| Error::other(format!("{number} does not fit {name}"))),
701 }
702 }
703 AttributeFormat::TimeDate => {
704 let trimmed = text.trim_end_matches('\0');
706 if trimmed.len() != 15 || !trimmed.ends_with('Z') {
707 return Err(Error::other(format!(
708 "{name} is a date; expected YYYYMMDDhhmmssZ, got {trimmed:?}"
709 )));
710 }
711 Ok(Value::Date(date_bytes(trimmed)))
712 }
713 other => Err(Error::other(format!(
714 "{name} has attribute format {other:?}, which this build cannot write"
715 ))),
716 }
717}
718
719fn date_bytes(timestamp: &str) -> Vec<u8> {
721 let mut bytes = timestamp.as_bytes().to_vec();
722 bytes.resize(16, 0);
723 bytes
724}
725
726#[derive(Debug, Clone)]
729pub struct StoredIdentity {
730 pub label: Option<String>,
732 pub public_key_hash: Vec<u8>,
734 pub certificate_record: u32,
735 pub certificate: Vec<u8>,
737 pub private_key_record: Option<u32>,
738}
739
740impl KeychainFile {
741 pub fn identities(&self) -> Vec<StoredIdentity> {
743 let mut key_by_label: Vec<(Vec<u8>, u32)> = Vec::new();
744 for record in self.records_of_type(RecordType::PRIVATE_KEY) {
745 if let Some(label) = self
746 .schema()
747 .attribute(RecordType::PRIVATE_KEY, record, "Label")
748 .and_then(Value::as_bytes)
749 {
750 key_by_label.push((label.to_vec(), record.number));
751 }
752 }
753
754 self.records_of_type(RecordType::X509_CERTIFICATE)
755 .into_iter()
756 .map(|record| {
757 let public_key_hash = self
758 .schema()
759 .attribute(RecordType::X509_CERTIFICATE, record, "PublicKeyHash")
760 .and_then(Value::as_bytes)
761 .unwrap_or_default()
762 .to_vec();
763 let label = self
764 .schema()
765 .attribute(RecordType::X509_CERTIFICATE, record, "PrintName")
766 .and_then(Value::as_bytes)
767 .map(|bytes| {
768 String::from_utf8_lossy(crate::format::trim_nul(bytes)).into_owned()
769 })
770 .filter(|name| !name.is_empty());
771 let private_key_record = key_by_label
772 .iter()
773 .find(|(key_label, _)| *key_label == public_key_hash)
774 .map(|(_, number)| *number);
775 StoredIdentity {
776 label,
777 public_key_hash,
778 certificate_record: record.number,
779 certificate: record.key_data.clone(),
780 private_key_record,
781 }
782 })
783 .collect()
784 }
785
786 pub fn private_key_pkcs8(&self, record_number: u32) -> Result<SecretBytes> {
791 let keys = self.keys().ok_or(Error::Locked)?;
792 let record = self
793 .records_of_type(RecordType::PRIVATE_KEY)
794 .into_iter()
795 .find(|record| record.number == record_number)
796 .ok_or(Error::NoSuchItem)?;
797 let blob = crypto::KeyBlob::parse(&record.key_data)?;
798 crypto::unwrap_blob(keys.encryption_key.as_slice(), &blob.iv, &blob.crypto_blob)
799 }
800}