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
//! Just enough DER to walk a CMS `EnvelopedData`. No schema, no codegen — a tag/length/value
//! reader with bounds checks, because the only ASN.1 this crate meets is one known shape.

use crate::{DpapiError, Result};

pub const SEQUENCE: u8 = 0x30;
pub const SET: u8 = 0x31;
pub const INTEGER: u8 = 0x02;
pub const OCTET_STRING: u8 = 0x04;
pub const OID: u8 = 0x06;

/// Context-specific constructed tag `[n]`.
pub const fn context(n: u8) -> u8 {
    0xA0 | n
}
/// Context-specific primitive tag `[n]`.
pub const fn context_primitive(n: u8) -> u8 {
    0x80 | n
}

/// One TLV: its tag and its contents (header already stripped).
#[derive(Clone, Copy, Debug)]
pub struct Tlv<'a> {
    pub tag: u8,
    pub value: &'a [u8],
}

/// Reads TLVs out of one DER buffer, left to right.
pub struct Reader<'a> {
    b: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    pub fn new(b: &'a [u8]) -> Self {
        Reader { b, pos: 0 }
    }

    pub fn is_empty(&self) -> bool {
        self.pos >= self.b.len()
    }

    /// Next TLV, whatever its tag.
    pub fn read_tlv(&mut self) -> Result<Tlv<'a>> {
        let tag = *self.b.get(self.pos).ok_or(DpapiError::Der("tag"))?;
        let first_len = *self.b.get(self.pos + 1).ok_or(DpapiError::Der("length"))?;
        let (len, header) = if first_len & 0x80 == 0 {
            (first_len as usize, 2)
        } else {
            let n = (first_len & 0x7F) as usize;
            if n == 0 || n > 4 {
                // Indefinite length is not valid DER; >4 bytes cannot address this buffer.
                return Err(DpapiError::Der("length form"));
            }
            let raw = self
                .b
                .get(self.pos + 2..self.pos + 2 + n)
                .ok_or(DpapiError::Der("long length"))?;
            let mut len = 0usize;
            for byte in raw {
                len = (len << 8) | *byte as usize;
            }
            (len, 2 + n)
        };
        let start = self.pos + header;
        let value = self
            .b
            .get(start..start.checked_add(len).ok_or(DpapiError::Der("length"))?)
            .ok_or(DpapiError::Der("value"))?;
        self.pos = start + len;
        Ok(Tlv { tag, value })
    }

    /// Next TLV, which must carry `tag`.
    pub fn expect(&mut self, tag: u8, what: &'static str) -> Result<&'a [u8]> {
        let tlv = self.read_tlv()?;
        if tlv.tag != tag {
            return Err(DpapiError::DerTag {
                what,
                expected: tag,
                got: tlv.tag,
            });
        }
        Ok(tlv.value)
    }

    /// Next TLV if it carries `tag`; otherwise nothing is consumed.
    pub fn peek_optional(&mut self, tag: u8) -> Option<&'a [u8]> {
        let save = self.pos;
        match self.read_tlv() {
            Ok(tlv) if tlv.tag == tag => Some(tlv.value),
            _ => {
                self.pos = save;
                None
            }
        }
    }
}

/// Decode an OID's contents into dotted form.
pub fn oid_to_string(b: &[u8]) -> Result<String> {
    let first = *b.first().ok_or(DpapiError::Der("empty oid"))?;
    let mut out = format!("{}.{}", first / 40, first % 40);
    let mut acc: u128 = 0;
    for byte in &b[1..] {
        acc = (acc << 7) | (byte & 0x7F) as u128;
        if byte & 0x80 == 0 {
            out.push('.');
            out.push_str(&acc.to_string());
            acc = 0;
        }
    }
    Ok(out)
}

/// Decode a non-negative INTEGER that fits in a `u32`.
pub fn integer_u32(b: &[u8]) -> Result<u32> {
    let trimmed = b.strip_prefix(&[0x00]).unwrap_or(b);
    if trimmed.len() > 4 {
        return Err(DpapiError::Der("integer too wide"));
    }
    Ok(trimmed.iter().fold(0u32, |acc, x| (acc << 8) | *x as u32))
}