Skip to main content

keychain_core/
container.rs

1//! The Apple `AppleDatabase` container that backs a `login.keychain-db`.
2//!
3//! Layout (all fields big-endian), reverse-engineered by `chainbreaker` and
4//! matching Apple's `libsecurity_cdsa_utilities` `AppleDatabase.cpp`:
5//!
6//! * a 20-byte header (`kych` signature, version, header size, schema offset);
7//! * a schema at `schema_offset` listing `table_count` table offsets;
8//! * each table has a 28-byte header then an array of 4-byte record offsets;
9//! * the `DbBlob` (master-key metadata) sits `0x38` past the metadata table;
10//! * secrets live in the generic/internet-password tables as `SSGP` blobs whose
11//!   per-record key is wrapped in the symmetric-key table.
12//!
13//! Every read is bounds-checked through the fleet `safe-read` crate: malformed
14//! input yields a typed error or an empty attribute, never a panic.
15
16use std::collections::BTreeMap;
17
18use safe_read::try_be_u32;
19
20use crate::error::KeychainError;
21
22/// `kych` — the `AppleDatabase` / keychain file signature.
23pub const KEYCHAIN_SIGNATURE: u32 = 0x6b79_6368;
24/// `0xFADE0711` — the `CommonBlob` magic prefixing every `DbBlob` / `KeyBlob`.
25pub const COMMON_BLOB_MAGIC: u32 = 0xFADE_0711;
26
27const HEADER_SIZE: usize = 20;
28const SCHEMA_HEADER_SIZE: usize = 8;
29const TABLE_HEADER_SIZE: usize = 28;
30const ATOM: usize = 4;
31const DB_BLOB_OFFSET_IN_METADATA: usize = 0x38;
32
33// CSSM record types (see `cssmtype.h`).
34/// `CSSM_DL_DB_RECORD_METADATA` — the table holding the `DbBlob`.
35pub const RECORD_METADATA: u32 = 0x8000_8000;
36/// `CSSM_DL_DB_RECORD_SYMMETRIC_KEY` — wrapped per-record keys.
37pub const RECORD_SYMMETRIC_KEY: u32 = 0x0000_0011;
38/// `CSSM_DL_DB_RECORD_GENERIC_PASSWORD` — generic secrets (incl. Safe Storage).
39pub const RECORD_GENERIC_PASSWORD: u32 = 0x8000_0000;
40/// `CSSM_DL_DB_RECORD_INTERNET_PASSWORD`.
41pub const RECORD_INTERNET_PASSWORD: u32 = 0x8000_0001;
42
43/// The `DbBlob`: the salt/IV/ciphertext that guard the DBKey (master wrap).
44#[derive(Debug, Clone)]
45pub struct DbBlob {
46    /// PBKDF2 salt for master-key derivation.
47    pub salt: [u8; 20],
48    /// 3DES-CBC IV for the DBKey unwrap.
49    pub iv: [u8; 8],
50    /// The wrapped DBKey ciphertext.
51    pub cipher: Vec<u8>,
52}
53
54/// A record in the symmetric-key table: a per-record key wrapped under the DBKey.
55#[derive(Debug, Clone)]
56pub struct KeyBlobRecord {
57    /// 20-byte label (`ssgp` magic + 16-byte key label) that a secret references.
58    pub label: [u8; 20],
59    /// The blob's own 3DES-CBC IV (second unwrap pass).
60    pub iv: [u8; 8],
61    /// The wrapped key ciphertext.
62    pub cipher: Vec<u8>,
63}
64
65/// The `SSGP` (Secure Storage Group) blob carrying one encrypted secret.
66#[derive(Debug, Clone)]
67pub struct SsgpBlob {
68    /// 20-byte key index (magic + label) mapping to a [`KeyBlobRecord::label`].
69    pub key_index: [u8; 20],
70    /// 3DES-CBC IV for the payload.
71    pub iv: [u8; 8],
72    /// The encrypted secret.
73    pub payload: Vec<u8>,
74}
75
76/// A generic-password record's cleartext attributes plus its encrypted secret.
77#[derive(Debug, Clone)]
78pub struct GenericRecord {
79    /// The `acct` attribute (account / username).
80    pub account: String,
81    /// The `svce` attribute (service name; e.g. `Chrome Safe Storage`).
82    pub service: String,
83    /// The `PrintName` label shown in Keychain Access.
84    pub label: String,
85    /// The encrypted secret, if the record has an SSGP area.
86    pub ssgp: Option<SsgpBlob>,
87}
88
89/// A parsed keychain container over borrowed bytes.
90#[derive(Debug)]
91pub struct Container<'a> {
92    data: &'a [u8],
93    /// CSSM record type -> table offset (relative to the end of the header).
94    table_by_type: BTreeMap<u32, usize>,
95}
96
97impl<'a> Container<'a> {
98    /// Parse the header + schema and index every table by its CSSM type.
99    pub fn parse(data: &'a [u8]) -> Result<Self, KeychainError> {
100        let sig = read_u32(data, 0)?;
101        if sig != KEYCHAIN_SIGNATURE {
102            return Err(KeychainError::BadSignature { found: sig });
103        }
104        let schema_offset = read_u32(data, 12)? as usize;
105        let table_count = read_u32(data, schema_offset + 4)? as usize;
106
107        let mut table_by_type = BTreeMap::new();
108        let base = HEADER_SIZE + SCHEMA_HEADER_SIZE;
109        for i in 0..table_count {
110            let table_offset = read_u32(data, base + ATOM * i)? as usize;
111            // Read the table's own header to learn its CSSM type id.
112            let table_base = HEADER_SIZE + table_offset;
113            let table_id = read_u32(data, table_base + ATOM)?;
114            table_by_type.entry(table_id).or_insert(table_offset);
115        }
116
117        Ok(Self {
118            data,
119            table_by_type,
120        })
121    }
122
123    /// Locate and parse the `DbBlob` (salt / IV / wrapped DBKey).
124    pub fn db_blob(&self) -> Result<DbBlob, KeychainError> {
125        let meta_offset = *self
126            .table_by_type
127            .get(&RECORD_METADATA)
128            .ok_or(KeychainError::DbBlobMissing)?;
129        let base = HEADER_SIZE + meta_offset + DB_BLOB_OFFSET_IN_METADATA;
130
131        let magic = read_u32(self.data, base)?;
132        if magic != COMMON_BLOB_MAGIC {
133            return Err(KeychainError::BadBlobMagic {
134                found: magic,
135                offset: base,
136            });
137        }
138        // CommonBlob(8) magic@0 ver@4; StartCryptoBlob@8; TotalLength@12;
139        // RandomSignature[16]@16; Sequence@32; Params(8)@36; Salt[20]@44;
140        // IV[8]@64; BlobSignature[20]@72.
141        let start_crypto = read_u32(self.data, base + 8)? as usize;
142        let total_length = read_u32(self.data, base + 12)? as usize;
143        let salt = read_array::<20>(self.data, base + 44)?;
144        let iv = read_array::<8>(self.data, base + 64)?;
145        let cipher = slice(self.data, base + start_crypto, base + total_length)?.to_vec();
146
147        Ok(DbBlob { salt, iv, cipher })
148    }
149
150    /// Every wrapped per-record key in the symmetric-key table.
151    ///
152    /// Records that are not `ssgp`-tagged are skipped (they carry no secret key).
153    pub fn symmetric_key_records(&self) -> Vec<KeyBlobRecord> {
154        let mut out = Vec::new();
155        for base in self.record_bases(RECORD_SYMMETRIC_KEY) {
156            if let Some(rec) = self.parse_key_blob(base) {
157                out.push(rec);
158            }
159        }
160        out
161    }
162
163    /// Every generic-password record with its cleartext attributes and SSGP blob.
164    pub fn generic_password_records(&self) -> Vec<GenericRecord> {
165        self.record_bases(RECORD_GENERIC_PASSWORD)
166            .into_iter()
167            .filter_map(|base| self.parse_generic_record(base))
168            .collect()
169    }
170
171    /// Parse one symmetric-key-table record into a [`KeyBlobRecord`].
172    fn parse_key_blob(&self, base: usize) -> Option<KeyBlobRecord> {
173        // _KEY_BLOB_REC_HEADER: RecordSize@0, RecordCount@4, Dummy[124] (132).
174        let record_size = try_be_u32(self.data, base)? as usize;
175        let rec = self.data.get(base + 132..base + record_size)?;
176        // _KEY_BLOB: CommonBlob(8)@0, StartCryptoBlob@8, TotalLength@12, IV[8]@16.
177        let start_crypto = try_be_u32(rec, 8)? as usize;
178        let total_length = try_be_u32(rec, 12)? as usize;
179        let iv = read_array::<8>(rec, 16).ok()?;
180        // The 20-byte label sits 8 bytes past the ciphertext, tagged `ssgp`.
181        if rec.get(total_length + 8..total_length + 12)? != b"ssgp" {
182            return None;
183        }
184        let label = read_array::<20>(rec, total_length + 8).ok()?;
185        let cipher = rec.get(start_crypto..total_length)?.to_vec();
186        if cipher.is_empty() {
187            return None;
188        }
189        Some(KeyBlobRecord { label, iv, cipher })
190    }
191
192    /// Parse one generic-password record's attributes + SSGP blob.
193    fn parse_generic_record(&self, base: usize) -> Option<GenericRecord> {
194        // _GENERIC_PW_HEADER: 22 x u32. Field i at offset 4*i.
195        //  [0]RecordSize [4]SSGPArea [13]PrintName [19]Account [20]Service.
196        let record_size = try_be_u32(self.data, base)? as usize;
197        let ssgp_area = try_be_u32(self.data, base + 4 * 4)? as usize;
198        let print_name_col = try_be_u32(self.data, base + 4 * 13)?;
199        let account_col = try_be_u32(self.data, base + 4 * 19)?;
200        let service_col = try_be_u32(self.data, base + 4 * 20)?;
201
202        let body = self.data.get(base + 88..base + record_size)?;
203
204        let ssgp = if ssgp_area != 0 {
205            let area = body.get(..ssgp_area)?;
206            let key_index = read_array::<20>(area, 0).ok()?;
207            let iv = read_array::<8>(area, 20).ok()?;
208            let payload = area.get(28..)?.to_vec();
209            Some(SsgpBlob {
210                key_index,
211                iv,
212                payload,
213            })
214        } else {
215            None
216        };
217
218        Some(GenericRecord {
219            account: read_lv(self.data, base, account_col),
220            service: read_lv(self.data, base, service_col),
221            label: read_lv(self.data, base, print_name_col),
222            ssgp,
223        })
224    }
225
226    /// The absolute base address of every record in a table.
227    fn record_bases(&self, table_type: u32) -> Vec<usize> {
228        let Some(&table_offset) = self.table_by_type.get(&table_type) else {
229            return Vec::new();
230        };
231        let table_base = HEADER_SIZE + table_offset;
232        let Some(record_count) = try_be_u32(self.data, table_base + 8) else {
233            return Vec::new();
234        };
235        let record_count = record_count as usize;
236        let list_base = table_base + TABLE_HEADER_SIZE;
237
238        let mut out = Vec::new();
239        let mut o = 0usize;
240        // Bounded by the record count AND by staying inside the buffer, so a
241        // crafted count can never spin forever.
242        while out.len() < record_count {
243            let Some(record_offset) = try_be_u32(self.data, list_base + ATOM * o) else {
244                break; // ran off the end of the buffer
245            };
246            let record_offset = record_offset as usize;
247            if record_offset != 0 && record_offset % 4 == 0 {
248                out.push(HEADER_SIZE + table_offset + record_offset);
249            }
250            o += 1;
251        }
252        out
253    }
254}
255
256/// Read a big-endian `u32`, erroring loudly with the offending offset.
257fn read_u32(data: &[u8], off: usize) -> Result<u32, KeychainError> {
258    try_be_u32(data, off).ok_or(KeychainError::TooShort {
259        offset: off,
260        needed: 4,
261        available: data.len().saturating_sub(off.min(data.len())),
262    })
263}
264
265/// Read a fixed-size byte array at `off`.
266fn read_array<const N: usize>(data: &[u8], off: usize) -> Result<[u8; N], KeychainError> {
267    let end = off.checked_add(N).ok_or(KeychainError::TooShort {
268        offset: off,
269        needed: N,
270        available: 0,
271    })?;
272    let slice = data.get(off..end).ok_or(KeychainError::TooShort {
273        offset: off,
274        needed: N,
275        available: data.len().saturating_sub(off.min(data.len())),
276    })?;
277    let mut out = [0u8; N];
278    out.copy_from_slice(slice);
279    Ok(out)
280}
281
282/// Slice `data[start..end]`, erroring loudly if out of range.
283fn slice(data: &[u8], start: usize, end: usize) -> Result<&[u8], KeychainError> {
284    if start > end {
285        return Err(KeychainError::TooShort {
286            offset: start,
287            needed: 0,
288            available: 0,
289        });
290    }
291    data.get(start..end).ok_or(KeychainError::TooShort {
292        offset: start,
293        needed: end.saturating_sub(start),
294        available: data.len().saturating_sub(start.min(data.len())),
295    })
296}
297
298/// Read a length-prefixed attribute value at `base + (col & !1)`.
299///
300/// The column pointer's low bit is a flag (cleared here); a zero column means
301/// the attribute is absent. The 4-byte length is padded up to a 4-byte
302/// boundary. Trailing NULs are trimmed. Any out-of-range read yields an empty
303/// string rather than a panic — a truncated attribute is not fatal to the scan.
304fn read_lv(data: &[u8], base: usize, col: u32) -> String {
305    let col = (col & 0xFFFF_FFFE) as usize;
306    if col == 0 {
307        return String::new();
308    }
309    let Some(len) = try_be_u32(data, base + col) else {
310        return String::new();
311    };
312    let len = len as usize;
313    let padded = len.div_ceil(4) * 4;
314    let start = base + col + 4;
315    let end = start.saturating_add(padded).min(data.len());
316    let bytes = data.get(start..end).unwrap_or(&[]);
317    let trimmed = bytes
318        .iter()
319        .rposition(|&b| b != 0)
320        .map_or(&bytes[..0], |p| &bytes[..=p]);
321    String::from_utf8_lossy(trimmed).into_owned()
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn parse_rejects_non_keychain() {
330        let err = Container::parse(b"NOTAKEYCHAINxxxxxxxx").unwrap_err();
331        assert!(matches!(err, KeychainError::BadSignature { .. }));
332    }
333
334    #[test]
335    fn parse_rejects_truncated_header() {
336        assert!(matches!(
337            Container::parse(b"kyc").unwrap_err(),
338            KeychainError::TooShort { .. }
339        ));
340    }
341
342    #[test]
343    fn read_lv_absent_column_is_empty() {
344        assert_eq!(read_lv(&[0u8; 64], 0, 0), "");
345    }
346
347    #[test]
348    fn read_lv_out_of_range_is_empty_not_panic() {
349        // col points past the buffer -> empty, no panic.
350        assert_eq!(read_lv(&[0u8; 8], 0, 0x1000), "");
351    }
352}