Skip to main content

dpapi_ng/
gkdi.rs

1//! MS-GKDI: the Group Key Distribution structures and the L0/L1/L2 key-tree walk.
2//!
3//! A DPAPI-NG blob does not carry a key — it carries a *key identifier*: which KDS root key,
4//! and which (L0, L1, L2) node of that root's tree. A domain controller hands out a
5//! [`GroupKeyEnvelope`] for some node at or above the one you asked for; deriving downwards
6//! to the exact node is [`compute_l2_key`], and it is pure computation — no network.
7
8use crate::kdf::{kdf, kds_service_label, HashAlg};
9use crate::{cursor::Cursor, DpapiError, Result};
10
11/// `KDSK` — the magic in a key-identifier blob.
12pub const KEY_IDENTIFIER_MAGIC: u32 = 0x4B53_444B;
13/// `KDSK` — the magic in a group-key envelope.
14pub const ENVELOPE_MAGIC: u32 = 0x4B53_444B;
15/// The tree is 32-ary: L1 and L2 indices run 0..=31.
16pub const TREE_ARITY: i32 = 32;
17
18/// A 16-byte GUID in its on-wire (mixed-endian) form, kept as raw bytes because that is
19/// exactly what the KDF context wants.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub struct RootKeyId(pub [u8; 16]);
22
23impl RootKeyId {
24    pub fn from_bytes(b: &[u8]) -> Result<RootKeyId> {
25        Ok(RootKeyId(
26            b.get(..16)
27                .ok_or(DpapiError::Truncated("root key identifier"))?
28                .try_into()
29                .unwrap(),
30        ))
31    }
32}
33
34impl std::fmt::Display for RootKeyId {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        let b = &self.0;
37        write!(
38            f,
39            "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{}",
40            b[3],
41            b[2],
42            b[1],
43            b[0],
44            b[5],
45            b[4],
46            b[7],
47            b[6],
48            b[8],
49            b[9],
50            b[10..16]
51                .iter()
52                .map(|x| format!("{x:02x}"))
53                .collect::<String>()
54        )
55    }
56}
57
58/// `KDF_PARAMETERS` — names the hash the key tree is derived with.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct KdfParameters {
61    pub hash: HashAlg,
62}
63
64impl KdfParameters {
65    pub fn parse(b: &[u8]) -> Result<KdfParameters> {
66        let mut c = Cursor::new(b);
67        // Two fixed u32 headers, then the length of the NUL-terminated UTF-16LE name,
68        // then another fixed u32, then the name itself.
69        c.skip(8, "kdf parameters header")?;
70        let name_len = c.u32le("kdf hash name length")? as usize;
71        c.skip(4, "kdf parameters padding")?;
72        let raw = c.take(name_len, "kdf hash name")?;
73        Ok(KdfParameters {
74            hash: HashAlg::from_name(&utf16_lossy(raw))?,
75        })
76    }
77
78    pub fn to_bytes(&self) -> Vec<u8> {
79        let name: Vec<u8> = format!("{}\0", self.hash.name())
80            .encode_utf16()
81            .flat_map(u16::to_le_bytes)
82            .collect();
83        let mut out = Vec::with_capacity(20 + name.len());
84        out.extend_from_slice(&0u32.to_le_bytes());
85        out.extend_from_slice(&1u32.to_le_bytes());
86        out.extend_from_slice(&(name.len() as u32).to_le_bytes());
87        out.extend_from_slice(&0u32.to_le_bytes());
88        out.extend_from_slice(&name);
89        out
90    }
91}
92
93/// The `KEY_IDENTIFIER` carried in a protected blob: which root key and which tree node the
94/// content was encrypted for.
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub struct KeyIdentifier {
97    pub version: u32,
98    pub flags: u32,
99    pub l0: i32,
100    pub l1: i32,
101    pub l2: i32,
102    pub root_key_id: RootKeyId,
103    pub kdf_algorithm: String,
104    pub kdf_parameters: Vec<u8>,
105    pub secret_algorithm: String,
106    pub secret_parameters: Vec<u8>,
107    pub private_key_length: u32,
108    pub public_key_length: u32,
109    pub domain_name: String,
110    pub forest_name: String,
111}
112
113impl KeyIdentifier {
114    /// `true` when the blob was protected with the public-key half of the node (the
115    /// key-agreement path) rather than the seed key directly.
116    pub fn is_public_key(&self) -> bool {
117        self.flags & 0x01 != 0
118    }
119
120    pub fn parse(b: &[u8]) -> Result<KeyIdentifier> {
121        let mut c = Cursor::new(b);
122        let version = c.u32le("version")?;
123        let magic = c.u32le("magic")?;
124        if magic != KEY_IDENTIFIER_MAGIC {
125            return Err(DpapiError::BadMagic {
126                what: "key identifier",
127                got: magic,
128            });
129        }
130        let flags = c.u32le("flags")?;
131        let l0 = c.i32le("l0 index")?;
132        let l1 = c.i32le("l1 index")?;
133        let l2 = c.i32le("l2 index")?;
134        let root_key_id = RootKeyId::from_bytes(c.take(16, "root key identifier")?)?;
135        let kdf_alg_len = c.u32le("kdf algorithm length")? as usize;
136        let kdf_param_len = c.u32le("kdf parameters length")? as usize;
137        let secret_alg_len = c.u32le("secret algorithm length")? as usize;
138        let secret_param_len = c.u32le("secret parameters length")? as usize;
139        let private_key_length = c.u32le("private key length")?;
140        let public_key_length = c.u32le("public key length")?;
141        let domain_len = c.u32le("domain name length")? as usize;
142        let forest_len = c.u32le("forest name length")? as usize;
143
144        let kdf_algorithm = utf16_lossy(c.take(kdf_alg_len, "kdf algorithm")?);
145        let kdf_parameters = c.take(kdf_param_len, "kdf parameters")?.to_vec();
146        let secret_algorithm = utf16_lossy(c.take(secret_alg_len, "secret algorithm")?);
147        let secret_parameters = c.take(secret_param_len, "secret parameters")?.to_vec();
148        let domain_name = utf16_lossy(c.take(domain_len, "domain name")?);
149        let forest_name = utf16_lossy(c.take(forest_len, "forest name")?);
150
151        Ok(KeyIdentifier {
152            version,
153            flags,
154            l0,
155            l1,
156            l2,
157            root_key_id,
158            kdf_algorithm,
159            kdf_parameters,
160            secret_algorithm,
161            secret_parameters,
162            private_key_length,
163            public_key_length,
164            domain_name,
165            forest_name,
166        })
167    }
168
169    pub fn to_bytes(&self) -> Vec<u8> {
170        let kdf_alg = utf16z(&self.kdf_algorithm);
171        let secret_alg = utf16z(&self.secret_algorithm);
172        let domain = utf16z(&self.domain_name);
173        let forest = utf16z(&self.forest_name);
174
175        let mut out = Vec::new();
176        out.extend_from_slice(&self.version.to_le_bytes());
177        out.extend_from_slice(&KEY_IDENTIFIER_MAGIC.to_le_bytes());
178        out.extend_from_slice(&self.flags.to_le_bytes());
179        out.extend_from_slice(&self.l0.to_le_bytes());
180        out.extend_from_slice(&self.l1.to_le_bytes());
181        out.extend_from_slice(&self.l2.to_le_bytes());
182        out.extend_from_slice(&self.root_key_id.0);
183        out.extend_from_slice(&(kdf_alg.len() as u32).to_le_bytes());
184        out.extend_from_slice(&(self.kdf_parameters.len() as u32).to_le_bytes());
185        out.extend_from_slice(&(secret_alg.len() as u32).to_le_bytes());
186        out.extend_from_slice(&(self.secret_parameters.len() as u32).to_le_bytes());
187        out.extend_from_slice(&self.private_key_length.to_le_bytes());
188        out.extend_from_slice(&self.public_key_length.to_le_bytes());
189        out.extend_from_slice(&(domain.len() as u32).to_le_bytes());
190        out.extend_from_slice(&(forest.len() as u32).to_le_bytes());
191        out.extend_from_slice(&kdf_alg);
192        out.extend_from_slice(&self.kdf_parameters);
193        out.extend_from_slice(&secret_alg);
194        out.extend_from_slice(&self.secret_parameters);
195        out.extend_from_slice(&domain);
196        out.extend_from_slice(&forest);
197        out
198    }
199
200    /// The hash the key tree for this blob is derived with.
201    pub fn hash(&self) -> Result<HashAlg> {
202        Ok(KdfParameters::parse(&self.kdf_parameters)?.hash)
203    }
204}
205
206/// `GROUP_KEY_ENVELOPE` — what `GetKey` returns: seed key material for one node of the tree,
207/// at or above the node you asked for.
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct GroupKeyEnvelope {
210    pub version: u32,
211    pub flags: u32,
212    pub l0: i32,
213    pub l1: i32,
214    pub l2: i32,
215    pub root_key_id: RootKeyId,
216    pub kdf_algorithm: String,
217    pub kdf_parameters: Vec<u8>,
218    pub secret_algorithm: String,
219    pub secret_parameters: Vec<u8>,
220    pub private_key_length: u32,
221    pub public_key_length: u32,
222    pub domain_name: String,
223    pub forest_name: String,
224    pub l1_key: Vec<u8>,
225    pub l2_key: Vec<u8>,
226}
227
228impl GroupKeyEnvelope {
229    /// `true` if this envelope carries the public key rather than seed keys.
230    pub fn is_public_key(&self) -> bool {
231        self.flags & 0x02 != 0
232    }
233
234    pub fn hash(&self) -> Result<HashAlg> {
235        Ok(KdfParameters::parse(&self.kdf_parameters)?.hash)
236    }
237
238    pub fn parse(b: &[u8]) -> Result<GroupKeyEnvelope> {
239        let mut c = Cursor::new(b);
240        let version = c.u32le("version")?;
241        let magic = c.u32le("magic")?;
242        if magic != ENVELOPE_MAGIC {
243            return Err(DpapiError::BadMagic {
244                what: "group key envelope",
245                got: magic,
246            });
247        }
248        let flags = c.u32le("flags")?;
249        let l0 = c.i32le("l0 index")?;
250        let l1 = c.i32le("l1 index")?;
251        let l2 = c.i32le("l2 index")?;
252        let root_key_id = RootKeyId::from_bytes(c.take(16, "root key identifier")?)?;
253        let kdf_alg_len = c.u32le("kdf algorithm length")? as usize;
254        let kdf_param_len = c.u32le("kdf parameters length")? as usize;
255        let secret_alg_len = c.u32le("secret algorithm length")? as usize;
256        let secret_param_len = c.u32le("secret parameters length")? as usize;
257        let private_key_length = c.u32le("private key length")?;
258        let public_key_length = c.u32le("public key length")?;
259        let l1_key_len = c.u32le("l1 key length")? as usize;
260        let l2_key_len = c.u32le("l2 key length")? as usize;
261        let domain_len = c.u32le("domain name length")? as usize;
262        let forest_len = c.u32le("forest name length")? as usize;
263
264        let kdf_algorithm = utf16_lossy(c.take(kdf_alg_len, "kdf algorithm")?);
265        let kdf_parameters = c.take(kdf_param_len, "kdf parameters")?.to_vec();
266        let secret_algorithm = utf16_lossy(c.take(secret_alg_len, "secret algorithm")?);
267        let secret_parameters = c.take(secret_param_len, "secret parameters")?.to_vec();
268        let domain_name = utf16_lossy(c.take(domain_len, "domain name")?);
269        let forest_name = utf16_lossy(c.take(forest_len, "forest name")?);
270        let l1_key = c.take(l1_key_len, "l1 key")?.to_vec();
271        let l2_key = c.take(l2_key_len, "l2 key")?.to_vec();
272
273        Ok(GroupKeyEnvelope {
274            version,
275            flags,
276            l0,
277            l1,
278            l2,
279            root_key_id,
280            kdf_algorithm,
281            kdf_parameters,
282            secret_algorithm,
283            secret_parameters,
284            private_key_length,
285            public_key_length,
286            domain_name,
287            forest_name,
288            l1_key,
289            l2_key,
290        })
291    }
292}
293
294/// The KDF context for one tree node: root key GUID followed by the three indices.
295pub fn kdf_context(root: RootKeyId, l0: i32, l1: i32, l2: i32) -> Vec<u8> {
296    let mut ctx = Vec::with_capacity(28);
297    ctx.extend_from_slice(&root.0);
298    ctx.extend_from_slice(&l0.to_le_bytes());
299    ctx.extend_from_slice(&l1.to_le_bytes());
300    ctx.extend_from_slice(&l2.to_le_bytes());
301    ctx
302}
303
304/// Walk an envelope down to the exact `(l1, l2)` node the blob was encrypted for.
305///
306/// The DC returns the key for the node it is willing to hand out; every step from there to
307/// the requested node is a one-way KDF, which is what makes the tree useful — a key for a
308/// later node cannot recover an earlier one.
309pub fn compute_l2_key(env: &GroupKeyEnvelope, want_l1: i32, want_l2: i32) -> Result<Vec<u8>> {
310    if env.is_public_key() {
311        return Err(DpapiError::PublicKeyEnvelope);
312    }
313    if !(0..TREE_ARITY).contains(&want_l1) || !(0..TREE_ARITY).contains(&want_l2) {
314        return Err(DpapiError::BadTreeIndex {
315            l1: want_l1,
316            l2: want_l2,
317        });
318    }
319    let hash = env.hash()?;
320    let label = kds_service_label();
321    let key_len = 64;
322
323    let mut l1 = env.l1;
324    let mut l1_key = env.l1_key.clone();
325    let mut l2 = env.l2;
326    let mut l2_key = env.l2_key.clone();
327
328    // The L2 chain only runs downwards. A fully-seeded node (l2 == 31), a move to a different
329    // L1 branch, or a request for a *later* L2 than we hold all mean the chain has to be
330    // re-seeded from the L1 key — the tree is one-way, so a later node is not reachable from
331    // an earlier one.
332    let mut reseed_l2 = l2 == TREE_ARITY - 1 || env.l1 != want_l1 || want_l2 > l2;
333    if l2 != TREE_ARITY - 1 && env.l1 != want_l1 {
334        l1 -= 1;
335    }
336    while l1 != want_l1 {
337        if l1_key.is_empty() {
338            return Err(DpapiError::MissingSeedKey("L1"));
339        }
340        reseed_l2 = true;
341        l1 -= 1;
342        l1_key = kdf(
343            hash,
344            &l1_key,
345            &label,
346            &kdf_context(env.root_key_id, env.l0, l1, -1),
347            key_len,
348        );
349    }
350    if reseed_l2 {
351        if l1_key.is_empty() {
352            return Err(DpapiError::MissingSeedKey("L1"));
353        }
354        l2 = TREE_ARITY - 1;
355        l2_key = kdf(
356            hash,
357            &l1_key,
358            &label,
359            &kdf_context(env.root_key_id, env.l0, l1, l2),
360            key_len,
361        );
362    }
363    if l2 < want_l2 {
364        // Only reachable if the envelope carried no L1 key to re-seed from.
365        return Err(DpapiError::MissingSeedKey("L1"));
366    }
367    while l2 != want_l2 {
368        if l2_key.is_empty() {
369            return Err(DpapiError::MissingSeedKey("L2"));
370        }
371        l2 -= 1;
372        l2_key = kdf(
373            hash,
374            &l2_key,
375            &label,
376            &kdf_context(env.root_key_id, env.l0, l1, l2),
377            key_len,
378        );
379    }
380    Ok(l2_key)
381}
382
383pub(crate) fn utf16_lossy(b: &[u8]) -> String {
384    let units: Vec<u16> = b
385        .chunks_exact(2)
386        .map(|c| u16::from_le_bytes([c[0], c[1]]))
387        .collect();
388    let trimmed = match units.iter().rposition(|&u| u != 0) {
389        Some(i) => &units[..=i],
390        None => &[][..],
391    };
392    String::from_utf16_lossy(trimmed)
393}
394
395pub(crate) fn utf16z(s: &str) -> Vec<u8> {
396    let mut out: Vec<u8> = s.encode_utf16().flat_map(u16::to_le_bytes).collect();
397    out.extend_from_slice(&[0, 0]);
398    out
399}