Skip to main content

dpapi_ng/
lib.rs

1//! DPAPI-NG (CNG "group protection") and MS-GKDI, 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//! The full pipeline:
11//!
12//! 1. [`LapsBlob::parse`] / [`cms::ProtectedBlob::parse`] — unwrap the CMS, recover the key
13//!    identifier.
14//! 2. Fetch the envelope from a DC: either [`rpc::get_key`] (feature `rpc`) or hand the
15//!    reply bytes to [`gkdi::GroupKeyEnvelope::parse`] yourself.
16//! 3. [`gkdi::compute_l2_key`] — walk the tree down to the exact node. Pure computation.
17//! 4. [`cms::ProtectedBlob`] + [`decrypt_with_seed_key`] — unwrap the content key and open
18//!    the AES-GCM content.
19//!
20//! Without the `rpc` feature the crate is pure computation (no dcerpc/tokio dep): bring your
21//! own transport and feed the `GetKey` reply bytes to `GroupKeyEnvelope::parse`.
22
23pub mod cms;
24mod cursor;
25pub mod der;
26pub mod gkdi;
27pub mod kdf;
28
29/// MS-GKDI `GetKey` RPC client — sealed ncacn_ip_tcp against a DC's ISDKey interface.
30/// Enable with `cargo … --features rpc`.
31#[cfg(feature = "rpc")]
32pub mod rpc;
33
34use aes_gcm::aead::Aead;
35use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
36use aes_kw::KekAes256;
37
38use cms::ProtectedBlob;
39use gkdi::GroupKeyEnvelope;
40use kdf::{kdf, kds_service_label};
41
42#[derive(Debug, thiserror::Error, PartialEq, Eq)]
43pub enum DpapiError {
44    #[error("truncated: {0}")]
45    Truncated(&'static str),
46    #[error("bad {what} magic: {got:#010x}")]
47    BadMagic { what: &'static str, got: u32 },
48    #[error("malformed DER: {0}")]
49    Der(&'static str),
50    #[error("DER {what}: expected tag {expected:#04x}, got {got:#04x}")]
51    DerTag {
52        what: &'static str,
53        expected: u8,
54        got: u8,
55    },
56    #[error("not a CMS EnvelopedData (contentType {0})")]
57    NotEnvelopedData(String),
58    #[error("no MS-GKDI key identifier in the KEK recipient info")]
59    NoKeyIdentifier,
60    #[error("unsupported algorithm: {0}")]
61    UnsupportedAlgorithm(String),
62    #[error("the envelope carries a public key, not seed keys — ask the DC for the private half")]
63    PublicKeyEnvelope,
64    #[error("the envelope has no {0} seed key")]
65    MissingSeedKey(&'static str),
66    #[error("tree index out of range: l1={l1} l2={l2}")]
67    BadTreeIndex { l1: i32, l2: i32 },
68    #[error("the envelope is for root key {envelope}, the blob wants {blob}")]
69    RootKeyMismatch { envelope: String, blob: String },
70    #[error("the envelope is at L0 {envelope}, the blob wants {blob} — ask the DC for that L0")]
71    L0Mismatch { envelope: i32, blob: i32 },
72    #[error("key unwrap failed — wrong KEK")]
73    KeyUnwrap,
74    #[error("content decryption failed — wrong content key or corrupt blob")]
75    Decrypt,
76    #[error("msLAPS-EncryptedPassword blob is too short")]
77    ShortLapsBlob,
78}
79
80pub type Result<T> = std::result::Result<T, DpapiError>;
81
82/// The header Windows LAPS puts in front of the DPAPI-NG blob in
83/// `msLAPS-EncryptedPassword`: an update timestamp and the blob length.
84#[derive(Clone, Debug)]
85pub struct LapsBlob {
86    /// FILETIME of the last password update.
87    pub update_timestamp: u64,
88    /// The DPAPI-NG blob itself.
89    pub blob: Vec<u8>,
90}
91
92impl LapsBlob {
93    /// Split an `msLAPS-EncryptedPassword` attribute value into its header and blob.
94    pub fn parse(b: &[u8]) -> Result<LapsBlob> {
95        if b.len() < 16 {
96            return Err(DpapiError::ShortLapsBlob);
97        }
98        // upper timestamp u32, lower timestamp u32, blob length u32, flags u32.
99        let upper = u32::from_le_bytes(b[0..4].try_into().unwrap()) as u64;
100        let lower = u32::from_le_bytes(b[4..8].try_into().unwrap()) as u64;
101        let len = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
102        let rest = &b[16..];
103        let blob = rest
104            .get(..len.min(rest.len()))
105            .ok_or(DpapiError::ShortLapsBlob)?;
106        Ok(LapsBlob {
107            update_timestamp: (upper << 32) | lower,
108            blob: blob.to_vec(),
109        })
110    }
111
112    /// Parse the contained DPAPI-NG blob.
113    pub fn protected(&self) -> Result<ProtectedBlob> {
114        ProtectedBlob::parse(&self.blob)
115    }
116}
117
118/// Windows LAPS stores the decrypted password as UTF-16LE JSON:
119/// `{"n":"<account>","t":"<hex time>","p":"<password>"}`. Pull the password out without
120/// pulling in a JSON dependency.
121pub fn laps_password_from_json(utf16le: &[u8]) -> Option<String> {
122    let json = gkdi::utf16_lossy(utf16le);
123    let at = json.find("\"p\"")?;
124    let rest = &json[at + 3..];
125    let start = rest.find('"')? + 1;
126    let tail = &rest[start..];
127    let end = tail.find('"')?;
128    Some(tail[..end].to_string())
129}
130
131/// Decrypt a blob given the L2 seed key for its node.
132///
133/// The content-encryption key is AES-wrapped under a KEK derived from the seed key. Windows
134/// has used more than one derivation here across versions, so each candidate is tried in
135/// turn — this is safe rather than sloppy: AES key-wrap and AES-GCM are both authenticated,
136/// so a wrong KEK fails loudly instead of yielding plausible garbage.
137pub fn decrypt_with_seed_key(blob: &ProtectedBlob, l2_key: &[u8]) -> Result<Vec<u8>> {
138    let hash = blob.key_identifier.hash()?;
139    let ctx = gkdi::kdf_context(
140        blob.key_identifier.root_key_id,
141        blob.key_identifier.l0,
142        blob.key_identifier.l1,
143        blob.key_identifier.l2,
144    );
145    let label = kds_service_label();
146
147    let mut candidates: Vec<Vec<u8>> = Vec::new();
148    if l2_key.len() >= 32 {
149        candidates.push(l2_key[..32].to_vec());
150    }
151    candidates.push(kdf(hash, l2_key, &label, &ctx, 32));
152    candidates.push(kdf(hash, l2_key, &label, &[], 32));
153
154    let mut last = DpapiError::KeyUnwrap;
155    for kek in candidates {
156        match decrypt_with_kek(blob, &kek) {
157            Ok(v) => return Ok(v),
158            Err(e) => last = e,
159        }
160    }
161    Err(last)
162}
163
164/// Decrypt a blob with a known key-encryption key: AES key-unwrap the content key, then open
165/// the AES-256-GCM content.
166pub fn decrypt_with_kek(blob: &ProtectedBlob, kek: &[u8]) -> Result<Vec<u8>> {
167    let kek: [u8; 32] = kek.try_into().map_err(|_| DpapiError::KeyUnwrap)?;
168    let unwrapper = KekAes256::from(kek);
169    let mut cek = vec![0u8; blob.encrypted_key.len().saturating_sub(8)];
170    unwrapper
171        .unwrap(&blob.encrypted_key, &mut cek)
172        .map_err(|_| DpapiError::KeyUnwrap)?;
173    decrypt_content(blob, &cek)
174}
175
176/// Open the AES-256-GCM content with an already-unwrapped content-encryption key.
177pub fn decrypt_content(blob: &ProtectedBlob, cek: &[u8]) -> Result<Vec<u8>> {
178    let cipher = Aes256Gcm::new_from_slice(cek).map_err(|_| DpapiError::Decrypt)?;
179    let nonce = Nonce::from_slice(&blob.nonce);
180    cipher
181        .decrypt(nonce, blob.encrypted_content.as_ref())
182        .map_err(|_| DpapiError::Decrypt)
183}
184
185/// The whole path in one call: a blob plus the `GetKey` envelope that covers it.
186///
187/// Fails early if the envelope is for a different root key or a different L0 — those are not
188/// derivable, and the caller has to go back to the DC with the right request.
189pub fn decrypt(blob: &ProtectedBlob, envelope: &GroupKeyEnvelope) -> Result<Vec<u8>> {
190    let id = &blob.key_identifier;
191    if envelope.root_key_id != id.root_key_id {
192        return Err(DpapiError::RootKeyMismatch {
193            envelope: envelope.root_key_id.to_string(),
194            blob: id.root_key_id.to_string(),
195        });
196    }
197    if envelope.l0 != id.l0 {
198        return Err(DpapiError::L0Mismatch {
199            envelope: envelope.l0,
200            blob: id.l0,
201        });
202    }
203    let l2_key = gkdi::compute_l2_key(envelope, id.l1, id.l2)?;
204    decrypt_with_seed_key(blob, &l2_key)
205}