dpapi-ng 0.2.0

Pure-Rust DPAPI-NG (CNG group protection) — decrypt Windows LAPS, gMSA and dMSA password blobs without a Windows host. Delegates the MS-GKDI key tree and ISDKey RPC to the `ms-gkdi` crate
Documentation
//! DPAPI-NG (CNG "group protection"), 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.
//!
//! **0.2 wiring.** The MS-GKDI structures, KDF, tree walk and `ISDKey::GetKey` RPC now live
//! in the [`ms-gkdi`](https://crates.io/crates/ms-gkdi) crate. The [`gkdi`], [`kdf`] and
//! [`rpc`] modules in this crate are thin `pub use` shims marked `#[deprecated]`. New code
//! should depend on `ms-gkdi` directly; existing 0.1.x code keeps compiling unchanged
//! (`ms_gkdi::GkdiError` converts into [`DpapiError`] via `From`).
//!
//! The full pipeline:
//!
//! 1. [`LapsBlob::parse`] / [`cms::ProtectedBlob::parse`] — unwrap the CMS, recover the key
//!    identifier.
//! 2. Fetch the envelope from a DC: either [`ms_gkdi::rpc::get_key`] (feature `rpc`) or hand
//!    the reply bytes to [`ms_gkdi::gkdi::GroupKeyEnvelope::parse`] yourself.
//! 3. [`ms_gkdi::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.

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

/// MS-GKDI `GetKey` RPC re-export — see [`ms_gkdi::rpc`]. Kept behind the `rpc` feature so
/// 0.1.x callers who wrote `use dpapi_ng::rpc::get_key;` still compile.
#[cfg(feature = "rpc")]
pub mod rpc;

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

use cms::ProtectedBlob;
use ms_gkdi::gkdi::{self as gkdi_impl, GroupKeyEnvelope};
use ms_gkdi::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>;

/// Lift a `ms-gkdi` error into `DpapiError` so `?` at the call site keeps working after the
/// wiring. Variants match 1:1 with the ms-gkdi enum.
impl From<ms_gkdi::GkdiError> for DpapiError {
    fn from(e: ms_gkdi::GkdiError) -> Self {
        match e {
            ms_gkdi::GkdiError::Truncated(w) => DpapiError::Truncated(w),
            ms_gkdi::GkdiError::BadMagic { what, got } => DpapiError::BadMagic { what, got },
            ms_gkdi::GkdiError::UnsupportedAlgorithm(a) => DpapiError::UnsupportedAlgorithm(a),
            ms_gkdi::GkdiError::PublicKeyEnvelope => DpapiError::PublicKeyEnvelope,
            ms_gkdi::GkdiError::MissingSeedKey(w) => DpapiError::MissingSeedKey(w),
            ms_gkdi::GkdiError::BadTreeIndex { l1, l2 } => DpapiError::BadTreeIndex { l1, l2 },
        }
    }
}

/// 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 = utf16le_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())
}

/// Best-effort UTF-16LE → String decode, trimming trailing NULs. Kept local so the crate
/// doesn't lean on a `pub(crate)` helper in `ms-gkdi`.
fn utf16le_lossy(b: &[u8]) -> String {
    let units: Vec<u16> = b
        .chunks_exact(2)
        .map(|c| u16::from_le_bytes([c[0], c[1]]))
        .collect();
    let trimmed = match units.iter().rposition(|&u| u != 0) {
        Some(i) => &units[..=i],
        None => &[][..],
    };
    String::from_utf16_lossy(trimmed)
}

/// 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_impl::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_impl::compute_l2_key(envelope, id.l1, id.l2)?;
    decrypt_with_seed_key(blob, &l2_key)
}