1use std::collections::BTreeMap;
17
18use safe_read::try_be_u32;
19
20use crate::error::KeychainError;
21
22pub const KEYCHAIN_SIGNATURE: u32 = 0x6b79_6368;
24pub 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
33pub const RECORD_METADATA: u32 = 0x8000_8000;
36pub const RECORD_SYMMETRIC_KEY: u32 = 0x0000_0011;
38pub const RECORD_GENERIC_PASSWORD: u32 = 0x8000_0000;
40pub const RECORD_INTERNET_PASSWORD: u32 = 0x8000_0001;
42
43#[derive(Debug, Clone)]
45pub struct DbBlob {
46 pub salt: [u8; 20],
48 pub iv: [u8; 8],
50 pub cipher: Vec<u8>,
52}
53
54#[derive(Debug, Clone)]
56pub struct KeyBlobRecord {
57 pub label: [u8; 20],
59 pub iv: [u8; 8],
61 pub cipher: Vec<u8>,
63}
64
65#[derive(Debug, Clone)]
67pub struct SsgpBlob {
68 pub key_index: [u8; 20],
70 pub iv: [u8; 8],
72 pub payload: Vec<u8>,
74}
75
76#[derive(Debug, Clone)]
78pub struct GenericRecord {
79 pub account: String,
81 pub service: String,
83 pub label: String,
85 pub ssgp: Option<SsgpBlob>,
87}
88
89#[derive(Debug)]
91pub struct Container<'a> {
92 data: &'a [u8],
93 table_by_type: BTreeMap<u32, usize>,
95}
96
97impl<'a> Container<'a> {
98 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 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 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 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 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 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 fn parse_key_blob(&self, base: usize) -> Option<KeyBlobRecord> {
173 let record_size = try_be_u32(self.data, base)? as usize;
175 let rec = self.data.get(base + 132..base + record_size)?;
176 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 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 fn parse_generic_record(&self, base: usize) -> Option<GenericRecord> {
194 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 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 while out.len() < record_count {
243 let Some(record_offset) = try_be_u32(self.data, list_base + ATOM * o) else {
244 break; };
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
256fn 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
265fn 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
282fn 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
298fn 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 assert_eq!(read_lv(&[0u8; 8], 0, 0x1000), "");
351 }
352}