filevault-core 0.1.4

Reader/decryptor for Apple CoreStorage / FileVault 2 (FVDE) encrypted volumes — AES-XTS, PBKDF2, RFC 3394 key unwrap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! # filevault — Apple CoreStorage / FileVault 2 (FVDE) reader & decryptor
//!
//! A panic-free, bounds-checked decryptor for CoreStorage / FileVault 2 volumes
//! (macOS 10.7–10.15, AES-XTS-128, password protector). Parses the physical
//! volume header, decrypts the CoreStorage metadata, derives the volume key
//! hierarchy from a password (PBKDF2-HMAC-SHA256 → RFC 3394 AES-KW → SHA-256
//! tweak key, all RustCrypto — never hand-rolled), and exposes the plaintext
//! logical volume as a `Read + Seek` stream.
//!
//! APFS-native encryption (10.13+) is a separate format and is out of scope.
//!
//! ```no_run
//! use std::fs::File;
//! use filevault::FileVaultVolume;
//!
//! let image = File::open("cs_partition.raw")?;
//! let mut volume = FileVaultVolume::unlock_with_password(image, "fvde-TEST")?;
//! let mut sector = [0u8; 512];
//! volume.read_at(0, &mut sector)?;
//! # Ok::<(), filevault::FileVaultError>(())
//! ```

#![forbid(unsafe_code)]
// `doc_markdown` false-positives on the domain proper nouns that pervade these
// docs (CoreStorage, FileVault, FVDE, PBKDF2, RustCrypto, UserType, …).
#![allow(clippy::doc_markdown)]
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]

use std::io::{Read, Seek, SeekFrom};

pub mod context;
pub mod error;
pub mod metadata;
pub mod read;
#[cfg(test)]
mod test_support;
pub mod unlock;
#[cfg(feature = "vfs")]
pub mod vfs;
#[cfg(feature = "vfs")]
pub use vfs::FileVaultLayer;
pub mod volume;
pub mod volume_header;
pub mod xts;

pub use context::{EncryptionContext, LogicalVolumeInfo, Protector, ProtectorKind};
pub use error::FileVaultError;
pub use volume::DecryptedVolume;
pub use volume_header::VolumeHeader;

/// Physical volume header length.
const VOLUME_HEADER_LEN: usize = 512;

/// Password-independent metadata parsed from a CoreStorage volume.
///
/// Everything here is derivable WITHOUT the password, so `filevault-forensic`
/// can audit protector inventory, encryption state, and KDF strength on a locked
/// volume. Producing it never unwraps any key.
#[derive(Debug, Clone)]
pub struct FileVaultInfo {
    /// Physical volume identifier (UUID string).
    pub physical_volume_identifier: String,
    /// PBKDF2 iteration count of the password protector.
    pub pbkdf2_iterations: u32,
    /// PBKDF2 salt (16 bytes).
    pub pbkdf2_salt: [u8; 16],
    /// Logical volume family UUID (string).
    pub family_uuid: String,
    /// Logical volume identifier UUID (string), if present.
    pub lv_identifier: Option<String>,
    /// Logical volume name, if present.
    pub lv_name: Option<String>,
    /// Logical volume size in bytes.
    pub lv_size: u64,
    /// Encryption method label (always AES-XTS-128 for a supported volume).
    pub encryption_method: &'static str,
    /// LV conversion status (`Complete` / `Converting` / …), if present.
    pub conversion_status: Option<String>,
    /// Protectors (crypto users) present.
    pub protectors: Vec<Protector>,
}

/// An unlocked CoreStorage / FileVault volume presenting the decrypted logical
/// volume as a `Read + Seek` stream.
#[derive(Debug)]
pub struct FileVaultVolume<R: Read + Seek> {
    decrypted: DecryptedVolume<R>,
    info: FileVaultInfo,
}

