Skip to main content

keychain/
db.rs

1//! Opening, unlocking, and querying a keychain database.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use crate::crypto::{self, DbBlob, DbKeys, KeyBlob, SSGP_MAGIC, SecretBytes, Ssgp};
7use crate::error::{Error, Result};
8use crate::format::{Keychain, Record, Value, trim_nul};
9use crate::query::{Expression, class_name};
10use crate::schema::{RecordType, Schema};
11use base64::Engine as _;
12
13/// A keychain database, optionally unlocked.
14pub struct KeychainFile {
15    path: Option<PathBuf>,
16    keychain: Keychain,
17    schema: Schema,
18    /// Present once a password has been accepted.
19    keys: Option<DbKeys>,
20    /// Item keys by their 20-byte `ssgp` label, populated on unlock.
21    item_keys: BTreeMap<[u8; 20], SecretBytes>,
22}
23
24impl KeychainFile {
25    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
26        let path = path.as_ref().to_path_buf();
27        let bytes = std::fs::read(&path).map_err(|source| Error::reading(&path, source))?;
28        let mut file = Self::from_bytes(&bytes)?;
29        file.path = Some(path);
30        Ok(file)
31    }
32
33    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
34        let keychain = Keychain::parse(bytes)?;
35        let schema = keychain.schema()?;
36        Ok(Self {
37            path: None,
38            keychain,
39            schema,
40            keys: None,
41            item_keys: BTreeMap::new(),
42        })
43    }
44
45    pub fn path(&self) -> Option<&Path> {
46        self.path.as_deref()
47    }
48
49    pub fn keychain(&self) -> &Keychain {
50        &self.keychain
51    }
52
53    pub fn schema(&self) -> &Schema {
54        &self.schema
55    }
56
57    pub fn is_unlocked(&self) -> bool {
58        self.keys.is_some()
59    }
60
61    /// The database blob, which holds the salt and the encrypted database keys.
62    pub fn db_blob(&self) -> Result<DbBlob> {
63        let table = self
64            .keychain
65            .table(RecordType::METADATA)
66            .ok_or(Error::MissingTable("CSSM_DL_DB_RECORD_METADATA"))?;
67        let record = table
68            .records()
69            .next()
70            .ok_or_else(|| Error::format("metadata table has no record"))?;
71        DbBlob::parse(&record.key_data)
72    }
73
74    /// Derive the database keys from a password and unwrap every item key.
75    pub fn unlock(&mut self, password: &[u8]) -> Result<()> {
76        let keys = self.db_blob()?.unlock(password)?;
77        self.item_keys = self.unwrap_item_keys(&keys)?;
78        self.keys = Some(keys);
79        Ok(())
80    }
81
82    /// Item keys, by label. A key whose blob will not unwrap is skipped rather
83    /// than failing the unlock: one damaged key should not hide every item.
84    fn unwrap_item_keys(&self, keys: &DbKeys) -> Result<BTreeMap<[u8; 20], SecretBytes>> {
85        let mut out = BTreeMap::new();
86        let Some(table) = self.keychain.table(RecordType::SYMMETRIC_KEY) else {
87            return Ok(out);
88        };
89
90        for record in table.records() {
91            let Some(label) = self.key_label(record) else {
92                continue;
93            };
94            let Ok(blob) = KeyBlob::parse(&record.key_data) else {
95                continue;
96            };
97            if let Ok(key) = blob.unwrap_key(keys.encryption_key.as_slice()) {
98                out.insert(label, key);
99            }
100        }
101        Ok(out)
102    }
103
104    /// The `Label` of a key record, when it is a secure-storage group label.
105    fn key_label(&self, record: &Record) -> Option<[u8; 20]> {
106        let value = self
107            .schema
108            .attribute(RecordType::SYMMETRIC_KEY, record, "Label")?;
109        let bytes = value.as_bytes()?;
110        if bytes.len() != 20 || &bytes[..4] != SSGP_MAGIC {
111            return None;
112        }
113        Some(bytes.try_into().expect("checked length"))
114    }
115
116    /// Number of item keys recovered by [`Self::unlock`].
117    pub fn item_key_count(&self) -> usize {
118        self.item_keys.len()
119    }
120
121    /// Every password item in the keychain, in table order.
122    pub fn items(&self) -> Vec<Item<'_>> {
123        let mut items = Vec::new();
124        for record_type in [
125            RecordType::GENERIC_PASSWORD,
126            RecordType::INTERNET_PASSWORD,
127            RecordType::APPLESHARE_PASSWORD,
128        ] {
129            items.extend(self.items_of_type(record_type));
130        }
131        items
132    }
133
134    pub fn items_of_type(&self, record_type: RecordType) -> Vec<Item<'_>> {
135        let Some(table) = self.keychain.table(record_type) else {
136            return Vec::new();
137        };
138        table
139            .records()
140            .map(|record| Item {
141                record_type,
142                record,
143                schema: &self.schema,
144            })
145            .collect()
146    }
147
148    /// Every user-facing or cryptographic record that `kc get` can query.
149    pub fn queryable_items(&self) -> Vec<Item<'_>> {
150        let mut items = Vec::new();
151        for record_type in [
152            RecordType::GENERIC_PASSWORD,
153            RecordType::INTERNET_PASSWORD,
154            RecordType::APPLESHARE_PASSWORD,
155            RecordType::X509_CERTIFICATE,
156            RecordType::CERT,
157            RecordType::PRIVATE_KEY,
158            RecordType::PUBLIC_KEY,
159            RecordType::SYMMETRIC_KEY,
160        ] {
161            items.extend(self.items_of_type(record_type));
162        }
163        items
164    }
165
166    /// Query every supported record class with one shared typed expression.
167    pub fn select(&self, expression: &Expression) -> Result<Vec<Item<'_>>> {
168        self.queryable_items()
169            .into_iter()
170            .filter_map(|item| match expression.matches(&item) {
171                Ok(true) => Some(Ok(item)),
172                Ok(false) => None,
173                Err(error) => Some(Err(error)),
174            })
175            .collect()
176    }
177
178    /// Create a mutation-safe reference to an item in this exact database
179    /// revision.
180    pub fn item_ref(&self, item: &Item<'_>) -> Result<ItemRef> {
181        let path = self
182            .path()
183            .ok_or_else(|| Error::other("item references require a keychain opened from a path"))?;
184        Ok(ItemRef {
185            keychain: path.to_path_buf(),
186            commit_version: self.keychain.commit_version.unwrap_or(0),
187            record_type: item.record_type,
188            record_number: item.number(),
189        })
190    }
191
192    /// Validate that a reference names this database revision and still points
193    /// at a record.
194    pub fn resolve_ref(&self, reference: &ItemRef) -> Result<Item<'_>> {
195        let path = self
196            .path()
197            .ok_or_else(|| Error::other("item references require a keychain opened from a path"))?;
198        if path != reference.keychain {
199            return Err(Error::other(format!(
200                "item reference names {}, not {}",
201                reference.keychain.display(),
202                path.display()
203            )));
204        }
205        let version = self.keychain.commit_version.unwrap_or(0);
206        if version != reference.commit_version {
207            return Err(Error::other(format!(
208                "stale item reference: keychain revision is {version}, reference is {}",
209                reference.commit_version
210            )));
211        }
212        self.items_of_type(reference.record_type)
213            .into_iter()
214            .find(|item| item.number() == reference.record_number)
215            .ok_or(Error::NoSuchItem)
216    }
217
218    /// Records of any relation, for callers that need schema-level inspection.
219    pub fn records_of_type(&self, record_type: RecordType) -> Vec<&Record> {
220        self.keychain
221            .table(record_type)
222            .map(|table| table.records().collect())
223            .unwrap_or_default()
224    }
225
226    /// Decrypt an item's secret. Requires an unlocked keychain.
227    pub fn secret(&self, item: &Item<'_>) -> Result<SecretBytes> {
228        if self.keys.is_none() {
229            return Err(Error::Locked);
230        }
231        let ssgp = Ssgp::parse(&item.record.key_data)?;
232        let key = self
233            .item_keys
234            .get(&ssgp.label)
235            .ok_or_else(|| Error::MissingItemKey {
236                label: ssgp.label_hex(),
237            })?;
238        ssgp.open(key.as_slice())
239    }
240
241    /// Items matching every supplied criterion.
242    pub fn find(&self, query: &Query) -> Vec<Item<'_>> {
243        let candidates = match query.record_type {
244            Some(record_type) => self.items_of_type(record_type),
245            None => self.items(),
246        };
247        candidates
248            .into_iter()
249            .filter(|item| query.matches(item))
250            .collect()
251    }
252
253    /// Exactly one match, or an error naming the ambiguity.
254    pub fn find_one(&self, query: &Query) -> Result<Item<'_>> {
255        let mut matches = self.find(query);
256        match matches.len() {
257            0 => Err(Error::NoSuchItem),
258            1 => Ok(matches.remove(0)),
259            _ => Err(Error::other(format!(
260                "{} items match; narrow the query (accounts: {})",
261                matches.len(),
262                matches
263                    .iter()
264                    .map(|item| item.account().unwrap_or_else(|| "?".into()))
265                    .collect::<Vec<_>>()
266                    .join(", ")
267            ))),
268        }
269    }
270
271    /// Write the database back out.
272    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
273        let path = path.as_ref();
274        let bytes = self.keychain.to_bytes()?;
275        write_file(path, &bytes)
276    }
277
278    /// Write back to the path this was opened from.
279    pub fn save_in_place(&self) -> Result<()> {
280        let path = self
281            .path
282            .as_ref()
283            .ok_or_else(|| Error::other("this keychain was not opened from a file"))?;
284        self.save(path)
285    }
286
287    pub(crate) fn keychain_mut(&mut self) -> &mut Keychain {
288        &mut self.keychain
289    }
290
291    /// Re-derive the cached schema from the schema tables.
292    ///
293    /// Needed after adding a relation: every attribute lookup goes through the
294    /// cached [`Schema`], so it has to learn the new relation before records of
295    /// that type can be written or read.
296    pub(crate) fn reload_schema(&mut self) -> Result<()> {
297        self.schema = self.keychain.schema()?;
298        Ok(())
299    }
300
301    pub(crate) fn keys(&self) -> Option<&DbKeys> {
302        self.keys.as_ref()
303    }
304
305    #[allow(dead_code)]
306    pub(crate) fn set_path(&mut self, path: PathBuf) {
307        self.path = Some(path);
308    }
309
310    pub(crate) fn remember_item_key(&mut self, label: [u8; 20], key: SecretBytes) {
311        self.item_keys.insert(label, key);
312    }
313
314    /// The unwrapped key for an item, once the keychain is unlocked.
315    pub(crate) fn item_key(&self, label: &[u8; 20]) -> Option<&SecretBytes> {
316        self.item_keys.get(label)
317    }
318
319    /// Drop an item key that no longer has an item.
320    pub(crate) fn forget_item_key(&mut self, label: &[u8; 20]) {
321        self.item_keys.remove(label);
322    }
323}
324
325/// Opaque, revision-bound identity for piping `kc get -o @ref` into a mutation.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct ItemRef {
328    keychain: PathBuf,
329    commit_version: u32,
330    record_type: RecordType,
331    record_number: u32,
332}
333
334impl ItemRef {
335    const PREFIX: &'static str = "kc-ref-v1:";
336
337    pub fn encode(&self) -> String {
338        let body = serde_json::json!({
339            "keychain": self.keychain,
340            "commit_version": self.commit_version,
341            "record_type": self.record_type.0,
342            "record_number": self.record_number,
343        })
344        .to_string();
345        format!(
346            "{}{}",
347            Self::PREFIX,
348            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(body)
349        )
350    }
351
352    pub fn decode(encoded: &str) -> Result<Self> {
353        let body = encoded
354            .trim()
355            .strip_prefix(Self::PREFIX)
356            .ok_or_else(|| Error::other("expected a kc-ref-v1 item reference"))?;
357        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
358            .decode(body)
359            .map_err(|error| Error::other(format!("invalid item reference: {error}")))?;
360        let value: serde_json::Value = serde_json::from_slice(&bytes)
361            .map_err(|error| Error::other(format!("invalid item reference: {error}")))?;
362        let keychain = value["keychain"]
363            .as_str()
364            .map(PathBuf::from)
365            .ok_or_else(|| Error::other("item reference has no keychain path"))?;
366        let commit_version = u32::try_from(
367            value["commit_version"]
368                .as_u64()
369                .ok_or_else(|| Error::other("item reference has no commit version"))?,
370        )
371        .map_err(|_| Error::other("item reference commit version does not fit u32"))?;
372        let record_type = u32::try_from(
373            value["record_type"]
374                .as_u64()
375                .ok_or_else(|| Error::other("item reference has no record type"))?,
376        )
377        .map(RecordType)
378        .map_err(|_| Error::other("item reference record type does not fit u32"))?;
379        let record_number = u32::try_from(
380            value["record_number"]
381                .as_u64()
382                .ok_or_else(|| Error::other("item reference has no record number"))?,
383        )
384        .map_err(|_| Error::other("item reference record number does not fit u32"))?;
385        Ok(Self {
386            keychain,
387            commit_version,
388            record_type,
389            record_number,
390        })
391    }
392
393    pub fn class(&self) -> Option<&'static str> {
394        class_name(self.record_type)
395    }
396
397    pub fn keychain(&self) -> &Path {
398        &self.keychain
399    }
400
401    pub fn commit_version(&self) -> u32 {
402        self.commit_version
403    }
404
405    pub fn record_type(&self) -> RecordType {
406        self.record_type
407    }
408
409    pub fn record_number(&self) -> u32 {
410        self.record_number
411    }
412}
413
414/// Write atomically, keeping an existing file's permissions and defaulting new
415/// files to owner-only: a keychain file is worth a brute-force attempt.
416fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
417    use std::io::Write as _;
418    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
419
420    let mode = std::fs::metadata(path)
421        .map(|meta| meta.permissions().mode() & 0o777)
422        .unwrap_or(0o600);
423    let temp = path.with_extension(format!("kc-tmp.{}", std::process::id()));
424
425    let mut file = std::fs::OpenOptions::new()
426        .write(true)
427        .create(true)
428        .truncate(true)
429        .mode(mode)
430        .open(&temp)
431        .map_err(|source| Error::io(format!("could not create {}", temp.display()), source))?;
432    let result = file
433        .write_all(bytes)
434        .and_then(|()| file.sync_all())
435        .map_err(|source| Error::io(format!("could not write {}", temp.display()), source));
436    drop(file);
437
438    if let Err(error) = result {
439        let _ = std::fs::remove_file(&temp);
440        return Err(error);
441    }
442    std::fs::rename(&temp, path).map_err(|source| {
443        let _ = std::fs::remove_file(&temp);
444        Error::io(format!("could not replace {}", path.display()), source)
445    })
446}
447
448/// Attributes that hold a four-character code in an integer field.
449pub const FOUR_CHAR_CODE_ATTRIBUTES: [&str; 3] = ["ptcl", "crtr", "type"];
450
451/// A password item: a record plus the schema needed to read it.
452#[derive(Clone, Copy)]
453pub struct Item<'kc> {
454    pub record_type: RecordType,
455    pub record: &'kc Record,
456    schema: &'kc Schema,
457}
458
459impl<'kc> Item<'kc> {
460    pub fn number(&self) -> u32 {
461        self.record.number
462    }
463
464    pub fn attribute(&self, name: &str) -> Option<&'kc Value> {
465        self.schema.attribute(self.record_type, self.record, name)
466    }
467
468    /// An attribute's bytes as a string, NUL-trimmed.
469    pub fn text(&self, name: &str) -> Option<String> {
470        let bytes = self.attribute(name)?.as_bytes()?;
471        let trimmed = trim_nul(bytes);
472        if trimmed.is_empty() {
473            return None;
474        }
475        Some(String::from_utf8_lossy(trimmed).into_owned())
476    }
477
478    pub fn number_attribute(&self, name: &str) -> Option<u32> {
479        self.attribute(name)?.as_u32()
480    }
481
482    pub fn account(&self) -> Option<String> {
483        self.text("acct")
484    }
485
486    pub fn service(&self) -> Option<String> {
487        self.text("svce")
488    }
489
490    pub fn server(&self) -> Option<String> {
491        self.text("srvr")
492    }
493
494    pub fn label(&self) -> Option<String> {
495        self.text("PrintName")
496    }
497
498    pub fn path(&self) -> Option<String> {
499        self.text("path")
500    }
501
502    pub fn port(&self) -> Option<u32> {
503        self.number_attribute("port").filter(|port| *port != 0)
504    }
505
506    pub fn volume(&self) -> Option<String> {
507        self.text("vlme")
508    }
509
510    pub fn address(&self) -> Option<String> {
511        self.text("addr")
512    }
513
514    pub fn signature(&self) -> Option<String> {
515        self.text("ssig")
516    }
517
518    pub fn created(&self) -> Option<String> {
519        self.text("cdat")
520    }
521
522    pub fn modified(&self) -> Option<String> {
523        self.text("mdat")
524    }
525
526    /// An attribute rendered the way `kc` displays it.
527    ///
528    /// Four-char codes are stored in integer fields (`ptcl` holds `htps` as
529    /// 0x68747073); they read as text, so they are shown and matched as text.
530    pub fn display_attribute(&self, name: &str) -> Option<String> {
531        let value = self.attribute(name)?;
532        if FOUR_CHAR_CODE_ATTRIBUTES.contains(&name)
533            && let Some(number) = value.as_u32()
534        {
535            let bytes = number.to_be_bytes();
536            if bytes.iter().all(|byte| (0x20..0x7f).contains(byte)) {
537                return Some(String::from_utf8_lossy(&bytes).into_owned());
538            }
539        }
540        Some(value.to_display_string())
541    }
542
543    /// Every attribute that has a value, in relation order.
544    pub fn attributes(&self) -> Vec<(&'kc str, &'kc Value)> {
545        self.schema.named_attributes(self.record_type, self.record)
546    }
547
548    /// True when the record carries an encrypted secret.
549    pub fn has_secret(&self) -> bool {
550        Ssgp::parse(&self.record.key_data).is_ok()
551    }
552}
553
554/// Attribute-match criteria for password and identity lookups.
555#[derive(Debug, Clone, Default)]
556pub struct Query {
557    pub record_type: Option<RecordType>,
558    pub account: Option<String>,
559    pub service: Option<String>,
560    pub server: Option<String>,
561    pub label: Option<String>,
562    pub path: Option<String>,
563    pub port: Option<u32>,
564    pub volume: Option<String>,
565    pub address: Option<String>,
566    pub signature: Option<String>,
567    /// `desc`, the "kind" Keychain Access shows.
568    pub description: Option<String>,
569    /// `icmt`, the comment.
570    pub comment: Option<String>,
571    /// `sdmn`, an internet item's authentication realm.
572    pub security_domain: Option<String>,
573    /// `gena`, a generic item's application-defined bytes.
574    pub generic: Option<String>,
575    /// Any other attribute, by the name the relation gives it, compared against
576    /// the value as [`Item::display_attribute`] renders it. This is the escape
577    /// hatch for attributes without a flag of their own.
578    pub attributes: Vec<(String, String)>,
579}
580
581impl Query {
582    pub fn generic() -> Self {
583        Self {
584            record_type: Some(RecordType::GENERIC_PASSWORD),
585            ..Self::default()
586        }
587    }
588
589    pub fn internet() -> Self {
590        Self {
591            record_type: Some(RecordType::INTERNET_PASSWORD),
592            ..Self::default()
593        }
594    }
595
596    pub fn appleshare() -> Self {
597        Self {
598            record_type: Some(RecordType::APPLESHARE_PASSWORD),
599            ..Self::default()
600        }
601    }
602
603    pub fn is_empty(&self) -> bool {
604        self.account.is_none()
605            && self.service.is_none()
606            && self.server.is_none()
607            && self.label.is_none()
608            && self.path.is_none()
609            && self.port.is_none()
610            && self.volume.is_none()
611            && self.address.is_none()
612            && self.signature.is_none()
613            && self.description.is_none()
614            && self.comment.is_none()
615            && self.security_domain.is_none()
616            && self.generic.is_none()
617            && self.attributes.is_empty()
618    }
619
620    fn matches(&self, item: &Item<'_>) -> bool {
621        let text_matches = |wanted: &Option<String>, actual: Option<String>| match wanted {
622            None => true,
623            Some(wanted) => actual.is_some_and(|actual| actual == *wanted),
624        };
625
626        text_matches(&self.account, item.account())
627            && text_matches(&self.service, item.service())
628            && text_matches(&self.server, item.server())
629            && text_matches(&self.label, item.label())
630            && text_matches(&self.path, item.path())
631            && text_matches(&self.volume, item.volume())
632            && text_matches(&self.address, item.address())
633            && text_matches(&self.signature, item.signature())
634            && text_matches(&self.description, item.text("desc"))
635            && text_matches(&self.comment, item.text("icmt"))
636            && text_matches(&self.security_domain, item.text("sdmn"))
637            && text_matches(&self.generic, item.text("gena"))
638            && match self.port {
639                None => true,
640                Some(port) => item.port() == Some(port),
641            }
642            && self.attributes.iter().all(|(name, wanted)| {
643                item.display_attribute(name)
644                    .is_some_and(|actual| actual == *wanted)
645            })
646    }
647}
648
649/// Summary for `kc info`.
650#[derive(Debug, Clone)]
651pub struct Info {
652    pub version: u32,
653    pub tables: Vec<(RecordType, usize)>,
654    pub blob_version: u32,
655    pub sequence: u32,
656    pub idle_timeout: u32,
657    pub lock_on_sleep: bool,
658    pub salt: String,
659    pub iv: String,
660    pub pbkdf2_iterations: u32,
661}
662
663impl KeychainFile {
664    pub fn info(&self) -> Result<Info> {
665        let blob = self.db_blob()?;
666        Ok(Info {
667            version: self.keychain.version,
668            tables: self
669                .keychain
670                .tables
671                .iter()
672                .map(|table| (table.record_type, table.record_count()))
673                .collect(),
674            blob_version: blob.version,
675            sequence: blob.sequence,
676            idle_timeout: blob.idle_timeout,
677            lock_on_sleep: blob.lock_on_sleep,
678            salt: hex::encode(blob.salt),
679            iv: hex::encode(blob.iv),
680            pbkdf2_iterations: crypto::PBKDF2_ITERATIONS,
681        })
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    #[test]
690    fn queries_match_on_every_supplied_field() {
691        let mut query = Query::generic();
692        assert!(query.is_empty());
693        query.account = Some("alice".into());
694        assert!(!query.is_empty());
695        assert_eq!(query.record_type, Some(RecordType::GENERIC_PASSWORD));
696
697        let internet = Query::internet();
698        assert_eq!(internet.record_type, Some(RecordType::INTERNET_PASSWORD));
699    }
700
701    #[test]
702    fn parsing_rejects_garbage_before_any_crypto_happens() {
703        assert!(KeychainFile::from_bytes(b"not a keychain").is_err());
704    }
705}