Skip to main content

ms_fve/
lib.rs

1//! **ms-fve** — BitLocker (`msFVE-RecoveryInformation`) primitives in pure Rust.
2//!
3//! # What ships in AD
4//!
5//! When a domain-joined machine has BitLocker enabled with the "back up
6//! recovery info to AD DS" policy, Windows creates a child object under the
7//! **computer** account:
8//!
9//! ```text
10//! CN=<datetime>{<guid>},CN=<COMPUTER>,OU=…,DC=corp,DC=local
11//!   objectClass: msFVE-RecoveryInformation
12//!   msFVE-RecoveryPassword: 123456-234567-345678-456789-567890-678901-789012-890123
13//!   msFVE-RecoveryGuid:     <16 raw bytes>
14//!   msFVE-VolumeGuid:       <16 raw bytes>
15//!   msFVE-KeyPackage:       <opaque BEK/FVEK export blob>
16//! ```
17//!
18//! Any principal with `RIGHT_DS_READ_PROPERTY` on that leaf can read the
19//! plaintext recovery password. Historically this defaulted to Domain Admins
20//! + Backup Operators, but delegation on the parent computer OU can silently
21//! grant it to help-desk groups — an under-audited privilege because the
22//! attribute isn't in the default LDAP filter set.
23//!
24//! # What this crate does
25//!
26//! * [`RecoveryPassword`] — parse a 48-digit / 55-char BitLocker recovery
27//!   password and validate its per-block divisibility checksum (each 6-digit
28//!   block must be divisible by 11; the mid-block value / 11 encodes the key
29//!   material). Rejects typos, OCR errors, and pasted-with-noise strings
30//!   without hitting a DC.
31//! * [`RecoveryInformation`] — a decoded `msFVE-RecoveryInformation` object
32//!   (`recovery_guid`, `volume_guid`, `password`, optional `key_package`).
33//! * [`ldap_filter_recovery_info_all`] / [`ldap_filter_recovery_info_for`] —
34//!   ready-to-use LDAP filters for enumeration and per-computer lookup.
35//! * [`is_bitlocker_leaf_dn`] — cheap DN-shape check for iterating a
36//!   subtree without an extra `objectClass` roundtrip.
37//!
38//! # What this crate does not do
39//!
40//! * No LDAP transport. Callers wire whatever LDAP client they already have
41//!   (`ldap3`, adhammer's raw LDAP, msldap-ext).
42//! * No key-package decryption. The `msFVE-KeyPackage` blob is a proprietary
43//!   BEK/FVEK export that the OS re-parses to unlock the volume; unlock is
44//!   done by the Windows FVE stack, not by AD tooling.
45//!
46//! # Example
47//!
48//! ```
49//! use ms_fve::RecoveryPassword;
50//! let pw = RecoveryPassword::parse("135795-258016-380237-502458-132000-122221-244442-366663")
51//!     .expect("well-formed recovery password");
52//! assert_eq!(pw.blocks().len(), 8);
53//! // Round-trip the canonical hyphenated form.
54//! assert_eq!(
55//!     pw.to_string(),
56//!     "135795-258016-380237-502458-132000-122221-244442-366663"
57//! );
58//! ```
59
60use core::fmt;
61
62/// A BitLocker recovery password — eight 6-digit blocks, hyphen-separated.
63///
64/// Each 6-digit block encodes a 16-bit key-material fragment via the
65/// invariant `block % 11 == 0` and `block / 11 <= 0xFFFF`. Validation
66/// enforces both, so a typo (`123456` instead of `123420`) is caught locally
67/// instead of at BitLocker unlock time.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct RecoveryPassword {
70    blocks: [u32; 8],
71}
72
73/// Errors returned by [`RecoveryPassword::parse`].
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum PasswordError {
76    /// Raw string is not the expected 55 chars (8 × 6-digit + 7 hyphens) or
77    /// contains non-digit / non-hyphen bytes at unexpected offsets.
78    Shape,
79    /// A block failed `block % 11 == 0` — either a typo or noise pasted in.
80    ChecksumBlock(usize),
81    /// A block passed the divisibility check but `block / 11` overflows the
82    /// 16-bit key-material window (very rare — indicates corruption).
83    OutOfRange(usize),
84}
85
86impl fmt::Display for PasswordError {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            PasswordError::Shape => {
90                f.write_str("recovery password must be eight 6-digit blocks separated by '-'")
91            }
92            PasswordError::ChecksumBlock(i) => write!(f, "block {i} fails BitLocker mod-11 check"),
93            PasswordError::OutOfRange(i) => write!(f, "block {i} / 11 exceeds 16-bit key window"),
94        }
95    }
96}
97
98impl std::error::Error for PasswordError {}
99
100impl RecoveryPassword {
101    /// Parse and validate a recovery password. Accepts the canonical
102    /// `NNNNNN-NNNNNN-…` form (55 chars, 8 blocks, 7 hyphens). No leading /
103    /// trailing whitespace tolerated — trim on the caller's side if needed.
104    pub fn parse(s: &str) -> Result<Self, PasswordError> {
105        let bytes = s.as_bytes();
106        if bytes.len() != 55 {
107            return Err(PasswordError::Shape);
108        }
109        let mut blocks = [0u32; 8];
110        for (i, block) in blocks.iter_mut().enumerate() {
111            let base = i * 7;
112            if i > 0 && bytes[base - 1] != b'-' {
113                return Err(PasswordError::Shape);
114            }
115            let mut v: u32 = 0;
116            for &b in &bytes[base..base + 6] {
117                if !b.is_ascii_digit() {
118                    return Err(PasswordError::Shape);
119                }
120                v = v * 10 + (b - b'0') as u32;
121            }
122            if v % 11 != 0 {
123                return Err(PasswordError::ChecksumBlock(i));
124            }
125            if v / 11 > 0xFFFF {
126                return Err(PasswordError::OutOfRange(i));
127            }
128            *block = v;
129        }
130        Ok(Self { blocks })
131    }
132
133    /// The eight validated blocks in order.
134    pub fn blocks(&self) -> [u32; 8] {
135        self.blocks
136    }
137
138    /// The 16-bit key-material fragments (`block / 11`) in order.
139    pub fn key_fragments(&self) -> [u16; 8] {
140        let mut out = [0u16; 8];
141        for i in 0..8 {
142            out[i] = (self.blocks[i] / 11) as u16;
143        }
144        out
145    }
146}
147
148impl fmt::Display for RecoveryPassword {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        for (i, b) in self.blocks.iter().enumerate() {
151            if i > 0 {
152                f.write_str("-")?;
153            }
154            write!(f, "{:06}", b)?;
155        }
156        Ok(())
157    }
158}
159
160/// A decoded `msFVE-RecoveryInformation` object. Field names match the
161/// attribute names on the AD leaf so bindings from `ldap3` / raw LDAP are
162/// mechanical.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct RecoveryInformation {
165    /// `msFVE-RecoveryGuid` — the recovery-key identifier the user types in
166    /// at the BitLocker recovery screen (first 8 chars). Raw 16-byte GUID
167    /// (Microsoft mixed-endian).
168    pub recovery_guid: [u8; 16],
169    /// `msFVE-VolumeGuid` — identifies the encrypted volume.
170    pub volume_guid: [u8; 16],
171    /// `msFVE-RecoveryPassword` — the 48-digit unlock key, validated.
172    pub password: RecoveryPassword,
173    /// `msFVE-KeyPackage` — opaque BEK/FVEK export blob; present when the
174    /// admin ticked "also back up key package" in the BitLocker policy.
175    /// Parsing this is out of scope (FVE-stack proprietary format).
176    pub key_package: Option<Vec<u8>>,
177}
178
179impl RecoveryInformation {
180    /// Assemble from raw attribute bytes. `recovery_guid` and `volume_guid`
181    /// must be exactly 16 bytes each; `password_str` is parsed and
182    /// validated; `key_package` is stored verbatim.
183    pub fn from_ldap_attrs(
184        recovery_guid: &[u8],
185        volume_guid: &[u8],
186        password_str: &str,
187        key_package: Option<Vec<u8>>,
188    ) -> Result<Self, ObjectError> {
189        let recovery_guid = guid_from_slice(recovery_guid).ok_or(ObjectError::RecoveryGuidLen)?;
190        let volume_guid = guid_from_slice(volume_guid).ok_or(ObjectError::VolumeGuidLen)?;
191        let password = RecoveryPassword::parse(password_str).map_err(ObjectError::Password)?;
192        Ok(Self {
193            recovery_guid,
194            volume_guid,
195            password,
196            key_package,
197        })
198    }
199
200    /// Present the recovery GUID in the standard "8-4-4-4-12" hex form (as
201    /// shown by Windows recovery screens).
202    pub fn recovery_guid_display(&self) -> String {
203        format_guid_mixed_endian(&self.recovery_guid)
204    }
205}
206
207/// Errors returned by [`RecoveryInformation::from_ldap_attrs`].
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub enum ObjectError {
210    RecoveryGuidLen,
211    VolumeGuidLen,
212    Password(PasswordError),
213}
214
215impl fmt::Display for ObjectError {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            ObjectError::RecoveryGuidLen => {
219                f.write_str("msFVE-RecoveryGuid must be exactly 16 bytes")
220            }
221            ObjectError::VolumeGuidLen => f.write_str("msFVE-VolumeGuid must be exactly 16 bytes"),
222            ObjectError::Password(e) => write!(f, "msFVE-RecoveryPassword: {e}"),
223        }
224    }
225}
226
227impl std::error::Error for ObjectError {}
228
229fn guid_from_slice(s: &[u8]) -> Option<[u8; 16]> {
230    if s.len() != 16 {
231        return None;
232    }
233    let mut out = [0u8; 16];
234    out.copy_from_slice(s);
235    Some(out)
236}
237
238/// GUIDs on the wire are stored little-endian in the first three fields and
239/// big-endian in the last two — matches how Microsoft prints them and how
240/// BitLocker recovery screens show the identifier.
241fn format_guid_mixed_endian(g: &[u8; 16]) -> String {
242    format!(
243        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
244        g[3], g[2], g[1], g[0],
245        g[5], g[4],
246        g[7], g[6],
247        g[8], g[9],
248        g[10], g[11], g[12], g[13], g[14], g[15],
249    )
250}
251
252/// LDAP filter matching every BitLocker recovery leaf across the directory.
253/// Pair with a subtree search under `DC=corp,DC=local` to enumerate.
254pub fn ldap_filter_recovery_info_all() -> &'static str {
255    "(objectClass=msFVE-RecoveryInformation)"
256}
257
258/// LDAP filter matching every recovery leaf for a specific computer, given
259/// its DN. Use with a one-level search under `computer_dn`.
260pub fn ldap_filter_recovery_info_for(_computer_dn: &str) -> &'static str {
261    // Subtree/one-level base is set by the caller; the filter stays the same.
262    "(objectClass=msFVE-RecoveryInformation)"
263}
264
265/// Cheap shape check: does `dn` look like a `msFVE-RecoveryInformation`
266/// leaf? Windows names these `CN=<UTC-datetime>{<guid>},...`. Useful when
267/// iterating a subtree without an extra per-object `objectClass` fetch.
268pub fn is_bitlocker_leaf_dn(dn: &str) -> bool {
269    let rdn = match dn.split(',').next() {
270        Some(r) => r.trim(),
271        None => return false,
272    };
273    let value = match rdn.strip_prefix("CN=").or_else(|| rdn.strip_prefix("cn=")) {
274        Some(v) => v,
275        None => return false,
276    };
277    // The leaf RDN carries a `{GUID}` suffix that we can key on. Anything
278    // less than the 38-char `{8-4-4-4-12}` doesn't qualify.
279    if !value.ends_with('}') || value.len() < 38 {
280        return false;
281    }
282    match value.rfind('{') {
283        Some(i) => value[i + 1..value.len() - 1].len() == 36,
284        None => false,
285    }
286}
287
288/// Attribute names commonly requested when enumerating BitLocker leaves.
289/// Passing this to the LDAP search's `attrs` parameter yields exactly what
290/// [`RecoveryInformation::from_ldap_attrs`] needs.
291pub const RECOVERY_INFO_ATTRS: &[&str] = &[
292    "msFVE-RecoveryGuid",
293    "msFVE-VolumeGuid",
294    "msFVE-RecoveryPassword",
295    "msFVE-KeyPackage",
296];
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn password_display_roundtrips() {
304        let s = "135795-258016-380237-502458-132000-122221-244442-366663";
305        let pw = RecoveryPassword::parse(s).unwrap();
306        assert_eq!(pw.to_string(), s);
307    }
308
309    #[test]
310    fn password_key_fragments_are_16bit() {
311        let s = "135795-258016-380237-502458-132000-122221-244442-366663";
312        let pw = RecoveryPassword::parse(s).unwrap();
313        for k in pw.key_fragments() {
314            let _: u16 = k;
315        }
316    }
317
318    #[test]
319    fn password_rejects_mod11_typo() {
320        let bad = "123456-258016-380237-502458-132000-122221-244442-366663";
321        match RecoveryPassword::parse(bad) {
322            Err(PasswordError::ChecksumBlock(0)) => {}
323            other => panic!("want ChecksumBlock(0), got {other:?}"),
324        }
325    }
326
327    #[test]
328    fn password_rejects_shape() {
329        assert_eq!(
330            RecoveryPassword::parse("too-short"),
331            Err(PasswordError::Shape)
332        );
333        assert_eq!(
334            RecoveryPassword::parse("12579Z-258016-380237-502458-132000-122221-244442-366663"),
335            Err(PasswordError::Shape)
336        );
337        assert_eq!(
338            RecoveryPassword::parse("135795X258016-380237-502458-132000-122221-244442-366663"),
339            Err(PasswordError::Shape)
340        );
341    }
342
343    #[test]
344    fn object_from_ldap_attrs() {
345        let rec_guid = [0x11u8; 16];
346        let vol_guid = [0x22u8; 16];
347        let obj = RecoveryInformation::from_ldap_attrs(
348            &rec_guid,
349            &vol_guid,
350            "135795-258016-380237-502458-132000-122221-244442-366663",
351            Some(vec![0xAA, 0xBB]),
352        )
353        .unwrap();
354        assert_eq!(obj.recovery_guid, rec_guid);
355        assert_eq!(obj.volume_guid, vol_guid);
356        assert_eq!(obj.key_package.as_deref(), Some(&[0xAA, 0xBB][..]));
357    }
358
359    #[test]
360    fn object_rejects_short_guid() {
361        let err = RecoveryInformation::from_ldap_attrs(
362            &[0x11u8; 15],
363            &[0x22u8; 16],
364            "135795-258016-380237-502458-132000-122221-244442-366663",
365            None,
366        )
367        .unwrap_err();
368        assert_eq!(err, ObjectError::RecoveryGuidLen);
369    }
370
371    #[test]
372    fn guid_display_is_mixed_endian() {
373        let g = [
374            0xa1, 0xb2, 0xc3, 0xd4, // Data1 LE
375            0xe5, 0xf6, // Data2 LE
376            0x07, 0x18, // Data3 LE
377            0x29, 0x3a, // Data4 first 2 (BE-printed)
378            0x4b, 0x5c, 0x6d, 0x7e, 0x8f, 0x90, // Data4 last 6 (BE-printed)
379        ];
380        assert_eq!(
381            format_guid_mixed_endian(&g),
382            "d4c3b2a1-f6e5-1807-293a-4b5c6d7e8f90"
383        );
384    }
385
386    #[test]
387    fn dn_shape_detector() {
388        assert!(is_bitlocker_leaf_dn(
389            "CN=2025-05-15T09:12:34Z{12345678-1234-1234-1234-1234567890ab},CN=WKS01,OU=Workstations,DC=corp,DC=local"
390        ));
391        assert!(!is_bitlocker_leaf_dn(
392            "CN=WKS01,OU=Workstations,DC=corp,DC=local"
393        ));
394        assert!(!is_bitlocker_leaf_dn("OU=Workstations,DC=corp,DC=local"));
395        assert!(!is_bitlocker_leaf_dn(""));
396    }
397
398    #[test]
399    fn ldap_filter_shape() {
400        assert!(ldap_filter_recovery_info_all().starts_with("(objectClass="));
401        assert!(
402            ldap_filter_recovery_info_for("CN=WKS01,DC=corp,DC=local").starts_with("(objectClass=")
403        );
404    }
405}