impl<R: Read + Seek> FileVaultVolume<R> {
    /// Parse, decrypt the metadata, derive the key hierarchy from `password`,
    /// and return an unlocked volume.
    ///
    /// # Errors
    /// Any [`FileVaultError`] from parsing (not CoreStorage, unsupported method,
    /// missing metadata) or key derivation (wrong password → `KeyUnwrap`).
    pub fn unlock_with_password(mut reader: R, password: &str) -> Result<Self, FileVaultError> {
        let mut header_bytes = [0u8; VOLUME_HEADER_LEN];
        reader.seek(SeekFrom::Start(0))?;
        read_exact_or_err(&mut reader, &mut header_bytes)?;
        let header = VolumeHeader::parse(&header_bytes)?;

        let plaintext = decrypt_metadata_region(&mut reader, &header)?;
        let context = EncryptionContext::extract(&plaintext)?;
        let lv = LogicalVolumeInfo::extract(&plaintext)?;

        let family_uuid_bytes =
            parse_uuid_bytes(&lv.family_uuid).ok_or(FileVaultError::MetadataStructureMissing {
                what: "parseable family UUID",
            })?;
        let keys = unlock::derive_volume_keys(password, &context, &family_uuid_bytes)?;

        let (physical_base, size) = resolve_lv_extent(&plaintext, &header, &lv);

        let info = build_info(&header, &context, &lv, size);
        let decrypted = DecryptedVolume::new(reader, keys, physical_base, size);
        Ok(FileVaultVolume { decrypted, info })
    }

    /// Read and decrypt `buf.len()` bytes at logical `offset` (see
    /// [`DecryptedVolume::read_at`]).
    ///
    /// # Errors
    /// [`FileVaultError::Io`] if the underlying read fails.
    pub fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<usize, FileVaultError> {
        self.decrypted.read_at(offset, buf)
    }

    /// The logical volume size in bytes.
    #[must_use]
    pub fn size(&self) -> u64 {
        self.decrypted.size()
    }

    /// The password-independent parsed metadata.
    #[must_use]
    pub fn info(&self) -> &FileVaultInfo {
        &self.info
    }

    /// Consume the volume, returning the inner decrypted `Read + Seek` stream.
    #[must_use]
    pub fn into_decrypted(self) -> DecryptedVolume<R> {
        self.decrypted
    }
}

impl<R: Read + Seek> Read for FileVaultVolume<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.decrypted.read(buf)
    }
}

impl<R: Read + Seek> Seek for FileVaultVolume<R> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.decrypted.seek(pos)
    }
}

/// Parse only the password-independent metadata from a reader, WITHOUT the
/// password — the entry point `filevault-forensic` uses to audit a locked volume.
///
/// # Errors
/// Any [`FileVaultError`] from header/metadata parsing.
pub fn parse_info<R: Read + Seek>(mut reader: R) -> Result<FileVaultInfo, FileVaultError> {
    let mut header_bytes = [0u8; VOLUME_HEADER_LEN];
    reader.seek(SeekFrom::Start(0))?;
    read_exact_or_err(&mut reader, &mut header_bytes)?;
    let header = VolumeHeader::parse(&header_bytes)?;

    let plaintext = decrypt_metadata_region(&mut reader, &header)?;
    let context = EncryptionContext::extract(&plaintext)?;
    let lv = LogicalVolumeInfo::extract(&plaintext)?;
    let (_, size) = resolve_lv_extent(&plaintext, &header, &lv);
    Ok(build_info(&header, &context, &lv, size))
}

/// Read the plaintext metadata region, then read and decrypt the encrypted
/// metadata region, returning the decrypted metadata bytes.
fn decrypt_metadata_region<R: Read + Seek>(
    reader: &mut R,
    header: &VolumeHeader,
) -> Result<Vec<u8>, FileVaultError> {
    let (region_offset, _) = metadata::plaintext_metadata_region(header);

    // Read the first plaintext block to learn the region size.
    let block_size = header.block_size as usize;
    if block_size == 0 {
        return Err(FileVaultError::OutOfRange {
            what: "block size is zero",
        });
    }
    let mut first_block = vec![0u8; block_size];
    reader.seek(SeekFrom::Start(region_offset))?;
    read_exact_or_err(reader, &mut first_block)?;

    let region_size = metadata::plaintext_metadata_size(header, &first_block)?;
    let mut region = vec![0u8; region_size as usize];
    reader.seek(SeekFrom::Start(region_offset))?;
    read_exact_or_err(reader, &mut region)?;

    let location = metadata::locate_encrypted_metadata(header, &region)?;
    let mut ciphertext = vec![0u8; location.length as usize];
    reader.seek(SeekFrom::Start(location.primary_offset))?;
    read_exact_or_err(reader, &mut ciphertext)?;

    metadata::decrypt_metadata(header, &mut ciphertext);
    Ok(ciphertext)
}

