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
//! The CMS `EnvelopedData` wrapper a DPAPI-NG blob is packaged in.
//!
//! Layout, as Windows writes it for a KDS-protected secret:
//!
//! ```text
//! ContentInfo
//!  ├─ contentType  1.2.840.113549.1.7.3  (envelopedData)
//!  └─ [0] EnvelopedData
//!      ├─ version
//!      ├─ recipientInfos SET { [2] KEKRecipientInfo }
//!      │    ├─ kekid → the MS-GKDI KEY_IDENTIFIER (which root key, which tree node)
//!      │    └─ encryptedKey → the content key, AES-wrapped under the KEK
//!      └─ encryptedContentInfo
//!           ├─ contentEncryptionAlgorithm  AES-256-GCM + nonce
//!           └─ [0] encryptedContent
//! ```

use crate::der::{self, Reader};
use crate::gkdi::KeyIdentifier;
use crate::{DpapiError, Result};

/// `id-envelopedData`
pub const OID_ENVELOPED_DATA: &str = "1.2.840.113549.1.7.3";
/// `aes256-wrap`
pub const OID_AES256_WRAP: &str = "2.16.840.1.101.3.4.1.45";
/// `aes256-GCM`
pub const OID_AES256_GCM: &str = "2.16.840.1.101.3.4.1.46";

/// A parsed DPAPI-NG blob, ready to decrypt once the KEK is known.
#[derive(Clone, Debug)]
pub struct ProtectedBlob {
    /// Which KDS root key and tree node the content key was wrapped for.
    pub key_identifier: KeyIdentifier,
    /// The content-encryption key, AES-wrapped under the KEK.
    pub encrypted_key: Vec<u8>,
    /// OID of the key-wrap algorithm (expected [`OID_AES256_WRAP`]).
    pub key_wrap_oid: String,
    /// OID of the content cipher (expected [`OID_AES256_GCM`]).
    pub content_cipher_oid: String,
    /// GCM nonce for the content cipher.
    pub nonce: Vec<u8>,
    /// Authentication-tag length in bytes, as declared in the GCM parameters.
    pub tag_len: usize,
    /// Ciphertext, tag appended (as CMS stores it).
    pub encrypted_content: Vec<u8>,
}

impl ProtectedBlob {
    /// Parse a DPAPI-NG blob — the raw bytes of `msLAPS-EncryptedPassword` (minus its
    /// 16-byte header) or of a gMSA/dMSA protected password.
    pub fn parse(b: &[u8]) -> Result<ProtectedBlob> {
        let mut outer = Reader::new(b);
        let content_info = outer.expect(der::SEQUENCE, "ContentInfo")?;

        let mut ci = Reader::new(content_info);
        let oid = der::oid_to_string(ci.expect(der::OID, "contentType")?)?;
        if oid != OID_ENVELOPED_DATA {
            return Err(DpapiError::NotEnvelopedData(oid));
        }
        let content = ci.expect(der::context(0), "[0] content")?;

        let mut c = Reader::new(content);
        let enveloped = c.expect(der::SEQUENCE, "EnvelopedData")?;

        let mut ed = Reader::new(enveloped);
        let _version = ed.expect(der::INTEGER, "EnvelopedData.version")?;
        let recipients = ed.expect(der::SET, "recipientInfos")?;
        let enc_content_info = ed.expect(der::SEQUENCE, "encryptedContentInfo")?;

        let (key_identifier, encrypted_key, key_wrap_oid) = parse_kek_recipient(recipients)?;
        let (content_cipher_oid, nonce, tag_len, encrypted_content) =
            parse_encrypted_content(enc_content_info)?;

        Ok(ProtectedBlob {
            key_identifier,
            encrypted_key,
            key_wrap_oid,
            content_cipher_oid,
            nonce,
            tag_len,
            encrypted_content,
        })
    }
}

/// `recipientInfos` → the single `[2] KEKRecipientInfo` Windows writes.
fn parse_kek_recipient(b: &[u8]) -> Result<(KeyIdentifier, Vec<u8>, String)> {
    let mut set = Reader::new(b);
    let kek = set.expect(der::context(2), "KEKRecipientInfo")?;

    let mut r = Reader::new(kek);
    let _version = r.expect(der::INTEGER, "KEKRecipientInfo.version")?;
    let kekid = r.expect(der::SEQUENCE, "KEKIdentifier")?;
    let alg = r.expect(der::SEQUENCE, "keyEncryptionAlgorithm")?;
    let encrypted_key = r.expect(der::OCTET_STRING, "encryptedKey")?.to_vec();

    let mut a = Reader::new(alg);
    let key_wrap_oid = der::oid_to_string(a.expect(der::OID, "keyEncryptionAlgorithm.oid")?)?;

    Ok((parse_kek_identifier(kekid)?, encrypted_key, key_wrap_oid))
}

/// `KEKIdentifier` carries the MS-GKDI key identifier. Windows has shipped it both directly
/// in `keyIdentifier` and inside the optional `OtherKeyAttribute`, so accept either — the
/// `KDSK` magic tells us which one we are looking at.
fn parse_kek_identifier(b: &[u8]) -> Result<KeyIdentifier> {
    let mut r = Reader::new(b);
    let key_identifier = r.expect(der::OCTET_STRING, "kekid.keyIdentifier")?;

    if let Ok(k) = KeyIdentifier::parse(key_identifier) {
        return Ok(k);
    }

    // OtherKeyAttribute ::= SEQUENCE { keyAttrId OID, keyAttr ANY OPTIONAL }
    while !r.is_empty() {
        let tlv = r.read_tlv()?;
        if tlv.tag != der::SEQUENCE {
            continue; // the optional GeneralizedTime
        }
        let mut o = Reader::new(tlv.value);
        let _attr_id = o.expect(der::OID, "OtherKeyAttribute.keyAttrId")?;
        while !o.is_empty() {
            let attr = o.read_tlv()?;
            if let Ok(k) = KeyIdentifier::parse(attr.value) {
                return Ok(k);
            }
        }
    }
    Err(DpapiError::NoKeyIdentifier)
}

/// `encryptedContentInfo` → cipher OID, GCM nonce, tag length, ciphertext.
fn parse_encrypted_content(b: &[u8]) -> Result<(String, Vec<u8>, usize, Vec<u8>)> {
    let mut r = Reader::new(b);
    let _content_type = r.expect(der::OID, "encryptedContentInfo.contentType")?;
    let alg = r.expect(der::SEQUENCE, "contentEncryptionAlgorithm")?;

    // [0] encryptedContent is IMPLICIT, so it may arrive primitive or constructed.
    let encrypted_content = match r.peek_optional(der::context_primitive(0)) {
        Some(v) => v.to_vec(),
        None => r.expect(der::context(0), "[0] encryptedContent")?.to_vec(),
    };

    let mut a = Reader::new(alg);
    let cipher_oid = der::oid_to_string(a.expect(der::OID, "contentEncryptionAlgorithm.oid")?)?;
    // GCMParameters ::= SEQUENCE { aes-nonce OCTET STRING, aes-ICVlen INTEGER DEFAULT 12 }
    let params = a.expect(der::SEQUENCE, "GCMParameters")?;
    let mut p = Reader::new(params);
    let nonce = p.expect(der::OCTET_STRING, "GCMParameters.nonce")?.to_vec();
    let tag_len = match p.peek_optional(der::INTEGER) {
        Some(v) => der::integer_u32(v)? as usize,
        None => 12,
    };

    Ok((cipher_oid, nonce, tag_len, encrypted_content))
}