Skip to main content

keychain/
write.rs

1//! Creating keychains and adding items.
2//!
3//! Three operations, all of which have to agree with macOS byte for byte to be
4//! useful:
5//!
6//! * [`create`] writes a new database: the four schema tables replayed from
7//!   [`apple_schema`], an empty table per record relation, and a metadata record
8//!   holding a fresh `DbBlob` sealed with the caller's password.
9//! * [`KeychainFile::add_password`] stores an item: a wrapped item key in the
10//!   symmetric-key table and the encrypted secret in the item record.
11//! * [`KeychainFile::add_identity`] stores a certificate and its private key,
12//!   adding the certificate relation to the schema first if the keychain has
13//!   never held one.
14//!
15//! Every write rebuilds the indexes of the tables it touched, because their
16//! offsets are table-relative: a stale index region sends macOS into the middle
17//! of a record and it reports `errSecNoSuchAttr`.
18
19use crate::acl::{AclBlob, ApplicationAccess, TrustedApplication};
20use crate::apple_schema::{self, RECORD_VERSION};
21use crate::crypto::{
22    self, BLOB_VERSION, BLOCK_SIZE, DbBlob, DbKeys, KEY_LEN, SALT_LEN, SecretBytes, Ssgp,
23};
24use crate::cssm::{KeyHeader, WrappedKeyFields};
25use crate::db::KeychainFile;
26use crate::der;
27use crate::error::{Error, Result};
28use crate::format::{
29    HEADER_SIZE_FIELD, Keychain, Record, Slot, Table, TableIndexes, VERSION, Value,
30};
31use crate::index::{Index, IndexBlob};
32use crate::records::{CertificateRecord, ItemKeyRecord, PasswordRecord, PrivateKeyRecord};
33use crate::schema::{AttributeFormat, RecordType, Relation, Schema};
34
35/// Value macOS writes in a symmetric-key record's fourth header word. Its
36/// meaning is unknown; most record types get `0`.
37const KEY_RECORD_UNKNOWN3: u32 = 4;
38
39/// The same word in a private-key record, where macOS writes `5`.
40const PRIVATE_KEY_RECORD_UNKNOWN3: u32 = 5;
41
42/// An identity to store: a certificate and the private key that matches it.
43#[derive(Debug, Clone)]
44pub struct NewIdentity {
45    /// The certificate, DER-encoded.
46    pub certificate: Vec<u8>,
47    /// The private key as a PKCS#8 `PrivateKeyInfo`, DER-encoded.
48    pub private_key: Vec<u8>,
49    /// Label for both records. Defaults to the certificate's common name.
50    pub label: Option<String>,
51    /// Applications allowed to use the private key. Empty means any.
52    pub trusted_applications: Vec<TrustedApplication>,
53}
54
55/// Settings for a new keychain. The defaults are what macOS writes.
56#[derive(Debug, Clone)]
57pub struct CreateOptions {
58    /// Seconds of inactivity before locking. macOS writes 300.
59    pub idle_timeout: u32,
60    pub lock_on_sleep: bool,
61}
62
63impl Default for CreateOptions {
64    fn default() -> Self {
65        Self {
66            idle_timeout: 300,
67            lock_on_sleep: true,
68        }
69    }
70}
71
72/// Build a new keychain protected by `password`.
73pub fn create(password: &[u8], options: &CreateOptions) -> Result<KeychainFile> {
74    let mut tables = Vec::with_capacity(apple_schema::TABLES.len());
75
76    for template in &apple_schema::TABLES {
77        let record_type = RecordType(template.relation_id);
78        // Index declarations come from the template; entries are built as
79        // records are added. An empty table's declarations sit right after its
80        // slot array, which is where the template's offsets were measured from.
81        let template_offset = crate::format::TABLE_HEADER_LEN + 4;
82        let indexes = IndexBlob::parse(template.index_data, template_offset, None)
83            .map(TableIndexes::Parsed)
84            .unwrap_or_else(|_| TableIndexes::Raw(template.index_data.to_vec()));
85        let mut table = Table {
86            record_type,
87            free_list_head: template.free_list,
88            slots: Vec::new(),
89            layout: Vec::new(),
90            indexes,
91        };
92
93        match record_type {
94            RecordType::SCHEMA_INFO => {
95                for (number, row) in apple_schema::RELATIONS.iter().enumerate() {
96                    table.slots.push(Slot::Record(schema_record(
97                        number as u32,
98                        vec![
99                            Some(Value::Uint32(row.relation_id)),
100                            row.name.map(|name| Value::String(name.to_vec())),
101                        ],
102                    )));
103                }
104            }
105            RecordType::SCHEMA_INDEXES => {
106                for (number, row) in apple_schema::INDEXES.iter().enumerate() {
107                    table.slots.push(Slot::Record(schema_record(
108                        number as u32,
109                        vec![
110                            Some(Value::Uint32(row.relation_id)),
111                            Some(Value::Uint32(row.index_id)),
112                            Some(Value::Uint32(row.attribute_id)),
113                            Some(Value::Uint32(row.index_type)),
114                            Some(Value::Uint32(row.indexed_data_location)),
115                        ],
116                    )));
117                }
118            }
119            RecordType::SCHEMA_ATTRIBUTES => {
120                for (number, row) in apple_schema::ATTRIBUTES.iter().enumerate() {
121                    table.slots.push(Slot::Record(schema_record(
122                        number as u32,
123                        vec![
124                            Some(Value::Uint32(row.relation_id)),
125                            Some(Value::Uint32(row.attribute_id)),
126                            Some(Value::Uint32(row.name_format)),
127                            row.name.map(|name| Value::String(name.to_vec())),
128                            row.name_id.map(|id| Value::Blob(id.to_vec())),
129                            Some(Value::Uint32(row.format)),
130                        ],
131                    )));
132                }
133            }
134            RecordType::METADATA => {
135                // Filled in below, once the blob is sealed.
136            }
137            _ => {
138                // An empty table still carries one unused slot, the way macOS
139                // writes it.
140                table.slots.push(Slot::Empty);
141            }
142        }
143
144        tables.push(table);
145    }
146
147    // The database blob: fresh salt, IV, and keys, sealed with the password.
148    let mut salt = [0u8; SALT_LEN];
149    salt.copy_from_slice(&crate::secret::random_bytes(SALT_LEN));
150    let mut iv = [0u8; BLOCK_SIZE];
151    iv.copy_from_slice(&crate::secret::random_bytes(BLOCK_SIZE));
152    let mut random_signature = [0u8; 16];
153    random_signature.copy_from_slice(&crate::secret::random_bytes(16));
154
155    let keys = DbKeys {
156        encryption_key: SecretBytes::new(crate::secret::random_bytes(KEY_LEN)),
157        signing_key: SecretBytes::new(crate::secret::random_bytes(20)),
158        private_acl: Vec::new(),
159    };
160
161    let mut blob = DbBlob {
162        version: BLOB_VERSION,
163        start_crypto_blob: 0,
164        total_length: 0,
165        random_signature,
166        sequence: 0,
167        idle_timeout: options.idle_timeout,
168        lock_on_sleep: options.lock_on_sleep,
169        // A keychain this code creates has no uninitialized memory to leak.
170        parameters_padding: [0; 3],
171        salt,
172        iv,
173        blob_signature: [0u8; 20],
174        public_acl: crate::acl::database_public_acl(),
175        crypto_blob: Vec::new(),
176    };
177    blob.seal(password, &keys)?;
178
179    let metadata = tables
180        .iter_mut()
181        .find(|table| table.record_type == RecordType::METADATA)
182        .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_METADATA"))?;
183    metadata.slots.push(Slot::Record(Record {
184        number: 0,
185        version: RECORD_VERSION,
186        unknown3: 0,
187        unknown5: 0,
188        key_data: blob.to_bytes(),
189        attributes: Vec::new(),
190    }));
191
192    let keychain = Keychain {
193        version: VERSION,
194        header_size: HEADER_SIZE_FIELD,
195        auth_offset: 0,
196        tables,
197        commit_version: Some(1),
198    };
199
200    let mut file = KeychainFile::from_bytes(&keychain.to_bytes()?)?;
201    file.unlock(password)?;
202    Ok(file)
203}
204
205/// Store an empty value for every attribute of the unique index that has none.
206///
207/// An attribute a record does not have is not indexed, and an item missing from
208/// its relation's unique index cannot be found through the Security framework.
209/// macOS avoids that by storing the identity attributes it was given no value
210/// for as zero or empty: an internet item with no port has `port` = 0 and `path`
211/// = "", not no `port` at all.
212fn fill_unique_key(relation: &Relation, unique: &[u32], attributes: &mut [Option<Value>]) {
213    for id in unique {
214        let Some(position) = relation
215            .attributes
216            .iter()
217            .position(|attribute| attribute.id == *id)
218        else {
219            continue;
220        };
221        let Some(slot) = attributes.get_mut(position) else {
222            continue;
223        };
224        if slot.is_some() {
225            continue;
226        }
227        *slot = match relation.attributes[position].format {
228            AttributeFormat::Sint32 => Some(Value::Sint32(0)),
229            AttributeFormat::Uint32 => Some(Value::Uint32(0)),
230            AttributeFormat::Blob => Some(Value::Blob(Vec::new())),
231            AttributeFormat::String => Some(Value::String(Vec::new())),
232            // A date is a fixed sixteen bytes, so it has no empty form; no date
233            // attribute takes part in a unique index. The rest are formats no
234            // password relation uses, and a guessed value would be worse than
235            // none.
236            _ => None,
237        };
238    }
239}
240
241/// The index declarations of a relation, as an index region with no entries.
242///
243/// One index per `IndexID`, over the attributes its rows name, in row order. The
244/// `IndexType` in the schema is the inverse of the `kind` word in the region: a
245/// schema type of `0` marks the relation's unique index, which the region writes
246/// as `1`.
247fn index_declarations(rows: &[apple_schema::IndexRow]) -> IndexBlob {
248    let mut indexes: Vec<Index> = Vec::new();
249    for row in rows {
250        match indexes.iter_mut().find(|index| index.id == row.index_id) {
251            Some(index) => index.attribute_ids.push(row.attribute_id),
252            None => indexes.push(Index {
253                id: row.index_id,
254                kind: u32::from(row.index_type == 0),
255                attribute_ids: vec![row.attribute_id],
256                entries: Vec::new(),
257            }),
258        }
259    }
260    IndexBlob { indexes }
261}
262
263fn schema_record(number: u32, attributes: Vec<Option<Value>>) -> Record {
264    Record {
265        number,
266        version: RECORD_VERSION,
267        unknown3: 0,
268        unknown5: 0,
269        key_data: Vec::new(),
270        attributes,
271    }
272}
273
274/// What to store for a new password item.
275#[derive(Debug, Clone, Default)]
276pub struct NewItem {
277    /// `PrintName`: the name Keychain Access shows. Defaults to the service or
278    /// server when not set.
279    pub label: Option<String>,
280    /// `acct`
281    pub account: Option<String>,
282    /// `svce`, generic items only.
283    pub service: Option<String>,
284    /// `gena`, generic items only: application-defined bytes.
285    pub generic: Option<Vec<u8>>,
286    /// `srvr`, internet and AppleShare items.
287    pub server: Option<String>,
288    /// `sdmn`, internet items only: the authentication realm.
289    pub security_domain: Option<String>,
290    /// `path`, internet items only.
291    pub path: Option<String>,
292    /// `port`, internet items only.
293    pub port: Option<u32>,
294    /// `ptcl`, internet and AppleShare items: a four-char code such as `http`.
295    pub protocol: Option<[u8; 4]>,
296    /// `atyp`, internet items only: a four-char code such as `dflt`.
297    pub auth_type: Option<[u8; 4]>,
298    /// `vlme`, AppleShare items only.
299    pub volume: Option<String>,
300    /// `addr`, AppleShare items only.
301    pub address: Option<String>,
302    /// `ssig`, AppleShare items only.
303    pub signature: Option<String>,
304    /// `desc`: the "kind" shown in Keychain Access.
305    pub description: Option<String>,
306    /// `icmt`: free-text comment.
307    pub comment: Option<String>,
308    /// Applications allowed to decrypt the item. Empty means any application,
309    /// which is what `security add-generic-password -A` stores.
310    pub trusted_applications: Vec<TrustedApplication>,
311}
312
313impl NewItem {
314    /// Lower into the stored attribute set.
315    fn to_record(&self, print_name: &str, timestamp: &str) -> PasswordRecord {
316        PasswordRecord {
317            created: timestamp.to_string(),
318            modified: timestamp.to_string(),
319            print_name: print_name.to_string(),
320            description: self.description.clone(),
321            comment: self.comment.clone(),
322            account: self.account.clone(),
323            service: self.service.clone(),
324            generic: self.generic.clone(),
325            server: self.server.clone(),
326            security_domain: self.security_domain.clone(),
327            path: self.path.clone(),
328            port: self.port,
329            protocol: self.protocol,
330            auth_type: self.auth_type,
331            volume: self.volume.clone(),
332            address: self.address.clone(),
333            signature: self.signature.clone(),
334        }
335    }
336
337    /// The name to store as `PrintName`.
338    fn print_name(&self) -> String {
339        self.label
340            .clone()
341            .or_else(|| self.service.clone())
342            .or_else(|| self.server.clone())
343            .or_else(|| self.volume.clone())
344            .or_else(|| self.account.clone())
345            .unwrap_or_default()
346    }
347}
348
349impl KeychainFile {
350    /// Store a password item, creating the item key that protects it.
351    ///
352    /// Requires an unlocked keychain: the item key is wrapped with the
353    /// database's encryption key and both blobs are signed with its signing key.
354    pub fn add_password(
355        &mut self,
356        record_type: RecordType,
357        item: &NewItem,
358        secret: &[u8],
359        timestamp: &str,
360    ) -> Result<()> {
361        let access = if item.trusted_applications.is_empty() {
362            ApplicationAccess::AllowAny
363        } else {
364            ApplicationAccess::TrustedApplications(item.trusted_applications.clone())
365        };
366        self.add_password_with_access(record_type, item, secret, timestamp, &access)
367    }
368
369    /// Store a password item with an explicit native application-access policy.
370    ///
371    /// Unlike [`KeychainFile::add_password`], this distinguishes an allow-any
372    /// ACL from an empty trusted-application list that prompts every caller.
373    pub fn add_password_with_access(
374        &mut self,
375        record_type: RecordType,
376        item: &NewItem,
377        secret: &[u8],
378        timestamp: &str,
379        access: &ApplicationAccess,
380    ) -> Result<()> {
381        let keys = self.keys().ok_or(Error::Locked)?;
382        let encryption_key = SecretBytes::new(keys.encryption_key.as_slice());
383        let signing_key = SecretBytes::new(keys.signing_key.as_slice());
384
385        // One fresh key per item, wrapped under the database key, exactly as
386        // macOS does. The label ties the item to its key.
387        let item_key = SecretBytes::new(crate::secret::random_bytes(KEY_LEN));
388        let mut label = [0u8; 20];
389        label[..4].copy_from_slice(crypto::SSGP_MAGIC);
390        label[4..].copy_from_slice(&crate::secret::random_bytes(16));
391
392        let print_name = item.print_name();
393        let key_attributes = {
394            let relation = self
395                .schema()
396                .relation(RecordType::SYMMETRIC_KEY)
397                .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_SYMMETRIC_KEY"))?;
398            ItemKeyRecord::for_item_key(label).to_attributes(relation)
399        };
400        let key_blob = self.wrap_item_key(
401            &item_key,
402            encryption_key.as_slice(),
403            signing_key.as_slice(),
404            &print_name,
405            access,
406        )?;
407
408        let mut ssgp_iv = [0u8; BLOCK_SIZE];
409        ssgp_iv.copy_from_slice(&crate::secret::random_bytes(BLOCK_SIZE));
410        let ssgp = Ssgp::seal(label, ssgp_iv, item_key.as_slice(), secret)?;
411
412        let item_attributes = {
413            let relation = self.schema().relation(record_type).ok_or_else(|| {
414                Error::format(format!("keychain has no 0x{:08x} relation", record_type.0))
415            })?;
416            let mut attributes = item
417                .to_record(&print_name, timestamp)
418                .to_attributes(relation);
419            if let Some(table) = self.keychain().table(record_type)
420                && let Some(unique) = table.unique_index_attribute_ids()
421            {
422                fill_unique_key(relation, unique, &mut attributes);
423            }
424            attributes
425        };
426
427        // macOS refuses a second item with the same unique key, and two records
428        // sharing one index key would give the index two entries that cannot be
429        // told apart. Refusing here keeps the file valid.
430        if let Some(relation) = self.schema().relation(record_type)
431            && let Some(table) = self.keychain().table(record_type)
432            && table.has_record_with_unique_key(relation, &item_attributes)
433        {
434            return Err(Error::DuplicateItem);
435        }
436
437        // Both records are stamped with the commit version of this write, the
438        // way macOS stamps them, and both go in together: an item without its
439        // key is unreadable, and a key without its item is garbage.
440        let keychain = self.keychain_mut();
441        keychain.bump_commit_version();
442        let version = keychain.commit_version.unwrap_or(1);
443
444        let key_table = keychain
445            .table_mut(RecordType::SYMMETRIC_KEY)
446            .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_SYMMETRIC_KEY"))?;
447        key_table.insert(Record {
448            // `insert` assigns the record number: it is the slot it lands in.
449            number: 0,
450            version,
451            unknown3: KEY_RECORD_UNKNOWN3,
452            unknown5: 0,
453            key_data: key_blob,
454            attributes: key_attributes,
455        });
456
457        let table = keychain
458            .table_mut(record_type)
459            .ok_or(Error::MissingTable("password table"))?;
460        table.insert(Record {
461            // `insert` assigns the record number: it is the slot it lands in.
462            number: 0,
463            version,
464            unknown3: 0,
465            unknown5: 0,
466            key_data: ssgp.to_bytes(),
467            attributes: item_attributes,
468        });
469
470        // Both tables' indexes must be rebuilt: the records moved, so every
471        // table-relative offset in the region changed, and the new records need
472        // entries or the Security framework will not find them.
473        let schema = self.schema().clone();
474        for touched in [RecordType::SYMMETRIC_KEY, record_type] {
475            let Some(relation) = schema.relation(touched) else {
476                continue;
477            };
478            if let Some(table) = self.keychain_mut().table_mut(touched) {
479                table.rebuild_indexes(relation)?;
480            }
481        }
482
483        self.remember_item_key(label, item_key);
484        Ok(())
485    }
486
487    /// Store an identity: the certificate in the clear, the private key wrapped.
488    ///
489    /// The two records are linked by the certificate's public key hash, which the
490    /// key record carries as its `Label` — that is how `SecIdentity` pairs them,
491    /// and how [`crate::db::KeychainFile`] and `security` both find
492    /// them.
493    ///
494    /// Requires an unlocked keychain: the private key is wrapped with the
495    /// database's encryption key, and both blobs are signed with its signing key.
496    pub fn add_identity(&mut self, identity: &NewIdentity) -> Result<[u8; 20]> {
497        let access = if identity.trusted_applications.is_empty() {
498            ApplicationAccess::AllowAny
499        } else {
500            ApplicationAccess::TrustedApplications(identity.trusted_applications.clone())
501        };
502        self.add_identity_with_access(identity, &access)
503    }
504
505    /// Store an identity with an explicit native application-access policy.
506    ///
507    /// This preserves the distinction between allow-any and prompt-every-caller
508    /// ACLs while keeping [`KeychainFile::add_identity`] backward compatible.
509    pub fn add_identity_with_access(
510        &mut self,
511        identity: &NewIdentity,
512        access: &ApplicationAccess,
513    ) -> Result<[u8; 20]> {
514        self.ensure_relation(RecordType::X509_CERTIFICATE)?;
515
516        let keys = self.keys().ok_or(Error::Locked)?;
517        let encryption_key = SecretBytes::new(keys.encryption_key.as_slice());
518        let signing_key = SecretBytes::new(keys.signing_key.as_slice());
519
520        let certificate = der::Certificate::parse(&identity.certificate)?;
521        let public_key_hash = certificate.public_key_hash();
522        let label = identity
523            .label
524            .clone()
525            .or_else(|| certificate.common_name.clone())
526            .unwrap_or_else(|| hex::encode(public_key_hash));
527
528        // The key must actually match the certificate, or the identity is a pair
529        // of records that can never be used together.
530        let key_info = der::PrivateKeyInfo::parse(&identity.private_key)?;
531        if !key_info.is_rsa() {
532            return Err(Error::other(
533                "only RSA private keys are supported; an EC key would need its own \
534                 KeyType and key-size handling, which is not implemented",
535            ));
536        }
537        let key_size = key_info.rsa_key_size_in_bits()?;
538
539        let certificate_attributes = {
540            let relation = self
541                .schema()
542                .relation(RecordType::X509_CERTIFICATE)
543                .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_X509_CERTIFICATE"))?;
544            CertificateRecord::for_certificate(&label, &certificate).to_attributes(relation)
545        };
546        let key_attributes = {
547            let relation = self
548                .schema()
549                .relation(RecordType::PRIVATE_KEY)
550                .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_PRIVATE_KEY"))?;
551            PrivateKeyRecord::for_private_key(&label, public_key_hash, key_size)
552                .to_attributes(relation)
553        };
554
555        let key_blob = self.wrap_private_key(
556            &identity.private_key,
557            encryption_key.as_slice(),
558            signing_key.as_slice(),
559            &label,
560            key_size,
561            access,
562        )?;
563
564        let keychain = self.keychain_mut();
565        keychain.bump_commit_version();
566        let version = keychain.commit_version.unwrap_or(1);
567
568        let key_table = keychain
569            .table_mut(RecordType::PRIVATE_KEY)
570            .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_PRIVATE_KEY"))?;
571        key_table.insert(Record {
572            // `insert` assigns the record number: it is the slot it lands in.
573            number: 0,
574            version,
575            unknown3: PRIVATE_KEY_RECORD_UNKNOWN3,
576            unknown5: 0,
577            key_data: key_blob,
578            attributes: key_attributes,
579        });
580
581        let certificate_table = keychain
582            .table_mut(RecordType::X509_CERTIFICATE)
583            .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_X509_CERTIFICATE"))?;
584        certificate_table.insert(Record {
585            // `insert` assigns the record number: it is the slot it lands in.
586            number: 0,
587            version,
588            unknown3: 0,
589            unknown5: 0,
590            // A certificate is public: it is stored unencrypted.
591            key_data: identity.certificate.clone(),
592            attributes: certificate_attributes,
593        });
594
595        let schema = self.schema().clone();
596        for touched in [RecordType::PRIVATE_KEY, RecordType::X509_CERTIFICATE] {
597            let Some(relation) = schema.relation(touched) else {
598                continue;
599            };
600            if let Some(table) = self.keychain_mut().table_mut(touched) {
601                table.rebuild_indexes(relation)?;
602            }
603        }
604        Ok(public_key_hash)
605    }
606
607    /// Add a relation to the schema, if the keychain does not have it yet.
608    ///
609    /// A keychain from `security create-keychain` has no certificate table:
610    /// `securityd` appends the relation's schema rows and an empty table the
611    /// first time something stores a certificate. Writing a certificate record
612    /// into a keychain that has no such relation would produce a file macOS
613    /// cannot read, so the relation is created the same way here.
614    fn ensure_relation(&mut self, record_type: RecordType) -> Result<()> {
615        if self.keychain().table(record_type).is_some() {
616            return Ok(());
617        }
618        let definition = apple_schema::ON_DEMAND_RELATIONS
619            .iter()
620            .find(|relation| relation.relation.relation_id == record_type.0)
621            .ok_or_else(|| {
622                Error::other(format!(
623                    "this keychain has no {} table, and adding that relation is not supported",
624                    record_type.name()
625                ))
626            })?;
627
628        let keychain = self.keychain_mut();
629
630        let info = keychain
631            .table_mut(RecordType::SCHEMA_INFO)
632            .ok_or(Error::MissingTable("CSSM_DL_DB_SCHEMA_INFO"))?;
633        info.insert(schema_record(
634            0,
635            vec![
636                Some(Value::Uint32(definition.relation.relation_id)),
637                definition
638                    .relation
639                    .name
640                    .map(|name| Value::String(name.to_vec())),
641            ],
642        ));
643
644        let attributes = keychain
645            .table_mut(RecordType::SCHEMA_ATTRIBUTES)
646            .ok_or(Error::MissingTable("CSSM_DL_DB_SCHEMA_ATTRIBUTES"))?;
647        for row in definition.attributes {
648            attributes.insert(schema_record(
649                0,
650                vec![
651                    Some(Value::Uint32(row.relation_id)),
652                    Some(Value::Uint32(row.attribute_id)),
653                    Some(Value::Uint32(row.name_format)),
654                    row.name.map(|name| Value::String(name.to_vec())),
655                    row.name_id.map(|id| Value::Blob(id.to_vec())),
656                    Some(Value::Uint32(row.format)),
657                ],
658            ));
659        }
660
661        let indexes = keychain
662            .table_mut(RecordType::SCHEMA_INDEXES)
663            .ok_or(Error::MissingTable("CSSM_DL_DB_SCHEMA_INDEXES"))?;
664        for row in definition.indexes {
665            indexes.insert(schema_record(
666                0,
667                vec![
668                    Some(Value::Uint32(row.relation_id)),
669                    Some(Value::Uint32(row.index_id)),
670                    Some(Value::Uint32(row.attribute_id)),
671                    Some(Value::Uint32(row.index_type)),
672                    Some(Value::Uint32(row.indexed_data_location)),
673                ],
674            ));
675        }
676
677        let table = Table {
678            record_type,
679            free_list_head: definition.free_list,
680            // An empty table still carries one unused slot, and the free list
681            // points at it.
682            slots: vec![Slot::Empty],
683            layout: Vec::new(),
684            indexes: TableIndexes::Parsed(index_declarations(definition.indexes)),
685        };
686        // The tables array is ordered by record type.
687        let at = keychain
688            .tables
689            .iter()
690            .position(|existing| existing.record_type.0 > record_type.0)
691            .unwrap_or(keychain.tables.len());
692        keychain.tables.insert(at, table);
693
694        self.reload_schema()
695    }
696
697    /// The key blob for a private key: the same wrapping an item key uses, over a
698    /// PKCS#8 payload instead of 24 bytes.
699    fn wrap_private_key(
700        &self,
701        private_key: &[u8],
702        encryption_key: &[u8],
703        signing_key: &[u8],
704        label: &str,
705        key_size: u32,
706        access: &ApplicationAccess,
707    ) -> Result<Vec<u8>> {
708        let mut iv = [0u8; BLOCK_SIZE];
709        iv.copy_from_slice(&crate::secret::random_bytes(BLOCK_SIZE));
710
711        let mut blob = crypto::KeyBlob {
712            version: BLOB_VERSION,
713            start_crypto_blob: 0,
714            total_length: 0,
715            iv,
716            header: KeyHeader::private_key(key_size),
717            wrapped: WrappedKeyFields::item_key(),
718            blob_signature: [0u8; 20],
719            public_acl: crypto::PublicAcl::Parsed(AclBlob::for_item_access(label, access)),
720            crypto_blob: crypto::wrap_blob(encryption_key, &iv, private_key)?,
721        };
722        blob.sign(signing_key);
723        Ok(blob.to_bytes())
724    }
725
726    /// The key blob for an item key: wrapped under the database key, carrying
727    /// the item's ACL, and signed.
728    #[allow(clippy::too_many_arguments)]
729    fn wrap_item_key(
730        &self,
731        item_key: &SecretBytes,
732        encryption_key: &[u8],
733        signing_key: &[u8],
734        print_name: &str,
735        access: &ApplicationAccess,
736    ) -> Result<Vec<u8>> {
737        let mut iv = [0u8; BLOCK_SIZE];
738        iv.copy_from_slice(&crate::secret::random_bytes(BLOCK_SIZE));
739
740        let mut blob = crypto::KeyBlob {
741            version: BLOB_VERSION,
742            start_crypto_blob: 0,
743            total_length: 0,
744            iv,
745            header: KeyHeader::item_key(),
746            wrapped: WrappedKeyFields::item_key(),
747            blob_signature: [0u8; 20],
748            public_acl: crypto::PublicAcl::Parsed(AclBlob::for_item_access(print_name, access)),
749            crypto_blob: crypto::wrap_key(encryption_key, &iv, item_key.as_slice())?,
750        };
751        blob.sign(signing_key);
752        Ok(blob.to_bytes())
753    }
754}
755
756/// Format a timestamp the way keychain date attributes are written.
757pub fn format_timestamp(unix_seconds: i64) -> String {
758    let (days, seconds) = (
759        unix_seconds.div_euclid(86_400),
760        unix_seconds.rem_euclid(86_400),
761    );
762    let (year, month, day) = civil_from_days(days);
763    let (hour, minute, second) = (seconds / 3600, (seconds % 3600) / 60, seconds % 60);
764    format!("{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}Z")
765}
766
767/// Days since the epoch to a civil date (Howard Hinnant's `civil_from_days`).
768fn civil_from_days(days: i64) -> (i64, u32, u32) {
769    let z = days + 719_468;
770    let era = z.div_euclid(146_097);
771    let day_of_era = z.rem_euclid(146_097);
772    let year_of_era =
773        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
774    let year = year_of_era + era * 400;
775    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
776    let month_prime = (5 * day_of_year + 2) / 153;
777    let day = (day_of_year - (153 * month_prime + 2) / 5 + 1) as u32;
778    let month = if month_prime < 10 {
779        month_prime + 3
780    } else {
781        month_prime - 9
782    } as u32;
783    (if month <= 2 { year + 1 } else { year }, month, day)
784}
785
786/// Timestamp for right now.
787pub fn now_timestamp() -> String {
788    let seconds = std::time::SystemTime::now()
789        .duration_since(std::time::UNIX_EPOCH)
790        .map(|d| d.as_secs() as i64)
791        .unwrap_or(0);
792    format_timestamp(seconds)
793}
794
795/// Verify a schema built by [`create`] against the file's own declarations.
796pub fn schema_of_created(file: &KeychainFile) -> Result<Schema> {
797    let schema = file.keychain().schema()?;
798    // A created keychain must be able to describe its own password relations, or
799    // nothing can be stored in it.
800    for record_type in [
801        RecordType::GENERIC_PASSWORD,
802        RecordType::INTERNET_PASSWORD,
803        RecordType::APPLESHARE_PASSWORD,
804    ] {
805        let relation = schema
806            .relation(record_type)
807            .ok_or_else(|| Error::format("created keychain is missing a password relation"))?;
808        if relation.index_of("acct").is_none() {
809            return Err(Error::format(
810                "created keychain's password relation has no acct",
811            ));
812        }
813    }
814    Ok(schema)
815}
816
817/// Formats used by the password relations, for tests and diagnostics.
818pub fn expected_format(name: &str) -> AttributeFormat {
819    match name {
820        "cdat" | "mdat" => AttributeFormat::TimeDate,
821        "port" | "crtr" | "type" | "invi" | "nega" | "cusi" | "ptcl" => AttributeFormat::Uint32,
822        "scrp" => AttributeFormat::Sint32,
823        _ => AttributeFormat::Blob,
824    }
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    #[test]
832    fn timestamps_match_the_keychain_format() {
833        assert_eq!(format_timestamp(0), "19700101000000Z");
834        assert_eq!(format_timestamp(1_784_982_896), "20260725123456Z");
835        assert_eq!(format_timestamp(1_709_164_800), "20240229000000Z");
836        assert_eq!(format_timestamp(951_782_400), "20000229000000Z");
837        assert_eq!(now_timestamp().len(), 15);
838        assert!(now_timestamp().ends_with('Z'));
839    }
840
841    #[test]
842    fn a_created_keychain_unlocks_and_describes_itself() {
843        let file = create(b"correct horse", &CreateOptions::default()).unwrap();
844        assert!(file.is_unlocked());
845        schema_of_created(&file).unwrap();
846
847        let info = file.info().unwrap();
848        assert_eq!(info.version, VERSION);
849        assert_eq!(info.tables.len(), apple_schema::TABLES.len());
850        assert_eq!(info.idle_timeout, 300);
851        assert!(info.lock_on_sleep);
852        assert!(file.items().is_empty());
853    }
854
855    #[test]
856    fn a_created_keychain_rejects_the_wrong_password() {
857        let file = create(b"right", &CreateOptions::default()).unwrap();
858        let bytes = file.keychain().to_bytes().unwrap();
859
860        let mut reopened = KeychainFile::from_bytes(&bytes).unwrap();
861        assert!(matches!(
862            reopened.unlock(b"wrong"),
863            Err(Error::WrongPassword)
864        ));
865        assert!(!reopened.is_unlocked());
866        reopened.unlock(b"right").unwrap();
867    }
868
869    #[test]
870    fn created_keychains_differ_in_salt_and_keys() {
871        let first = create(b"same password", &CreateOptions::default()).unwrap();
872        let second = create(b"same password", &CreateOptions::default()).unwrap();
873        assert_ne!(first.info().unwrap().salt, second.info().unwrap().salt);
874        assert_ne!(first.info().unwrap().iv, second.info().unwrap().iv);
875    }
876
877    #[test]
878    fn adding_an_item_stores_a_recoverable_secret() {
879        let mut file = create(b"master", &CreateOptions::default()).unwrap();
880        let item = NewItem {
881            account: Some("alice".into()),
882            service: Some("myservice".into()),
883            description: Some("note kind".into()),
884            ..NewItem::default()
885        };
886        file.add_password(
887            RecordType::GENERIC_PASSWORD,
888            &item,
889            b"s3cr3t",
890            "20260725123456Z",
891        )
892        .unwrap();
893
894        // Round-trip through bytes, so this exercises the serializer too.
895        let bytes = file.keychain().to_bytes().unwrap();
896        let mut reopened = KeychainFile::from_bytes(&bytes).unwrap();
897        reopened.unlock(b"master").unwrap();
898
899        let items = reopened.items();
900        assert_eq!(items.len(), 1);
901        let stored = &items[0];
902        assert_eq!(stored.account().as_deref(), Some("alice"));
903        assert_eq!(stored.service().as_deref(), Some("myservice"));
904        assert_eq!(stored.label().as_deref(), Some("myservice"));
905        assert_eq!(stored.created().as_deref(), Some("20260725123456Z"));
906        assert!(stored.has_secret());
907        assert_eq!(reopened.secret(stored).unwrap().as_slice(), b"s3cr3t");
908        assert_eq!(reopened.item_key_count(), 1);
909    }
910
911    #[test]
912    fn each_item_gets_its_own_key() {
913        let mut file = create(b"master", &CreateOptions::default()).unwrap();
914        for (account, secret) in [("a", "one"), ("b", "two"), ("c", "three")] {
915            let item = NewItem {
916                account: Some(account.into()),
917                service: Some("svc".into()),
918                ..NewItem::default()
919            };
920            file.add_password(
921                RecordType::GENERIC_PASSWORD,
922                &item,
923                secret.as_bytes(),
924                "20260725123456Z",
925            )
926            .unwrap();
927        }
928
929        let bytes = file.keychain().to_bytes().unwrap();
930        let mut reopened = KeychainFile::from_bytes(&bytes).unwrap();
931        reopened.unlock(b"master").unwrap();
932        assert_eq!(reopened.item_key_count(), 3, "one wrapped key per item");
933
934        for (account, expected) in [("a", "one"), ("b", "two"), ("c", "three")] {
935            let item = reopened
936                .items()
937                .into_iter()
938                .find(|item| item.account().as_deref() == Some(account))
939                .expect("item is present");
940            assert_eq!(
941                reopened.secret(&item).unwrap().as_slice(),
942                expected.as_bytes()
943            );
944        }
945    }
946
947    #[test]
948    fn internet_items_keep_their_network_attributes() {
949        let mut file = create(b"master", &CreateOptions::default()).unwrap();
950        let item = NewItem {
951            account: Some("bob".into()),
952            server: Some("example.com".into()),
953            path: Some("/login".into()),
954            port: Some(8080),
955            protocol: Some(*b"http"),
956            auth_type: Some(*b"dflt"),
957            ..NewItem::default()
958        };
959        file.add_password(
960            RecordType::INTERNET_PASSWORD,
961            &item,
962            b"pw",
963            "20260725123456Z",
964        )
965        .unwrap();
966
967        let bytes = file.keychain().to_bytes().unwrap();
968        let mut reopened = KeychainFile::from_bytes(&bytes).unwrap();
969        reopened.unlock(b"master").unwrap();
970
971        let items = reopened.items_of_type(RecordType::INTERNET_PASSWORD);
972        assert_eq!(items.len(), 1);
973        assert_eq!(items[0].server().as_deref(), Some("example.com"));
974        assert_eq!(items[0].path().as_deref(), Some("/login"));
975        assert_eq!(items[0].port(), Some(8080));
976        assert_eq!(items[0].label().as_deref(), Some("example.com"));
977        assert_eq!(reopened.secret(&items[0]).unwrap().as_slice(), b"pw");
978    }
979
980    #[test]
981    fn adding_to_a_locked_keychain_is_refused() {
982        let file = create(b"master", &CreateOptions::default()).unwrap();
983        let bytes = file.keychain().to_bytes().unwrap();
984        let mut locked = KeychainFile::from_bytes(&bytes).unwrap();
985
986        let result = locked.add_password(
987            RecordType::GENERIC_PASSWORD,
988            &NewItem::default(),
989            b"secret",
990            "20260725123456Z",
991        );
992        assert!(matches!(result, Err(Error::Locked)));
993    }
994
995    #[test]
996    fn commit_version_advances_with_each_write() {
997        let mut file = create(b"master", &CreateOptions::default()).unwrap();
998        assert_eq!(file.keychain().commit_version, Some(1));
999        file.add_password(
1000            RecordType::GENERIC_PASSWORD,
1001            &NewItem {
1002                account: Some("a".into()),
1003                ..NewItem::default()
1004            },
1005            b"x",
1006            "20260725123456Z",
1007        )
1008        .unwrap();
1009        assert_eq!(file.keychain().commit_version, Some(2));
1010    }
1011}