Skip to main content

dpapi_ng/
cms.rs

1//! The CMS `EnvelopedData` wrapper a DPAPI-NG blob is packaged in.
2//!
3//! Layout, as Windows writes it for a KDS-protected secret:
4//!
5//! ```text
6//! ContentInfo
7//!  ├─ contentType  1.2.840.113549.1.7.3  (envelopedData)
8//!  └─ [0] EnvelopedData
9//!      ├─ version
10//!      ├─ recipientInfos SET { [2] KEKRecipientInfo }
11//!      │    ├─ kekid → the MS-GKDI KEY_IDENTIFIER (which root key, which tree node)
12//!      │    └─ encryptedKey → the content key, AES-wrapped under the KEK
13//!      └─ encryptedContentInfo
14//!           ├─ contentEncryptionAlgorithm  AES-256-GCM + nonce
15//!           └─ [0] encryptedContent
16//! ```
17
18use crate::der::{self, Reader};
19use crate::gkdi::KeyIdentifier;
20use crate::{DpapiError, Result};
21
22/// `id-envelopedData`
23pub const OID_ENVELOPED_DATA: &str = "1.2.840.113549.1.7.3";
24/// `aes256-wrap`
25pub const OID_AES256_WRAP: &str = "2.16.840.1.101.3.4.1.45";
26/// `aes256-GCM`
27pub const OID_AES256_GCM: &str = "2.16.840.1.101.3.4.1.46";
28
29/// A parsed DPAPI-NG blob, ready to decrypt once the KEK is known.
30#[derive(Clone, Debug)]
31pub struct ProtectedBlob {
32    /// Which KDS root key and tree node the content key was wrapped for.
33    pub key_identifier: KeyIdentifier,
34    /// The content-encryption key, AES-wrapped under the KEK.
35    pub encrypted_key: Vec<u8>,
36    /// OID of the key-wrap algorithm (expected [`OID_AES256_WRAP`]).
37    pub key_wrap_oid: String,
38    /// OID of the content cipher (expected [`OID_AES256_GCM`]).
39    pub content_cipher_oid: String,
40    /// GCM nonce for the content cipher.
41    pub nonce: Vec<u8>,
42    /// Authentication-tag length in bytes, as declared in the GCM parameters.
43    pub tag_len: usize,
44    /// Ciphertext, tag appended (as CMS stores it).
45    pub encrypted_content: Vec<u8>,
46}
47
48impl ProtectedBlob {
49    /// Parse a DPAPI-NG blob — the raw bytes of `msLAPS-EncryptedPassword` (minus its
50    /// 16-byte header) or of a gMSA/dMSA protected password.
51    pub fn parse(b: &[u8]) -> Result<ProtectedBlob> {
52        let mut outer = Reader::new(b);
53        let content_info = outer.expect(der::SEQUENCE, "ContentInfo")?;
54
55        let mut ci = Reader::new(content_info);
56        let oid = der::oid_to_string(ci.expect(der::OID, "contentType")?)?;
57        if oid != OID_ENVELOPED_DATA {
58            return Err(DpapiError::NotEnvelopedData(oid));
59        }
60        let content = ci.expect(der::context(0), "[0] content")?;
61
62        let mut c = Reader::new(content);
63        let enveloped = c.expect(der::SEQUENCE, "EnvelopedData")?;
64
65        let mut ed = Reader::new(enveloped);
66        let _version = ed.expect(der::INTEGER, "EnvelopedData.version")?;
67        let recipients = ed.expect(der::SET, "recipientInfos")?;
68        let enc_content_info = ed.expect(der::SEQUENCE, "encryptedContentInfo")?;
69
70        let (key_identifier, encrypted_key, key_wrap_oid) = parse_kek_recipient(recipients)?;
71        let (content_cipher_oid, nonce, tag_len, encrypted_content) =
72            parse_encrypted_content(enc_content_info)?;
73
74        Ok(ProtectedBlob {
75            key_identifier,
76            encrypted_key,
77            key_wrap_oid,
78            content_cipher_oid,
79            nonce,
80            tag_len,
81            encrypted_content,
82        })
83    }
84}
85
86/// `recipientInfos` → the single `[2] KEKRecipientInfo` Windows writes.
87fn parse_kek_recipient(b: &[u8]) -> Result<(KeyIdentifier, Vec<u8>, String)> {
88    let mut set = Reader::new(b);
89    let kek = set.expect(der::context(2), "KEKRecipientInfo")?;
90
91    let mut r = Reader::new(kek);
92    let _version = r.expect(der::INTEGER, "KEKRecipientInfo.version")?;
93    let kekid = r.expect(der::SEQUENCE, "KEKIdentifier")?;
94    let alg = r.expect(der::SEQUENCE, "keyEncryptionAlgorithm")?;
95    let encrypted_key = r.expect(der::OCTET_STRING, "encryptedKey")?.to_vec();
96
97    let mut a = Reader::new(alg);
98    let key_wrap_oid = der::oid_to_string(a.expect(der::OID, "keyEncryptionAlgorithm.oid")?)?;
99
100    Ok((parse_kek_identifier(kekid)?, encrypted_key, key_wrap_oid))
101}
102
103/// `KEKIdentifier` carries the MS-GKDI key identifier. Windows has shipped it both directly
104/// in `keyIdentifier` and inside the optional `OtherKeyAttribute`, so accept either — the
105/// `KDSK` magic tells us which one we are looking at.
106fn parse_kek_identifier(b: &[u8]) -> Result<KeyIdentifier> {
107    let mut r = Reader::new(b);
108    let key_identifier = r.expect(der::OCTET_STRING, "kekid.keyIdentifier")?;
109
110    if let Ok(k) = KeyIdentifier::parse(key_identifier) {
111        return Ok(k);
112    }
113
114    // OtherKeyAttribute ::= SEQUENCE { keyAttrId OID, keyAttr ANY OPTIONAL }
115    while !r.is_empty() {
116        let tlv = r.read_tlv()?;
117        if tlv.tag != der::SEQUENCE {
118            continue; // the optional GeneralizedTime
119        }
120        let mut o = Reader::new(tlv.value);
121        let _attr_id = o.expect(der::OID, "OtherKeyAttribute.keyAttrId")?;
122        while !o.is_empty() {
123            let attr = o.read_tlv()?;
124            if let Ok(k) = KeyIdentifier::parse(attr.value) {
125                return Ok(k);
126            }
127        }
128    }
129    Err(DpapiError::NoKeyIdentifier)
130}
131
132/// `encryptedContentInfo` → cipher OID, GCM nonce, tag length, ciphertext.
133fn parse_encrypted_content(b: &[u8]) -> Result<(String, Vec<u8>, usize, Vec<u8>)> {
134    let mut r = Reader::new(b);
135    let _content_type = r.expect(der::OID, "encryptedContentInfo.contentType")?;
136    let alg = r.expect(der::SEQUENCE, "contentEncryptionAlgorithm")?;
137
138    // [0] encryptedContent is IMPLICIT, so it may arrive primitive or constructed.
139    let encrypted_content = match r.peek_optional(der::context_primitive(0)) {
140        Some(v) => v.to_vec(),
141        None => r.expect(der::context(0), "[0] encryptedContent")?.to_vec(),
142    };
143
144    let mut a = Reader::new(alg);
145    let cipher_oid = der::oid_to_string(a.expect(der::OID, "contentEncryptionAlgorithm.oid")?)?;
146    // GCMParameters ::= SEQUENCE { aes-nonce OCTET STRING, aes-ICVlen INTEGER DEFAULT 12 }
147    let params = a.expect(der::SEQUENCE, "GCMParameters")?;
148    let mut p = Reader::new(params);
149    let nonce = p.expect(der::OCTET_STRING, "GCMParameters.nonce")?.to_vec();
150    let tag_len = match p.peek_optional(der::INTEGER) {
151        Some(v) => der::integer_u32(v)? as usize,
152        None => 12,
153    };
154
155    Ok((cipher_oid, nonce, tag_len, encrypted_content))
156}