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