dpapi-ng 0.1.0

Pure-Rust DPAPI-NG (CNG group protection) and MS-GKDI key derivation — decrypt Windows LAPS, gMSA and dMSA password blobs without a Windows host.
Documentation
//! DPAPI-NG (CNG "group protection") and MS-GKDI, in pure Rust.
//!
//! Windows LAPS (`msLAPS-EncryptedPassword`), gMSA and dMSA managed passwords are all
//! protected the same way: a CMS `EnvelopedData` whose content key is wrapped under a KEK
//! derived from a **KDS root key** held by the domain controllers. The blob itself carries no
//! key — only a [`gkdi::KeyIdentifier`] saying *which* root key and *which* node of its
//! L0/L1/L2 tree. A principal allowed to read the secret asks a DC for that node
//! (`GetKey` over MS-GKDI), then derives downwards.
//!
//! This crate does everything except the RPC call:
//!
//! 1. [`LapsBlob::parse`] / [`cms::ProtectedBlob::parse`] — unwrap the CMS, recover the key
//!    identifier.
//! 2. [`gkdi::GroupKeyEnvelope::parse`] — decode what `GetKey` returned.
//! 3. [`gkdi::compute_l2_key`] — walk the tree down to the exact node. Pure computation.
//! 4. [`cms::ProtectedBlob`] + [`decrypt_with_seed_key`] — unwrap the content key and open
//!    the AES-GCM content.
//!
//! Transport is deliberately out of scope: bring your own DCE/RPC and hand the bytes here.

pub mod cms;
mod cursor;
pub mod der;
pub mod gkdi;
pub mod kdf;

use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use aes_kw::KekAes256;