/// Derive the LV physical base and size. Prefer the parsed `0x0305` segment
/// descriptor (a single contiguous segment); fall back to the plist LV size for
/// the size when the segment map is absent.
fn resolve_lv_extent(
    metadata_bytes: &[u8],
    header: &VolumeHeader,
    lv: &LogicalVolumeInfo,
) -> (u64, u64) {
    let block_size = u64::from(header.block_size);
    let segments = metadata::parse_segments(metadata_bytes, header.block_size as usize);
    if let Some(first) = segments.first() {
        let base = first.physical_block.saturating_mul(block_size);
        let size = if lv.size != 0 {
            lv.size
        } else {
            u64::from(first.number_of_blocks).saturating_mul(block_size)
        };
        (base, size)
    } else {
        (0, lv.size)
    }
}

/// Assemble the password-independent [`FileVaultInfo`].
fn build_info(
    header: &VolumeHeader,
    context: &EncryptionContext,
    lv: &LogicalVolumeInfo,
    size: u64,
) -> FileVaultInfo {
    FileVaultInfo {
        physical_volume_identifier: format_uuid(&header.physical_volume_identifier),
        pbkdf2_iterations: context.iterations,
        pbkdf2_salt: context.salt,
        family_uuid: lv.family_uuid.clone(),
        lv_identifier: lv.lv_identifier.clone(),
        lv_name: lv.name.clone(),
        lv_size: size,
        encryption_method: "AES-XTS-128",
        conversion_status: context.conversion_status.clone(),
        protectors: context.protectors.clone(),
    }
}

/// Read exactly `buf.len()` bytes, erroring loudly on a short read (a truncated
/// image is a bootstrap failure, never a silent empty result).
fn read_exact_or_err<R: Read>(reader: &mut R, buf: &mut [u8]) -> Result<(), FileVaultError> {
    reader.read_exact(buf).map_err(FileVaultError::Io)
}

/// Format 16 on-disk UUID bytes as the canonical `8-4-4-4-12` string.
fn format_uuid(bytes: &[u8; 16]) -> String {
    uuid::Uuid::from_bytes(*bytes).hyphenated().to_string()
}

/// Parse a UUID string to its 16 canonical bytes (as used for the tweak key).
fn parse_uuid_bytes(text: &str) -> Option<[u8; 16]> {
    uuid::Uuid::parse_str(text).ok().map(|u| *u.as_bytes())
}

#[cfg(test)]
mod tests {
    use super::test_support::{build_image, BLOCK, FAMILY, ITERS, KEY1, PASSWORD, PV_ID};
    use super::*;
    use std::io::Cursor;

    #[test]
    fn unlock_synthetic_volume_end_to_end() {
        let image = build_image();
        let mut vol = FileVaultVolume::unlock_with_password(Cursor::new(image), PASSWORD).unwrap();
        assert_eq!(vol.size(), 0x4000);
        assert_eq!(vol.info().pbkdf2_iterations, ITERS);
        assert_eq!(vol.info().lv_name.as_deref(), Some("SynthLV"));
        assert_eq!(vol.info().encryption_method, "AES-XTS-128");
        assert_eq!(vol.info().conversion_status.as_deref(), Some("Complete"));
        assert_eq!(vol.info().protectors.len(), 1);

        // Decrypt LV offset 0 -> known plaintext (0,1,2,...).
        let mut buf = [0u8; 512];
        assert_eq!(vol.read_at(0, &mut buf).unwrap(), 512);
        let expected: Vec<u8> = (0..512).map(|i| (i & 0xff) as u8).collect();
        assert_eq!(&buf[..], &expected[..]);

        // Read + Seek passthrough.
        assert_eq!(vol.seek(SeekFrom::Start(512)).unwrap(), 512);
        let mut b2 = [0u8; 16];
        assert!(std::io::Read::read(&mut vol, &mut b2).unwrap() > 0);

        // parse_info (no password) matches.
        let image2 = build_image();
        let info = parse_info(Cursor::new(image2)).unwrap();
        assert_eq!(info.family_uuid, vol.info().family_uuid);
        assert_eq!(info.lv_size, 0x4000);
        assert_eq!(
            info.physical_volume_identifier,
            uuid::Uuid::from_bytes(PV_ID).hyphenated().to_string()
        );

        // into_decrypted exposes the stream.
        let mut dec = vol.into_decrypted();
        assert_eq!(dec.size(), 0x4000);
        let mut b3 = [0u8; 16];
        assert_eq!(dec.read_at(0, &mut b3).unwrap(), 16);
    }

