pub mod cms;
pub mod der;
pub mod gkdi;
pub mod kdf;
#[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>;
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 },
}
}
}
#[derive(Clone, Debug)]
pub struct LapsBlob {
pub update_timestamp: u64,
pub blob: Vec<u8>,
}
impl LapsBlob {
pub fn parse(b: &[u8]) -> Result<LapsBlob> {
if b.len() < 16 {
return Err(DpapiError::ShortLapsBlob);
}
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(),
})
}
pub fn protected(&self) -> Result<ProtectedBlob> {
ProtectedBlob::parse(&self.blob)
}
}
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())
}
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)
}
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)
}
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)
}
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)
}
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)
}