1use 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
35const KEY_RECORD_UNKNOWN3: u32 = 4;
38
39const PRIVATE_KEY_RECORD_UNKNOWN3: u32 = 5;
41
42#[derive(Debug, Clone)]
44pub struct NewIdentity {
45 pub certificate: Vec<u8>,
47 pub private_key: Vec<u8>,
49 pub label: Option<String>,
51 pub trusted_applications: Vec<TrustedApplication>,
53}
54
55#[derive(Debug, Clone)]
57pub struct CreateOptions {
58 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
72pub 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 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 }
137 _ => {
138 table.slots.push(Slot::Empty);
141 }
142 }
143
144 tables.push(table);
145 }
146
147 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 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
205fn 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 _ => None,
237 };
238 }
239}
240
241fn 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#[derive(Debug, Clone, Default)]
276pub struct NewItem {
277 pub label: Option<String>,
280 pub account: Option<String>,
282 pub service: Option<String>,
284 pub generic: Option<Vec<u8>>,
286 pub server: Option<String>,
288 pub security_domain: Option<String>,
290 pub path: Option<String>,
292 pub port: Option<u32>,
294 pub protocol: Option<[u8; 4]>,
296 pub auth_type: Option<[u8; 4]>,
298 pub volume: Option<String>,
300 pub address: Option<String>,
302 pub signature: Option<String>,
304 pub description: Option<String>,
306 pub comment: Option<String>,
308 pub trusted_applications: Vec<TrustedApplication>,
311}
312
313impl NewItem {
314 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 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 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 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 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 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 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 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 number: 0,
463 version,
464 unknown3: 0,
465 unknown5: 0,
466 key_data: ssgp.to_bytes(),
467 attributes: item_attributes,
468 });
469
470 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 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 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 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 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 number: 0,
587 version,
588 unknown3: 0,
589 unknown5: 0,
590 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 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 slots: vec![Slot::Empty],
683 layout: Vec::new(),
684 indexes: TableIndexes::Parsed(index_declarations(definition.indexes)),
685 };
686 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 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 #[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
756pub 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
767fn 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
786pub 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
795pub fn schema_of_created(file: &KeychainFile) -> Result<Schema> {
797 let schema = file.keychain().schema()?;
798 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
817pub 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 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}