Skip to main content

dpapi_ng/
lib.rs

1//! DPAPI-NG (CNG "group protection"), in pure Rust.
2//!
3//! Windows LAPS (`msLAPS-EncryptedPassword`), gMSA and dMSA managed passwords are all
4//! protected the same way: a CMS `EnvelopedData` whose content key is wrapped under a KEK
5//! derived from a **KDS root key** held by the domain controllers. The blob itself carries no
6//! key — only a [`gkdi::KeyIdentifier`] saying *which* root key and *which* node of its
7//! L0/L1/L2 tree. A principal allowed to read the secret asks a DC for that node
8//! (`GetKey` over MS-GKDI), then derives downwards.
9//!
10//! **0.2 wiring.** The MS-GKDI structures, KDF, tree walk and `ISDKey::GetKey` RPC now live
11//! in the [`ms-gkdi`](https://crates.io/crates/ms-gkdi) crate. The [`gkdi`], [`kdf`] and
12//! [`rpc`] modules in this crate are thin `pub use` shims marked `#[deprecated]`. New code
13//! should depend on `ms-gkdi` directly; existing 0.1.x code keeps compiling unchanged
14//! (`ms_gkdi::GkdiError` converts into [`DpapiError`] via `From`).
15//!
16//! The full pipeline:
17//!
18//! 1. [`LapsBlob::parse`] / [`cms::ProtectedBlob::parse`] — unwrap the CMS, recover the key
19//!    identifier.
20//! 2. Fetch the envelope from a DC: either [`ms_gkdi::rpc::get_key`] (feature `rpc`) or hand
21//!    the reply bytes to [`ms_gkdi::gkdi::GroupKeyEnvelope::parse`] yourself.
22//! 3. [`ms_gkdi::gkdi::compute_l2_key`] — walk the tree down to the exact node. Pure
23//!    computation.
24//! 4. [`cms::ProtectedBlob`] + [`decrypt_with_seed_key`] — unwrap the content key and open
25//!    the AES-GCM content.
26
27pub mod cms;
28pub mod der;
29pub mod gkdi;
30pub mod kdf;
31
32/// MS-GKDI `GetKey` RPC re-export — see [`ms_gkdi::rpc`]. Kept behind the `rpc` feature so
33/// 0.1.x callers who wrote `use dpapi_ng::rpc::get_key;` still compile.
34#[cfg(feature = "rpc")]
35pub mod rpc;
36
37use aes_gcm::aead::Aead;
38use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
39use aes_kw::KekAes256;
40
41use cms::ProtectedBlob;
42use ms_gkdi::gkdi::{self as gkdi_impl, GroupKeyEnvelope};
43use ms_gkdi::kdf::{kdf, kds_service_label};
44
45#[derive(Debug, thiserror::Error, PartialEq, Eq)]
46pub enum DpapiError {
47    #[error("truncated: {0}")]
48    Truncated(&'static str),
49    #[error("bad {what} magic: {got:#010x}")]
50    BadMagic { what: &'static str, got: u32 },
51    #[error("malformed DER: {0}")]
52    Der(&'static str),
53    #[error("DER {what}: expected tag {expected:#04x}, got {got:#04x}")]
54    DerTag {
55        what: &'static str,
56        expected: u8,
57        got: u8,
58    },
59    #[error("not a CMS EnvelopedData (contentType {0})")]
60    NotEnvelopedData(String),
61    #[error("no MS-GKDI key identifier in the KEK recipient info")]
62    NoKeyIdentifier,
63    #[error("unsupported algorithm: {0}")]
64    UnsupportedAlgorithm(String),
65    #[error("the envelope carries a public key, not seed keys — ask the DC for the private half")]
66    PublicKeyEnvelope,
67    #[error("the envelope has no {0} seed key")]
68    MissingSeedKey(&'static str),
69    #[error("tree index out of range: l1={l1} l2={l2}")]
70    BadTreeIndex { l1: i32, l2: i32 },
71    #[error("the envelope is for root key {envelope}, the blob wants {blob}")]
72    RootKeyMismatch { envelope: String, blob: String },
73    #[error("the envelope is at L0 {envelope}, the blob wants {blob} — ask the DC for that L0")]
74    L0Mismatch { envelope: i32, blob: i32 },
75    #[error("key unwrap failed — wrong KEK")]
76    KeyUnwrap,
77    #[error("content decryption failed — wrong content key or corrupt blob")]
78    Decrypt,
79    #[error("msLAPS-EncryptedPassword blob is too short")]
80    ShortLapsBlob,
81}
82
83pub type Result<T> = std::result::Result<T, DpapiError>;
84
85/// Lift a `ms-gkdi` error into `DpapiError` so `?` at the call site keeps working after the
86/// wiring. Variants match 1:1 with the ms-gkdi enum.
87impl From<ms_gkdi::GkdiError> for DpapiError {
88    fn from(e: ms_gkdi::GkdiError) -> Self {
89        match e {
90            ms_gkdi::GkdiError::Truncated(w) => DpapiError::Truncated(w),
91            ms_gkdi::GkdiError::BadMagic { what, got } => DpapiError::BadMagic { what, got },
92            ms_gkdi::GkdiError::UnsupportedAlgorithm(a) => DpapiError::UnsupportedAlgorithm(a),
93            ms_gkdi::GkdiError::PublicKeyEnvelope => DpapiError::PublicKeyEnvelope,
94            ms_gkdi::GkdiError::MissingSeedKey(w) => DpapiError::MissingSeedKey(w),
95            ms_gkdi::GkdiError::BadTreeIndex { l1, l2 } => DpapiError::BadTreeIndex { l1, l2 },
96        }
97    }
98}
99
100/// The header Windows LAPS puts in front of the DPAPI-NG blob in
101/// `msLAPS-EncryptedPassword`: an update timestamp and the blob length.
102#[derive(Clone, Debug)]
103pub struct LapsBlob {
104    /// FILETIME of the last password update.
105    pub update_timestamp: u64,
106    /// The DPAPI-NG blob itself.
107    pub blob: Vec<u8>,
108}
109
110impl LapsBlob {
111    /// Split an `msLAPS-EncryptedPassword` attribute value into its header and blob.
112    pub fn parse(b: &[u8]) -> Result<LapsBlob> {
113        if b.len() < 16 {
114            return Err(DpapiError::ShortLapsBlob);
115        }
116        // upper timestamp u32, lower timestamp u32, blob length u32, flags u32.
117        let upper = u32::from_le_bytes(b[0..4].try_into().unwrap()) as u64;
118        let lower = u32::from_le_bytes(b[4..8].try_into().unwrap()) as u64;
119        let len = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
120        let rest = &b[16..];
121        let blob = rest
122            .get(..len.min(rest.len()))
123            .ok_or(DpapiError::ShortLapsBlob)?;
124        Ok(LapsBlob {
125            update_timestamp: (upper << 32) | lower,
126            blob: blob.to_vec(),
127        })
128    }
129
130    /// Parse the contained DPAPI-NG blob.
131    pub fn protected(&self) -> Result<ProtectedBlob> {
132        ProtectedBlob::parse(&self.blob)
133    }
134}
135
136/// Windows LAPS stores the decrypted password as UTF-16LE JSON:
137/// `{"n":"<account>","t":"<hex time>","p":"<password>"}`. Pull the password out without
138/// pulling in a JSON dependency.
139pub fn laps_password_from_json(utf16le: &[u8]) -> Option<String> {
140    let json = utf16le_lossy(utf16le);
141    let at = json.find("\"p\"")?;
142    let rest = &json[at + 3..];
143    let start = rest.find('"')? + 1;
144    let tail = &rest[start..];
145    let end = tail.find('"')?;
146    Some(tail[..end].to_string())
147}
148
149/// Best-effort UTF-16LE → String decode, trimming trailing NULs. Kept local so the crate
150/// doesn't lean on a `pub(crate)` helper in `ms-gkdi`.
151fn utf16le_lossy(b: &[u8]) -> String {
152    let units: Vec<u16> = b
153        .chunks_exact(2)
154        .map(|c| u16::from_le_bytes([c[0], c[1]]))
155        .collect();
156    let trimmed = match units.iter().rposition(|&u| u != 0) {
157        Some(i) => &units[..=i],
158        None => &[][..],
159    };
160    String::from_utf16_lossy(trimmed)
161}
162
163/// Decrypt a blob given the L2 seed key for its node.
164///
165/// The content-encryption key is AES-wrapped under a KEK derived from the seed key. Windows
166/// has used more than one derivation here across versions, so each candidate is tried in
167/// turn — this is safe rather than sloppy: AES key-wrap and AES-GCM are both authenticated,
168/// so a wrong KEK fails loudly instead of yielding plausible garbage.
169pub fn decrypt_with_seed_key(blob: &ProtectedBlob, l2_key: &[u8]) -> Result<Vec<u8>> {
170    let hash = blob.key_identifier.hash()?;
171    let ctx = gkdi_impl::kdf_context(
172        blob.key_identifier.root_key_id,
173        blob.key_identifier.l0,
174        blob.key_identifier.l1,
175        blob.key_identifier.l2,
176    );
177    let label = kds_service_label();
178
179    let mut candidates: Vec<Vec<u8>> = Vec::new();
180    if l2_key.len() >= 32 {
181        candidates.push(l2_key[..32].to_vec());
182    }
183    candidates.push(kdf(hash, l2_key, &label, &ctx, 32));
184    candidates.push(kdf(hash, l2_key, &label, &[], 32));
185
186    let mut last = DpapiError::KeyUnwrap;
187    for kek in candidates {
188        match decrypt_with_kek(blob, &kek) {
189            Ok(v) => return Ok(v),
190            Err(e) => last = e,
191        }
192    }
193    Err(last)
194}
195
196/// Decrypt a blob with a known key-encryption key: AES key-unwrap the content key, then open
197/// the AES-256-GCM content.
198pub fn decrypt_with_kek(blob: &ProtectedBlob, kek: &[u8]) -> Result<Vec<u8>> {
199    let kek: [u8; 32] = kek.try_into().map_err(|_| DpapiError::KeyUnwrap)?;
200    let unwrapper = KekAes256::from(kek);
201    let mut cek = vec![0u8; blob.encrypted_key.len().saturating_sub(8)];
202    unwrapper
203        .unwrap(&blob.encrypted_key, &mut cek)
204        .map_err(|_| DpapiError::KeyUnwrap)?;
205    decrypt_content(blob, &cek)
206}
207
208/// Open the AES-256-GCM content with an already-unwrapped content-encryption key.
209pub fn decrypt_content(blob: &ProtectedBlob, cek: &[u8]) -> Result<Vec<u8>> {
210    let cipher = Aes256Gcm::new_from_slice(cek).map_err(|_| DpapiError::Decrypt)?;
211    let nonce = Nonce::from_slice(&blob.nonce);
212    cipher
213        .decrypt(nonce, blob.encrypted_content.as_ref())
214        .map_err(|_| DpapiError::Decrypt)
215}
216
217/// The whole path in one call: a blob plus the `GetKey` envelope that covers it.
218///
219/// Fails early if the envelope is for a different root key or a different L0 — those are not
220/// derivable, and the caller has to go back to the DC with the right request.
221pub fn decrypt(blob: &ProtectedBlob, envelope: &GroupKeyEnvelope) -> Result<Vec<u8>> {
222    let id = &blob.key_identifier;
223    if envelope.root_key_id != id.root_key_id {
224        return Err(DpapiError::RootKeyMismatch {
225            envelope: envelope.root_key_id.to_string(),
226            blob: id.root_key_id.to_string(),
227        });
228    }
229    if envelope.l0 != id.l0 {
230        return Err(DpapiError::L0Mismatch {
231            envelope: envelope.l0,
232            blob: id.l0,
233        });
234    }
235    let l2_key = gkdi_impl::compute_l2_key(envelope, id.l1, id.l2)?;
236    decrypt_with_seed_key(blob, &l2_key)
237}