Skip to main content

dpapi_ng/
der.rs

1//! Just enough DER to walk a CMS `EnvelopedData`. No schema, no codegen — a tag/length/value
2//! reader with bounds checks, because the only ASN.1 this crate meets is one known shape.
3
4use crate::{DpapiError, Result};
5
6pub const SEQUENCE: u8 = 0x30;
7pub const SET: u8 = 0x31;
8pub const INTEGER: u8 = 0x02;
9pub const OCTET_STRING: u8 = 0x04;
10pub const OID: u8 = 0x06;
11
12/// Context-specific constructed tag `[n]`.
13pub const fn context(n: u8) -> u8 {
14    0xA0 | n
15}
16/// Context-specific primitive tag `[n]`.
17pub const fn context_primitive(n: u8) -> u8 {
18    0x80 | n
19}
20
21/// One TLV: its tag and its contents (header already stripped).
22#[derive(Clone, Copy, Debug)]
23pub struct Tlv<'a> {
24    pub tag: u8,
25    pub value: &'a [u8],
26}
27
28/// Reads TLVs out of one DER buffer, left to right.
29pub struct Reader<'a> {
30    b: &'a [u8],
31    pos: usize,
32}
33
34impl<'a> Reader<'a> {
35    pub fn new(b: &'a [u8]) -> Self {
36        Reader { b, pos: 0 }
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.pos >= self.b.len()
41    }
42
43    /// Next TLV, whatever its tag.
44    pub fn read_tlv(&mut self) -> Result<Tlv<'a>> {
45        let tag = *self.b.get(self.pos).ok_or(DpapiError::Der("tag"))?;
46        let first_len = *self.b.get(self.pos + 1).ok_or(DpapiError::Der("length"))?;
47        let (len, header) = if first_len & 0x80 == 0 {
48            (first_len as usize, 2)
49        } else {
50            let n = (first_len & 0x7F) as usize;
51            if n == 0 || n > 4 {
52                // Indefinite length is not valid DER; >4 bytes cannot address this buffer.
53                return Err(DpapiError::Der("length form"));
54            }
55            let raw = self
56                .b
57                .get(self.pos + 2..self.pos + 2 + n)
58                .ok_or(DpapiError::Der("long length"))?;
59            let mut len = 0usize;
60            for byte in raw {
61                len = (len << 8) | *byte as usize;
62            }
63            (len, 2 + n)
64        };
65        let start = self.pos + header;
66        let value = self
67            .b
68            .get(start..start.checked_add(len).ok_or(DpapiError::Der("length"))?)
69            .ok_or(DpapiError::Der("value"))?;
70        self.pos = start + len;
71        Ok(Tlv { tag, value })
72    }
73
74    /// Next TLV, which must carry `tag`.
75    pub fn expect(&mut self, tag: u8, what: &'static str) -> Result<&'a [u8]> {
76        let tlv = self.read_tlv()?;
77        if tlv.tag != tag {
78            return Err(DpapiError::DerTag {
79                what,
80                expected: tag,
81                got: tlv.tag,
82            });
83        }
84        Ok(tlv.value)
85    }
86
87    /// Next TLV if it carries `tag`; otherwise nothing is consumed.
88    pub fn peek_optional(&mut self, tag: u8) -> Option<&'a [u8]> {
89        let save = self.pos;
90        match self.read_tlv() {
91            Ok(tlv) if tlv.tag == tag => Some(tlv.value),
92            _ => {
93                self.pos = save;
94                None
95            }
96        }
97    }
98}
99
100/// Decode an OID's contents into dotted form.
101pub fn oid_to_string(b: &[u8]) -> Result<String> {
102    let first = *b.first().ok_or(DpapiError::Der("empty oid"))?;
103    let mut out = format!("{}.{}", first / 40, first % 40);
104    let mut acc: u128 = 0;
105    for byte in &b[1..] {
106        acc = (acc << 7) | (byte & 0x7F) as u128;
107        if byte & 0x80 == 0 {
108            out.push('.');
109            out.push_str(&acc.to_string());
110            acc = 0;
111        }
112    }
113    Ok(out)
114}
115
116/// Decode a non-negative INTEGER that fits in a `u32`.
117pub fn integer_u32(b: &[u8]) -> Result<u32> {
118    let trimmed = b.strip_prefix(&[0x00]).unwrap_or(b);
119    if trimmed.len() > 4 {
120        return Err(DpapiError::Der("integer too wide"));
121    }
122    Ok(trimmed.iter().fold(0u32, |acc, x| (acc << 8) | *x as u32))
123}