    #[test]
    fn unlock_wrong_password_fails() {
        let image = build_image();
        assert!(matches!(
            FileVaultVolume::unlock_with_password(Cursor::new(image), "nope"),
            Err(FileVaultError::KeyUnwrap { .. })
        ));
    }

    #[test]
    fn unlock_non_corestorage_fails() {
        let image = vec![0u8; 4096];
        assert!(matches!(
            FileVaultVolume::unlock_with_password(Cursor::new(image), PASSWORD),
            Err(FileVaultError::NotCoreStorage { .. })
        ));
    }

    #[test]
    fn truncated_image_errors_loudly() {
        // A header-only image: metadata read runs past EOF -> Io error, not empty.
        let mut image = vec![0u8; 600];
        image[88] = b'C';
        image[89] = b'S';
        image[96..100].copy_from_slice(&(BLOCK as u32).to_le_bytes());
        image[172..176].copy_from_slice(&2u32.to_le_bytes());
        image[104..112].copy_from_slice(&1u64.to_le_bytes());
        let err = parse_info(Cursor::new(image)).unwrap_err();
        assert!(matches!(err, FileVaultError::Io(_)));
    }

    #[test]
    fn zero_block_size_header_errors() {
        // block_size 0 in the header -> decrypt_metadata_region OutOfRange.
        let mut image = vec![0u8; 4096];
        image[88] = b'C';
        image[89] = b'S';
        image[96..100].copy_from_slice(&0u32.to_le_bytes());
        image[172..176].copy_from_slice(&2u32.to_le_bytes());
        let err = parse_info(Cursor::new(image)).unwrap_err();
        assert!(matches!(err, FileVaultError::OutOfRange { .. }));
    }

    #[test]
    fn format_and_parse_uuid_roundtrip() {
        let s = format_uuid(&FAMILY);
        assert_eq!(parse_uuid_bytes(&s), Some(FAMILY));
        assert_eq!(parse_uuid_bytes("not-a-uuid"), None);
    }

    #[test]
    fn resolve_extent_uses_segment_blocks_when_lv_size_zero() {
        // Segment present, but lv.size == 0 -> size derived from segment blocks.
        let header = VolumeHeader {
            block_size: BLOCK as u32,
            bytes_per_sector: 512,
            physical_volume_size: 0,
            metadata_block_numbers: [1, 0, 0, 0],
            key_data: KEY1,
            physical_volume_identifier: PV_ID,
        };
        // Metadata with a single 0x0305 segment (16 blocks) and no lv.size key.
        let mut meta = vec![0u8; BLOCK];
        meta[10..12].copy_from_slice(&0x0305u16.to_le_bytes());
        let payload = 64;
        meta[payload..payload + 4].copy_from_slice(&1u32.to_le_bytes());
        let entry = payload + 8;
        meta[entry + 16..entry + 20].copy_from_slice(&2u32.to_le_bytes());
        meta[entry + 32..entry + 40].copy_from_slice(&5u64.to_le_bytes());
        let lv = LogicalVolumeInfo {
            size: 0,
            family_uuid: "x".to_string(),
            lv_identifier: None,
            name: None,
        };
        let (base, size) = resolve_lv_extent(&meta, &header, &lv);
        assert_eq!(base, 5 * BLOCK as u64);
        assert_eq!(size, 2 * BLOCK as u64);
    }

    #[test]
    fn resolve_extent_no_segment_falls_back_to_lv_size() {
        let header = VolumeHeader {
            block_size: BLOCK as u32,
            bytes_per_sector: 512,
            physical_volume_size: 0,
            metadata_block_numbers: [1, 0, 0, 0],
            key_data: KEY1,
            physical_volume_identifier: PV_ID,
        };
        let meta = vec![0u8; BLOCK]; // no 0x0305 block
        let lv = LogicalVolumeInfo {
            size: 12345,
            family_uuid: "x".to_string(),
            lv_identifier: None,
            name: None,
        };
        let (base, size) = resolve_lv_extent(&meta, &header, &lv);
        assert_eq!(base, 0);
        assert_eq!(size, 12345);
    }
}