use cms::ProtectedBlob;
use gkdi::GroupKeyEnvelope;
use kdf::{kdf, kds_service_label};

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DpapiError {
    #[error("truncated: {0}")]
    Truncated(&'static str),
    #[error("bad {what} magic: {got:#010x}")]
    BadMagic { what: &'static str, got: u32 },
    #[error("malformed DER: {0}")]
    Der(&'static str),
    #[error("DER {what}: expected tag {expected:#04x}, got {got:#04x}")]
    DerTag {
        what: &'static str,
        expected: u8,
        got: u8,
    },
    #[error("not a CMS EnvelopedData (contentType {0})")]
    NotEnvelopedData(String),
    #[error("no MS-GKDI key identifier in the KEK recipient info")]
    NoKeyIdentifier,
    #[error("unsupported algorithm: {0}")]
    UnsupportedAlgorithm(String),
    #[error("the envelope carries a public key, not seed keys — ask the DC for the private half")]
    PublicKeyEnvelope,
    #[error("the envelope has no {0} seed key")]
    MissingSeedKey(&'static str),
    #[error("tree index out of range: l1={l1} l2={l2}")]
    BadTreeIndex { l1: i32, l2: i32 },
    #[error("the envelope is for root key {envelope}, the blob wants {blob}")]
    RootKeyMismatch { envelope: String, blob: String },
    #[error("the envelope is at L0 {envelope}, the blob wants {blob} — ask the DC for that L0")]
    L0Mismatch { envelope: i32, blob: i32 },
    #[error("key unwrap failed — wrong KEK")]
    KeyUnwrap,
    #[error("content decryption failed — wrong content key or corrupt blob")]
    Decrypt,
    #[error("msLAPS-EncryptedPassword blob is too short")]
    ShortLapsBlob,
}

pub type Result<T> = std::result::Result<T, DpapiError>;

/// The header Windows LAPS puts in front of the DPAPI-NG blob in
/// `msLAPS-EncryptedPassword`: an update timestamp and the blob length.
#[derive(Clone, Debug)]
pub struct LapsBlob {
    /// FILETIME of the last password update.
    pub update_timestamp: u64,
    /// The DPAPI-NG blob itself.
    pub blob: Vec<u8>,
}

impl LapsBlob {
    /// Split an `msLAPS-EncryptedPassword` attribute value into its header and blob.
    pub fn parse(b: &[u8]) -> Result<LapsBlob> {
        if b.len() < 16 {
            return Err(DpapiError::ShortLapsBlob);
        }
        // upper timestamp u32, lower timestamp u32, blob length u32, flags u32.
        let upper = u32::from_le_bytes(b[0..4].try_into().unwrap()) as u64;
        let lower = u32::from_le_bytes(b[4..8].try_into().unwrap()) as u64;
        let len = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
        let rest = &b[16..];
        let blob = rest
            .get(..len.min(rest.len()))
            .ok_or(DpapiError::ShortLapsBlob)?;
        Ok(LapsBlob {
            update_timestamp: (upper << 32) | lower,
            blob: blob.to_vec(),
        })
    }

    /// Parse the contained DPAPI-NG blob.
    pub fn protected(&self) -> Result<ProtectedBlob> {
        ProtectedBlob::parse(&self.blob)
    }
}

/// Windows LAPS stores the decrypted password as UTF-16LE JSON:
/// `{"n":"<account>","t":"<hex time>","p":"<password>"}`. Pull the password out without
/// pulling in a JSON dependency.
pub fn laps_password_from_json(utf16le: &[u8]) -> Option<String> {
    let json = gkdi::utf16_lossy(utf16le);
    let at = json.find("\"p\"")?;
    let rest = &json[at + 3..];
    let start = rest.find('"')? + 1;
    let tail = &rest[start..];
    let end = tail.find('"')?;
    Some(tail[..end].to_string())
}

/// Decrypt a blob given the L2 seed key for its node.
///
/// The content-encryption key is AES-wrapped under a KEK derived from the seed key. Windows
/// has used more than one derivation here across versions, so each candidate is tried in
/// turn — this is safe rather than sloppy: AES key-wrap and AES-GCM are both authenticated,
/// so a wrong KEK fails loudly instead of yielding plausible garbage.
pub fn decrypt_with_seed_key(blob: &ProtectedBlob, l2_key: &[u8]) -> Result<Vec<u8>> {
    let hash = blob.key_identifier.hash()?;
    let ctx = gkdi::kdf_context(
        blob.key_identifier.root_key_id,
        blob.key_identifier.l0,
        blob.key_identifier.l1,
        blob.key_identifier.l2,
    );
    let label = kds_service_label();

    let mut candidates: Vec<Vec<u8>> = Vec::new();
    if l2_key.len() >= 32 {
        candidates.push(l2_key[..32].to_vec());
    }
    candidates.push(kdf(hash, l2_key, &label, &ctx, 32));
    candidates.push(kdf(hash, l2_key, &label, &[], 32));

    let mut last = DpapiError::KeyUnwrap;
    for kek in candidates {
        match decrypt_with_kek(blob, &kek) {
            Ok(v) => return Ok(v),
            Err(e) => last = e,
        }
    }
    Err(last)
}

/// Decrypt a blob with a known key-encryption key: AES key-unwrap the content key, then open
/// the AES-256-GCM content.
pub fn decrypt_with_kek(blob: &ProtectedBlob, kek: &[u8]) -> Result<Vec<u8>> {
    let kek: [u8; 32] = kek.try_into().map_err(|_| DpapiError::KeyUnwrap)?;
    let unwrapper = KekAes256::from(kek);
    let mut cek = vec![0u8; blob.encrypted_key.len().saturating_sub(8)];
    unwrapper
        .unwrap(&blob.encrypted_key, &mut cek)
        .map_err(|_| DpapiError::KeyUnwrap)?;
    decrypt_content(blob, &cek)
}

/// Open the AES-256-GCM content with an already-unwrapped content-encryption key.
pub fn decrypt_content(blob: &ProtectedBlob, cek: &[u8]) -> Result<Vec<u8>> {
    let cipher = Aes256Gcm::new_from_slice(cek).map_err(|_| DpapiError::Decrypt)?;
    let nonce = Nonce::from_slice(&blob.nonce);
    cipher
        .decrypt(nonce, blob.encrypted_content.as_ref())
        .map_err(|_| DpapiError::Decrypt)
}

/// The whole path in one call: a blob plus the `GetKey` envelope that covers it.
///
/// Fails early if the envelope is for a different root key or a different L0 — those are not
/// derivable, and the caller has to go back to the DC with the right request.
pub fn decrypt(blob: &ProtectedBlob, envelope: &GroupKeyEnvelope) -> Result<Vec<u8>> {
    let id = &blob.key_identifier;
    if envelope.root_key_id != id.root_key_id {
        return Err(DpapiError::RootKeyMismatch {
            envelope: envelope.root_key_id.to_string(),
            blob: id.root_key_id.to_string(),
        });
    }
    if envelope.l0 != id.l0 {
        return Err(DpapiError::L0Mismatch {
            envelope: envelope.l0,
            blob: id.l0,
        });
    }
    let l2_key = gkdi::compute_l2_key(envelope, id.l1, id.l2)?;
    decrypt_with_seed_key(blob, &l2_key)
}