Skip to main content

keychain/
edit.rs

1//! Changing a keychain that already exists: updating items, deleting them,
2//! rewriting an item's access control, and re-sealing the database itself.
3//!
4//! Everything here has the same constraint as [`crate::write`]: macOS has to
5//! keep working on the file afterwards. Three of these operations are not just
6//! "write different bytes" —
7//!
8//! * Deleting a record leaves a hole. macOS records that hole in the slot array
9//!   as a free-list link rather than shrinking the array, so record numbers stay
10//!   stable; see [`crate::format::Slot`].
11//! * Updating an item touches two records — the item and the key that protects
12//!   it — and both indexes have to follow.
13//! * Changing the password re-seals the database blob, but must **not** disturb
14//!   the master keys: every item key in the file is wrapped under them, so
15//!   generating new ones would orphan every secret in the keychain.
16
17use 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/// What to change about an item. Every field left `None` is left alone; this is
27/// a patch, not a replacement.
28///
29/// The distinction matters for attributes that are stored present-but-empty:
30/// `Some(String::new())` clears an attribute, `None` leaves it as it was.
31#[derive(Debug, Clone, Default)]
32pub struct ItemChanges {
33    /// `PrintName`
34    pub label: Option<String>,
35    /// `desc`, the "kind"
36    pub description: Option<String>,
37    /// `icmt`
38    pub comment: Option<String>,
39    /// `gena`, generic items
40    pub generic: Option<Vec<u8>>,
41    /// `sdmn`, internet items
42    pub security_domain: Option<String>,
43    /// Any other attribute, by the name its relation gives it.
44    ///
45    /// The identity attributes of a relation — the ones in its unique index —
46    /// are rejected rather than written: changing one turns the item into a
47    /// different item, which is a delete and an add, not an update.
48    pub attributes: Vec<(String, Value)>,
49}
50
51impl ItemChanges {
52    /// True when nothing would change.
53    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    /// The changes as (attribute name, value) pairs.
63    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/// The keychain's own settings, as `security set-keychain-settings` sets them.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct Settings {
85    /// Seconds of inactivity before the keychain locks.
86    ///
87    /// [`Settings::NO_TIMEOUT`] means never; there is no separate flag for it.
88    pub idle_timeout: u32,
89    pub lock_on_sleep: bool,
90}
91
92impl Settings {
93    /// What macOS stores for "no idle timeout": `INT_MAX`, not zero.
94    pub const NO_TIMEOUT: u32 = 0x7fff_ffff;
95
96    /// True when the keychain never locks on idle.
97    pub fn never_times_out(&self) -> bool {
98        self.idle_timeout == Self::NO_TIMEOUT
99    }
100
101    /// Reject what securityd rejects: zero, and anything past `INT_MAX`.
102    ///
103    /// macOS refuses these outright and writes nothing, so accepting them here
104    /// would produce a keychain its own tool would not have written.
105    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    /// Update an item in place: its secret, its attributes, or both.
121    ///
122    /// The item keeps its record number, its slot, and its item key; only the
123    /// encrypted payload is re-sealed, under a fresh IV. `mdat` is stamped with
124    /// `timestamp` and `cdat` is left as it was.
125    ///
126    /// Requires an unlocked keychain when `secret` is given.
127    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        // Refuse to rewrite an attribute the relation indexes as identity: the
148        // result would be a different item sharing a record with the old one,
149        // and a duplicate of it may already exist.
150        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        // Re-seal the secret under the item's existing key, with a fresh IV.
173        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    /// Delete an item and the key record that protects it.
226    ///
227    /// The slot keeps its place in the array — macOS never renumbers records —
228    /// and both tables' indexes are rebuilt so nothing points at the hole.
229    ///
230    /// Returns the number of records removed: the item, plus its key when one
231    /// was found.
232    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        // The item names its key by the `ssgp` label the two share.
239        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        // macOS advances the commit version once per record removed: deleting an
249        // item and its key moves it by two.
250        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    /// Delete a certificate, leaving any private key that goes with it.
282    ///
283    /// This is what `security delete-certificate` does: the key is left behind,
284    /// orphaned, and `security find-identity` stops reporting the identity.
285    /// Use [`KeychainFile::delete_identity`] to remove both halves.
286    pub fn delete_certificate(&mut self, public_key_hash: &[u8]) -> Result<usize> {
287        self.delete_identity_records(public_key_hash, false)
288    }
289
290    /// Delete an identity: the certificate and the private key that matches it.
291    ///
292    /// Returns the number of records removed.
293    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    /// Rewrite the access control of an item's key.
355    ///
356    /// An empty list means any application, which is what
357    /// `security add-generic-password -A` stores. The key itself is untouched:
358    /// only the ACL region of its blob is replaced, and the blob re-signed.
359    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    /// Rewrite an item's native application access.
374    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    /// Rewrite the access control of a stored private key.
396    ///
397    /// This is the identity equivalent of [`KeychainFile::set_item_trust`].
398    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    /// Rewrite a stored private key's native application access.
412    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    /// Native application access for a password item.
432    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    /// Native application access for a stored private key.
452    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    /// Native ACL applications for a password item.
460    ///
461    /// `None` means the ACL was not in the canonical form this library models;
462    /// an empty vector may mean allow-any or prompt-all. Use
463    /// [`KeychainFile::item_application_access`] to distinguish them.
464    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    /// Native ACL applications for a stored private key.
484    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        // The ACL is replaced with this crate's canonical form, so an ACL it
532        // could not parse must not be touched: rewriting one would silently
533        // drop whatever macOS put there.
534        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        // Keep the name the ACL already carries: it is the item's name as of
548        // when the key was created, and macOS does not rewrite it either.
549        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    /// Change the password that protects the keychain.
575    ///
576    /// The database's own keys are preserved — every item key in the file is
577    /// wrapped under them — so only the blob is re-sealed: a fresh salt and IV,
578    /// the keys re-encrypted under the new password, and a new signature.
579    /// Nothing outside the metadata record changes.
580    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        // The old derivation is stale; adopt the new one so the handle stays
590        // usable and item keys stay available.
591        self.unlock(new)
592    }
593
594    /// The keychain's settings, as stored in the database blob.
595    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    /// Change the keychain's settings.
604    ///
605    /// The settings live in the signed part of the database blob, so this needs
606    /// the signing key: an unlocked keychain, or the password.
607    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    /// Write a database blob back into the metadata record.
620    ///
621    /// The metadata record carries a counter of its own in the fourth header
622    /// word, which macOS advances by one on every re-seal, along with the
623    /// container's commit version.
624    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    /// The record number of the key whose `Label` is `label`.
641    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
654/// Fit a value to the format its attribute is declared with.
655///
656/// Text arrives from a caller that has no schema in hand — a command line, say —
657/// so `"7"` for an integer attribute arrives as bytes. Storing those bytes would
658/// not fail loudly: an integer is four raw bytes and a blob is a length followed
659/// by data, so `"7"` would be read back as *1*, its own length. Anything that
660/// cannot be fitted is an error rather than a guess.
661fn coerce(name: &str, value: Value, format: AttributeFormat) -> Result<Value> {
662    let bytes = match &value {
663        Value::Blob(bytes) | Value::String(bytes) => bytes.clone(),
664        // Already typed by the caller: only the format has to agree.
665        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            // Some integer attributes hold a four-character code; `ptcl` reads
684            // as `htps`, and that is how it is written here too.
685            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            // The stored form is fixed: `YYYYMMDDhhmmssZ` and a NUL.
705            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
719/// A timestamp as the fixed sixteen bytes a date attribute holds.
720fn 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/// A certificate stored in the keychain, and the private key that goes with it
727/// when the keychain has one.
728#[derive(Debug, Clone)]
729pub struct StoredIdentity {
730    /// `PrintName` of the certificate record.
731    pub label: Option<String>,
732    /// SHA-1 of the certificate's public key: what links the two records.
733    pub public_key_hash: Vec<u8>,
734    pub certificate_record: u32,
735    /// The certificate, DER-encoded, exactly as stored.
736    pub certificate: Vec<u8>,
737    pub private_key_record: Option<u32>,
738}
739
740impl KeychainFile {
741    /// Certificates in the keychain, paired with their private keys.
742    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    /// A stored private key, unwrapped, as a PKCS#8 `PrivateKeyInfo`.
787    ///
788    /// Requires an unlocked keychain. The bytes are the ones that went in: this
789    /// is the reverse of [`KeychainFile::add_identity`].
790    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}