Skip to main content

webpki/
der.rs

1// Copyright 2015 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15#[cfg(feature = "alloc")]
16use alloc::vec::Vec;
17use core::marker::PhantomData;
18
19use crate::{Error, error::DerTypeId};
20
21/// Iterator to parse a sequence of DER-encoded values of type `T`.
22#[derive(Debug)]
23pub struct DerIterator<'a, T> {
24    reader: untrusted::Reader<'a>,
25    marker: PhantomData<T>,
26}
27
28impl<'a, T> DerIterator<'a, T> {
29    /// [`DerIterator`] will consume all of the bytes in `input` reading values of type `T`.
30    pub(crate) fn new(input: untrusted::Input<'a>) -> Self {
31        Self {
32            reader: untrusted::Reader::new(input),
33            marker: PhantomData,
34        }
35    }
36}
37
38impl<'a, T: FromDer<'a>> Iterator for DerIterator<'a, T> {
39    type Item = Result<T, Error>;
40
41    fn next(&mut self) -> Option<Self::Item> {
42        (!self.reader.at_end()).then(|| T::from_der(&mut self.reader))
43    }
44}
45
46pub(crate) trait FromDer<'a>: Sized + 'a {
47    /// Parse a value of type `Self` from the given DER-encoded input.
48    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error>;
49
50    const TYPE_ID: DerTypeId;
51}
52
53pub(crate) fn read_all<'a, T: FromDer<'a>>(input: untrusted::Input<'a>) -> Result<T, Error> {
54    input.read_all(Error::TrailingData(T::TYPE_ID), T::from_der)
55}
56
57// Copied (and extended) from ring's src/der.rs
58#[expect(clippy::upper_case_acronyms)]
59#[derive(Clone, Copy, Eq, PartialEq)]
60#[repr(u8)]
61pub(crate) enum Tag {
62    Boolean = 0x01,
63    Integer = 0x02,
64    BitString = 0x03,
65    OctetString = 0x04,
66    OID = 0x06,
67    Enum = 0x0A,
68    Sequence = CONSTRUCTED | 0x10, // 0x30
69    UTCTime = 0x17,
70    GeneralizedTime = 0x18,
71
72    #[expect(clippy::identity_op)]
73    ContextSpecificConstructed0 = CONTEXT_SPECIFIC | CONSTRUCTED | 0,
74    ContextSpecificConstructed1 = CONTEXT_SPECIFIC | CONSTRUCTED | 1,
75    ContextSpecificConstructed3 = CONTEXT_SPECIFIC | CONSTRUCTED | 3,
76
77    ContextSpecificPrimitive1 = CONTEXT_SPECIFIC | 1,
78    ContextSpecificPrimitive2 = CONTEXT_SPECIFIC | 2,
79}
80
81pub(crate) const CONSTRUCTED: u8 = 0x20;
82pub(crate) const CONTEXT_SPECIFIC: u8 = 0x80;
83
84impl From<Tag> for usize {
85    #[expect(clippy::as_conversions)]
86    fn from(tag: Tag) -> Self {
87        tag as Self
88    }
89}
90
91impl From<Tag> for u8 {
92    #[expect(clippy::as_conversions)]
93    fn from(tag: Tag) -> Self {
94        tag as Self
95    } // XXX: narrowing conversion.
96}
97
98#[inline(always)]
99pub(crate) fn expect_tag_and_get_value_limited<'a>(
100    input: &mut untrusted::Reader<'a>,
101    tag: Tag,
102    size_limit: usize,
103) -> Result<untrusted::Input<'a>, Error> {
104    let (actual_tag, inner) = read_tag_and_get_value_limited(input, size_limit)?;
105    if usize::from(tag) != usize::from(actual_tag) {
106        return Err(Error::BadDer);
107    }
108    Ok(inner)
109}
110
111pub(crate) fn nested_limited<'a, R>(
112    input: &mut untrusted::Reader<'a>,
113    tag: Tag,
114    error: Error,
115    decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
116    size_limit: usize,
117) -> Result<R, Error> {
118    match expect_tag_and_get_value_limited(input, tag, size_limit) {
119        Ok(value) => value.read_all(error, decoder),
120        Err(_) => Err(error),
121    }
122}
123
124// TODO: investigate taking decoder as a reference to reduce generated code
125// size.
126pub(crate) fn nested<'a, R>(
127    input: &mut untrusted::Reader<'a>,
128    tag: Tag,
129    error: Error,
130    decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
131) -> Result<R, Error> {
132    nested_limited(input, tag, error, decoder, TWO_BYTE_DER_SIZE)
133}
134
135pub(crate) fn expect_tag<'a>(
136    input: &mut untrusted::Reader<'a>,
137    tag: Tag,
138) -> Result<untrusted::Input<'a>, Error> {
139    let (actual_tag, value) = read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)?;
140    if usize::from(tag) != usize::from(actual_tag) {
141        return Err(Error::BadDer);
142    }
143
144    Ok(value)
145}
146
147#[inline(always)]
148pub(crate) fn read_tag_and_get_value<'a>(
149    input: &mut untrusted::Reader<'a>,
150) -> Result<(u8, untrusted::Input<'a>), Error> {
151    read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)
152}
153
154#[inline(always)]
155pub(crate) fn read_tag_and_get_value_limited<'a>(
156    input: &mut untrusted::Reader<'a>,
157    size_limit: usize,
158) -> Result<(u8, untrusted::Input<'a>), Error> {
159    let tag = input.read_byte().map_err(end_of_input_err)?;
160    if (tag & HIGH_TAG_RANGE_START) == HIGH_TAG_RANGE_START {
161        return Err(Error::BadDer); // High tag number form is not allowed.
162    }
163
164    // If the high order bit of the first byte is set to zero then the length
165    // is encoded in the seven remaining bits of that byte. Otherwise, those
166    // seven bits represent the number of bytes used to encode the length.
167    let length = match input.read_byte().map_err(end_of_input_err)? {
168        n if (n & SHORT_FORM_LEN_MAX) == 0 => usize::from(n),
169        LONG_FORM_LEN_ONE_BYTE => {
170            let length_byte = input.read_byte().map_err(end_of_input_err)?;
171            if length_byte < SHORT_FORM_LEN_MAX {
172                return Err(Error::BadDer); // Not the canonical encoding.
173            }
174            usize::from(length_byte)
175        }
176        LONG_FORM_LEN_TWO_BYTES => {
177            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
178            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
179            let combined = (length_byte_one << 8) | length_byte_two;
180            if combined <= LONG_FORM_LEN_ONE_BYTE_MAX {
181                return Err(Error::BadDer); // Not the canonical encoding.
182            }
183            combined
184        }
185        LONG_FORM_LEN_THREE_BYTES => {
186            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
187            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
188            let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
189            let combined = (length_byte_one << 16) | (length_byte_two << 8) | length_byte_three;
190            if combined <= LONG_FORM_LEN_TWO_BYTES_MAX {
191                return Err(Error::BadDer); // Not the canonical encoding.
192            }
193            combined
194        }
195        LONG_FORM_LEN_FOUR_BYTES => {
196            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
197            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
198            let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
199            let length_byte_four = usize::from(input.read_byte().map_err(end_of_input_err)?);
200            let combined = (length_byte_one << 24)
201                | (length_byte_two << 16)
202                | (length_byte_three << 8)
203                | length_byte_four;
204            if combined <= LONG_FORM_LEN_THREE_BYTES_MAX {
205                return Err(Error::BadDer); // Not the canonical encoding.
206            }
207            combined
208        }
209        _ => {
210            return Err(Error::BadDer); // We don't support longer lengths.
211        }
212    };
213
214    if length >= size_limit {
215        return Err(Error::BadDer); // The length is larger than the caller accepts.
216    }
217
218    let inner = input.read_bytes(length).map_err(end_of_input_err)?;
219    Ok((tag, inner))
220}
221
222/// Prepend `bytes` with the given ASN.1 [`Tag`] and appropriately encoded length byte(s).
223/// Useful for "adding back" ASN.1 bytes to parsed content.
224#[cfg(feature = "alloc")]
225#[expect(clippy::as_conversions)]
226pub(crate) fn asn1_wrap(tag: Tag, bytes: &[u8]) -> Vec<u8> {
227    let len = bytes.len();
228    // The length is encoded differently depending on how many bytes there are
229    if len < usize::from(SHORT_FORM_LEN_MAX) {
230        // Short form: the length is encoded using a single byte
231        // Contents: Tag byte, single length byte, and passed bytes
232        let mut ret = Vec::with_capacity(2 + len);
233        ret.push(tag.into()); // Tag byte
234        ret.push(len as u8); // Single length byte
235        ret.extend_from_slice(bytes); // Passed bytes
236        ret
237    } else {
238        // Long form: The length is encoded using multiple bytes
239        // Contents: Tag byte, number-of-length-bytes byte, length bytes, and passed bytes
240        // The first byte indicates how many more bytes will be used to encode the length
241        // First, get a big-endian representation of the byte slice's length
242        let size = len.to_be_bytes();
243        // Find the number of leading empty bytes in that representation
244        // This will determine the smallest number of bytes we need to encode the length
245        let leading_zero_bytes = size
246            .iter()
247            .position(|&byte| byte != 0)
248            .unwrap_or(size.len());
249        assert!(leading_zero_bytes < size.len());
250        // Number of bytes used - number of not needed bytes = smallest number needed
251        let encoded_bytes = size.len() - leading_zero_bytes;
252        let mut ret = Vec::with_capacity(2 + encoded_bytes + len);
253        // Indicate this is a number-of-length-bytes byte by setting the high order bit
254        let number_of_length_bytes_byte = SHORT_FORM_LEN_MAX + encoded_bytes as u8;
255        ret.push(tag.into()); // Tag byte
256        ret.push(number_of_length_bytes_byte); // Number-of-length-bytes byte
257        ret.extend_from_slice(&size[leading_zero_bytes..]); // Length bytes
258        ret.extend_from_slice(bytes); // Passed bytes
259        ret
260    }
261}
262
263// Long-form DER encoded lengths of two bytes can express lengths up to the following limit.
264//
265// The upstream ring::io::der::read_tag_and_get_value() function limits itself to up to two byte
266// long-form DER lengths, and so this limit represents the maximum length that was possible to
267// read before the introduction of the read_tag_and_get_value_limited function.
268pub(crate) const TWO_BYTE_DER_SIZE: usize = LONG_FORM_LEN_TWO_BYTES_MAX;
269
270// The maximum size of a DER value that Webpki can support reading.
271//
272// Webpki limits itself to four byte long-form DER lengths, and so this limit represents
273// the maximum size tagged DER value that can be read for any purpose.
274pub(crate) const MAX_DER_SIZE: usize = LONG_FORM_LEN_FOUR_BYTES_MAX;
275
276// DER Tag identifiers have two forms:
277// * Low tag number form (for tags values in the range [0..30]
278// * High tag number form (for tag values in the range [31..]
279// We only support low tag number form.
280const HIGH_TAG_RANGE_START: u8 = 31;
281
282// DER length octets have two forms:
283// * Short form: 1 octet supporting lengths between 0 and 127.
284// * Long definite form: 2 to 127 octets, number of octets encoded into first octet.
285const SHORT_FORM_LEN_MAX: u8 = 128;
286
287// Leading octet for long definite form DER length expressed in second byte.
288const LONG_FORM_LEN_ONE_BYTE: u8 = 0x81;
289
290// Maximum size that can be expressed in a one byte long form len.
291const LONG_FORM_LEN_ONE_BYTE_MAX: usize = 0xff;
292
293// Leading octet for long definite form DER length expressed in subsequent two bytes.
294const LONG_FORM_LEN_TWO_BYTES: u8 = 0x82;
295
296// Maximum size that can be expressed in a two byte long form len.
297const LONG_FORM_LEN_TWO_BYTES_MAX: usize = 0xff_ff;
298
299// Leading octet for long definite form DER length expressed in subsequent three bytes.
300const LONG_FORM_LEN_THREE_BYTES: u8 = 0x83;
301
302// Maximum size that can be expressed in a three byte long form len.
303const LONG_FORM_LEN_THREE_BYTES_MAX: usize = 0xff_ff_ff;
304
305// Leading octet for long definite form DER length expressed in subsequent four bytes.
306const LONG_FORM_LEN_FOUR_BYTES: u8 = 0x84;
307
308// Maximum size that can be expressed in a four byte long form der len.
309const LONG_FORM_LEN_FOUR_BYTES_MAX: usize = 0xff_ff_ff_ff;
310
311// TODO: investigate taking decoder as a reference to reduce generated code
312// size.
313pub(crate) fn nested_of_mut<'a>(
314    input: &mut untrusted::Reader<'a>,
315    outer_tag: Tag,
316    inner_tag: Tag,
317    error: Error,
318    allow_empty: bool,
319    mut decoder: impl FnMut(&mut untrusted::Reader<'a>) -> Result<(), Error>,
320) -> Result<(), Error> {
321    nested(input, outer_tag, error.clone(), |outer| {
322        if allow_empty && outer.at_end() {
323            return Ok(());
324        }
325        loop {
326            nested(outer, inner_tag, error.clone(), |inner| decoder(inner))?;
327            if outer.at_end() {
328                break;
329            }
330        }
331        Ok(())
332    })
333}
334
335pub(crate) fn bit_string_with_no_unused_bits<'a>(
336    input: &mut untrusted::Reader<'a>,
337) -> Result<untrusted::Input<'a>, Error> {
338    nested(
339        input,
340        Tag::BitString,
341        Error::TrailingData(DerTypeId::BitString),
342        |value| {
343            let unused_bits_at_end = value.read_byte().map_err(|_| Error::BadDer)?;
344            if unused_bits_at_end != 0 {
345                return Err(Error::BadDer);
346            }
347            Ok(value.read_bytes_to_end())
348        },
349    )
350}
351
352pub(crate) struct BitStringFlags<'a> {
353    raw_bits: &'a [u8],
354}
355
356impl BitStringFlags<'_> {
357    pub(crate) fn bit_set(&self, bit: usize) -> bool {
358        let byte_index = bit / 8;
359        let bit_shift = 7 - (bit % 8);
360
361        if self.raw_bits.len() < (byte_index + 1) {
362            false
363        } else {
364            ((self.raw_bits[byte_index] >> bit_shift) & 1) != 0
365        }
366    }
367}
368
369// ASN.1 BIT STRING fields for sets of flags are encoded in DER with some peculiar details related
370// to padding. Notably this means we expect an indicator of the number of bits of padding, and then
371// the actual bit values. See this Stack Overflow discussion[0], and ITU X690-0207[1] Section 8.6
372// and Section 11.2 for more information.
373//
374// [0]: https://security.stackexchange.com/a/10396
375// [1]: https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
376pub(crate) fn bit_string_flags(input: untrusted::Input<'_>) -> Result<BitStringFlags<'_>, Error> {
377    input.read_all(Error::BadDer, |bit_string| {
378        // ITU X690-0207 11.2:
379        //   "The initial octet shall encode, as an unsigned binary integer with bit 1 as the least
380        //   significant bit, the number of unused bits in the final subsequent octet.
381        //   The number shall be in the range zero to seven"
382        let padding_bits = bit_string.read_byte().map_err(|_| Error::BadDer)?;
383        let raw_bits = bit_string.read_bytes_to_end().as_slice_less_safe();
384
385        // It's illegal to have more than 7 bits of padding. Similarly, if the raw bitflags
386        // are empty there should be no padding.
387        if padding_bits > 7 || (raw_bits.is_empty() && padding_bits != 0) {
388            return Err(Error::BadDer);
389        }
390
391        // If there are padding bits then the last bit of the last raw byte must be 0 or the
392        // distinguished encoding rules are not being followed.
393        let last_byte = raw_bits[raw_bits.len() - 1];
394        let padding_mask = (1 << padding_bits) - 1;
395
396        match padding_bits > 0 && (last_byte & padding_mask) != 0 {
397            true => Err(Error::BadDer),
398            false => Ok(BitStringFlags { raw_bits }),
399        }
400    })
401}
402
403impl<'a> FromDer<'a> for u8 {
404    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
405        match *nonnegative_integer(reader)?.as_slice_less_safe() {
406            [b] => Ok(b),
407            _ => Err(Error::BadDer),
408        }
409    }
410
411    const TYPE_ID: DerTypeId = DerTypeId::U8;
412}
413
414pub(crate) fn nonnegative_integer<'a>(
415    input: &mut untrusted::Reader<'a>,
416) -> Result<untrusted::Input<'a>, Error> {
417    let value = expect_tag(input, Tag::Integer)?;
418    match value
419        .as_slice_less_safe()
420        .split_first()
421        .ok_or(Error::BadDer)?
422    {
423        // Zero or leading zero.
424        (0, rest) => {
425            match rest.first() {
426                // Zero
427                None => Ok(value),
428                // Necessary leading zero.
429                Some(&second) if second & 0x80 == 0x80 => Ok(untrusted::Input::from(rest)),
430                // Unnecessary leading zero.
431                _ => Err(Error::BadDer),
432            }
433        }
434        // Positive value with no leading zero.
435        (first, _) if first & 0x80 == 0x00 => Ok(value),
436        // Negative value.
437        (_, _) => Err(Error::BadDer),
438    }
439}
440
441pub(crate) fn end_of_input_err(_: untrusted::EndOfInput) -> Error {
442    Error::BadDer
443}
444
445// Like mozilla::pkix, we accept the nonconformant explicit encoding of
446// the default value (false) for compatibility with real-world certificates.
447impl<'a> FromDer<'a> for bool {
448    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
449        if !reader.peek(Tag::Boolean.into()) {
450            return Ok(false);
451        }
452
453        nested(
454            reader,
455            Tag::Boolean,
456            Error::TrailingData(Self::TYPE_ID),
457            |input| match input.read_byte() {
458                Ok(0xff) => Ok(true),
459                Ok(0x00) => Ok(false),
460                _ => Err(Error::BadDer),
461            },
462        )
463    }
464
465    const TYPE_ID: DerTypeId = DerTypeId::Bool;
466}
467
468macro_rules! oid {
469    ( $first:expr, $second:expr, $( $tail:expr ),* ) =>
470    (
471        [(40 * $first) + $second, $( $tail ),*]
472    )
473}
474
475#[cfg(test)]
476mod tests {
477    use super::DerTypeId;
478    use std::prelude::v1::*;
479
480    #[cfg(feature = "alloc")]
481    #[test]
482    fn test_asn1_wrap() {
483        // Prepend stuff to `bytes` to put it in a DER SEQUENCE.
484        let wrap_in_sequence = |bytes: &[u8]| super::asn1_wrap(super::Tag::Sequence, bytes);
485
486        // Empty slice
487        assert_eq!(vec![0x30, 0x00], wrap_in_sequence(&[]));
488
489        // Small size
490        assert_eq!(
491            vec![0x30, 0x04, 0x00, 0x11, 0x22, 0x33],
492            wrap_in_sequence(&[0x00, 0x11, 0x22, 0x33])
493        );
494
495        // Medium size
496        let mut val = Vec::new();
497        val.resize(255, 0x12);
498        assert_eq!(
499            vec![0x30, 0x81, 0xff, 0x12, 0x12, 0x12],
500            wrap_in_sequence(&val)[..6]
501        );
502
503        // Large size
504        let mut val = Vec::new();
505        val.resize(4660, 0x12);
506        wrap_in_sequence(&val);
507        assert_eq!(
508            vec![0x30, 0x82, 0x12, 0x34, 0x12, 0x12],
509            wrap_in_sequence(&val)[..6]
510        );
511
512        // Huge size
513        let mut val = Vec::new();
514        val.resize(0xffff, 0x12);
515        let result = wrap_in_sequence(&val);
516        assert_eq!(vec![0x30, 0x82, 0xff, 0xff, 0x12, 0x12], result[..6]);
517        assert_eq!(result.len(), 0xffff + 4);
518
519        // Gigantic size
520        let mut val = Vec::new();
521        val.resize(0x100000, 0x12);
522        let result = wrap_in_sequence(&val);
523        assert_eq!(vec![0x30, 0x83, 0x10, 0x00, 0x00, 0x12, 0x12], result[..7]);
524        assert_eq!(result.len(), 0x100000 + 5);
525
526        // Ludicrous size
527        let mut val = Vec::new();
528        val.resize(0x1000000, 0x12);
529        let result = wrap_in_sequence(&val);
530        assert_eq!(
531            vec![0x30, 0x84, 0x01, 0x00, 0x00, 0x00, 0x12, 0x12],
532            result[..8]
533        );
534        assert_eq!(result.len(), 0x1000000 + 6);
535    }
536
537    #[test]
538    fn test_optional_boolean() {
539        use super::{Error, FromDer};
540
541        // Empty input results in false
542        assert!(!bool::from_der(&mut bytes_reader(&[])).unwrap());
543
544        // Optional, so another data type results in false
545        assert!(!bool::from_der(&mut bytes_reader(&[0x05, 0x00])).unwrap());
546
547        // Only 0x00 and 0xff are accepted values
548        assert_eq!(
549            Err(Error::BadDer),
550            bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0x42]))
551        );
552
553        // True
554        assert!(bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0xff])).unwrap());
555
556        // False
557        assert!(!bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0x00])).unwrap());
558    }
559
560    #[test]
561    fn test_bit_string_with_no_unused_bits() {
562        use super::{Error, bit_string_with_no_unused_bits};
563
564        // Unexpected type
565        assert_eq!(
566            bit_string_with_no_unused_bits(&mut bytes_reader(&[0x01, 0x01, 0xff])).unwrap_err(),
567            Error::TrailingData(DerTypeId::BitString),
568        );
569
570        // Unexpected nonexistent type
571        assert_eq!(
572            bit_string_with_no_unused_bits(&mut bytes_reader(&[0x42, 0xff, 0xff])).unwrap_err(),
573            Error::TrailingData(DerTypeId::BitString),
574        );
575
576        // Unexpected empty input
577        assert_eq!(
578            bit_string_with_no_unused_bits(&mut bytes_reader(&[])).unwrap_err(),
579            Error::TrailingData(DerTypeId::BitString),
580        );
581
582        // Valid input with non-zero unused bits
583        assert_eq!(
584            bit_string_with_no_unused_bits(&mut bytes_reader(&[0x03, 0x03, 0x04, 0x12, 0x34]))
585                .unwrap_err(),
586            Error::BadDer,
587        );
588
589        // Valid input
590        assert_eq!(
591            bit_string_with_no_unused_bits(&mut bytes_reader(&[0x03, 0x03, 0x00, 0x12, 0x34]))
592                .unwrap()
593                .as_slice_less_safe(),
594            &[0x12, 0x34],
595        );
596    }
597
598    fn bytes_reader(bytes: &[u8]) -> untrusted::Reader<'_> {
599        untrusted::Reader::new(untrusted::Input::from(bytes))
600    }
601
602    #[test]
603    fn read_tag_and_get_value_default_limit() {
604        use super::{Error, read_tag_and_get_value};
605
606        let inputs = &[
607            // DER with short-form length encoded as three bytes.
608            &[EXAMPLE_TAG, 0x83, 0xFF, 0xFF, 0xFF].as_slice(),
609            // DER with short-form length encoded as four bytes.
610            &[EXAMPLE_TAG, 0x84, 0xFF, 0xFF, 0xFF, 0xFF].as_slice(),
611        ];
612
613        for input in inputs {
614            let mut bytes = untrusted::Reader::new(untrusted::Input::from(input));
615            // read_tag_and_get_value should reject DER with encoded lengths larger than two
616            // bytes as BadDer.
617            assert!(matches!(
618                read_tag_and_get_value(&mut bytes),
619                Err(Error::BadDer)
620            ));
621        }
622    }
623
624    #[test]
625    fn read_tag_and_get_value_limited_high_form() {
626        use super::{Error, LONG_FORM_LEN_TWO_BYTES_MAX, read_tag_and_get_value_limited};
627
628        let mut bytes = untrusted::Reader::new(untrusted::Input::from(&[0xFF]));
629        // read_tag_and_get_value_limited_high_form should reject DER with "high tag number form" tags.
630        assert!(matches!(
631            read_tag_and_get_value_limited(&mut bytes, LONG_FORM_LEN_TWO_BYTES_MAX),
632            Err(Error::BadDer)
633        ));
634    }
635
636    #[test]
637    fn read_tag_and_get_value_limited_non_canonical() {
638        use super::{Error, LONG_FORM_LEN_TWO_BYTES_MAX, read_tag_and_get_value_limited};
639
640        let inputs = &[
641            // Two byte length, with expressed length < 128.
642            &[EXAMPLE_TAG, 0x81, 0x01].as_slice(),
643            // Three byte length, with expressed length < 256.
644            &[EXAMPLE_TAG, 0x82, 0x00, 0x01].as_slice(),
645            // Four byte length, with expressed length, < 65536.
646            &[EXAMPLE_TAG, 0x83, 0x00, 0x00, 0x01].as_slice(),
647            // Five byte length, with expressed length < 16777216.
648            &[EXAMPLE_TAG, 0x84, 0x00, 0x00, 0x00, 0x01].as_slice(),
649        ];
650
651        for input in inputs {
652            let mut bytes = untrusted::Reader::new(untrusted::Input::from(input));
653            // read_tag_and_get_value_limited should reject DER with non-canonical lengths.
654            assert!(matches!(
655                read_tag_and_get_value_limited(&mut bytes, LONG_FORM_LEN_TWO_BYTES_MAX),
656                Err(Error::BadDer)
657            ));
658        }
659    }
660
661    #[test]
662    #[cfg(feature = "alloc")]
663    fn read_tag_and_get_value_limited_limits() {
664        use super::{Error, read_tag_and_get_value_limited};
665
666        let short_input = &[0xFF];
667        let short_input_encoded = &[
668            &[EXAMPLE_TAG],
669            der_encode_length(short_input.len()).as_slice(),
670            short_input,
671        ]
672        .concat();
673
674        let long_input = &[1_u8; 65537];
675        let long_input_encoded = &[
676            &[EXAMPLE_TAG],
677            der_encode_length(long_input.len()).as_slice(),
678            long_input,
679        ]
680        .concat();
681
682        struct Testcase<'a> {
683            input: &'a [u8],
684            limit: usize,
685            err: Option<Error>,
686        }
687
688        let testcases = &[
689            Testcase {
690                input: short_input_encoded,
691                limit: 1,
692                err: Some(Error::BadDer),
693            },
694            Testcase {
695                input: short_input_encoded,
696                limit: short_input_encoded.len() + 1,
697                err: None,
698            },
699            Testcase {
700                input: long_input_encoded,
701                limit: long_input.len(),
702                err: Some(Error::BadDer),
703            },
704            Testcase {
705                input: long_input_encoded,
706                limit: long_input.len() + 1,
707                err: None,
708            },
709        ];
710
711        for tc in testcases {
712            let mut bytes = untrusted::Reader::new(untrusted::Input::from(tc.input));
713
714            let res = read_tag_and_get_value_limited(&mut bytes, tc.limit);
715            match &tc.err {
716                None => assert!(res.is_ok()),
717                Some(e) => {
718                    let actual = res.unwrap_err();
719                    assert_eq!(&actual, e)
720                }
721            }
722        }
723    }
724
725    #[expect(clippy::as_conversions)] // infallible.
726    const EXAMPLE_TAG: u8 = super::Tag::Sequence as u8;
727
728    #[cfg(feature = "alloc")]
729    #[expect(clippy::as_conversions)] // test code.
730    fn der_encode_length(length: usize) -> Vec<u8> {
731        if length < 128 {
732            vec![length as u8]
733        } else {
734            let mut encoded: Vec<u8> = Vec::new();
735            let mut remaining_length = length;
736
737            while remaining_length > 0 {
738                let byte = (remaining_length & 0xFF) as u8;
739                encoded.insert(0, byte);
740                remaining_length >>= 8;
741            }
742
743            let length_octet = encoded.len() as u8 | 0x80;
744            encoded.insert(0, length_octet);
745
746            encoded
747        }
748    }
749
750    #[test]
751    fn misencoded_bit_string_flags() {
752        use super::{Error, bit_string_flags};
753
754        let bad_padding_example = untrusted::Input::from(&[
755            0x08, // 8 bit of padding (illegal!).
756            0x06, // 1 byte of bit flags asserting bits 5 and 6.
757        ]);
758        assert!(matches!(
759            bit_string_flags(bad_padding_example),
760            Err(Error::BadDer)
761        ));
762
763        let bad_padding_example = untrusted::Input::from(&[
764            0x01, // 1 bit of padding.
765                 // No flags value (illegal with padding!).
766        ]);
767        assert!(matches!(
768            bit_string_flags(bad_padding_example),
769            Err(Error::BadDer)
770        ));
771    }
772
773    #[test]
774    fn valid_bit_string_flags() {
775        use super::bit_string_flags;
776
777        let example_key_usage = untrusted::Input::from(&[
778            0x01, // 1 bit of padding.
779            0x06, // 1 byte of bit flags asserting bits 5 and 6.
780        ]);
781        let res = bit_string_flags(example_key_usage).unwrap();
782
783        assert!(!res.bit_set(0));
784        assert!(!res.bit_set(1));
785        assert!(!res.bit_set(2));
786        assert!(!res.bit_set(3));
787        assert!(!res.bit_set(4));
788        // NB: Bits 5 and 6 should be set.
789        assert!(res.bit_set(5));
790        assert!(res.bit_set(6));
791        assert!(!res.bit_set(7));
792        assert!(!res.bit_set(8));
793        // Bits outside the range of values shouldn't be considered set.
794        assert!(!res.bit_set(256));
795    }
796
797    #[test]
798    fn test_small_nonnegative_integer() {
799        use super::{Error, FromDer, Tag};
800
801        for value in 0..=127 {
802            let data = [Tag::Integer.into(), 1, value];
803            let mut rd = untrusted::Reader::new(untrusted::Input::from(&data));
804            assert_eq!(u8::from_der(&mut rd), Ok(value),);
805        }
806
807        for value in 128..=255 {
808            let data = [Tag::Integer.into(), 2, 0x00, value];
809            let mut rd = untrusted::Reader::new(untrusted::Input::from(&data));
810            assert_eq!(u8::from_der(&mut rd), Ok(value),);
811        }
812
813        // not an integer
814        assert_eq!(
815            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
816                Tag::Sequence.into(),
817                1,
818                1
819            ]))),
820            Err(Error::BadDer)
821        );
822
823        // negative
824        assert_eq!(
825            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
826                Tag::Integer.into(),
827                1,
828                0xff
829            ]))),
830            Err(Error::BadDer)
831        );
832
833        // positive but too large
834        assert_eq!(
835            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
836                Tag::Integer.into(),
837                2,
838                0x01,
839                0x00
840            ]))),
841            Err(Error::BadDer)
842        );
843
844        // unnecessary leading zero
845        assert_eq!(
846            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
847                Tag::Integer.into(),
848                2,
849                0x00,
850                0x05
851            ]))),
852            Err(Error::BadDer)
853        );
854
855        // truncations
856        assert_eq!(
857            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[]))),
858            Err(Error::BadDer)
859        );
860
861        assert_eq!(
862            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
863                Tag::Integer.into(),
864            ]))),
865            Err(Error::BadDer)
866        );
867
868        assert_eq!(
869            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
870                Tag::Integer.into(),
871                1,
872            ]))),
873            Err(Error::BadDer)
874        );
875
876        assert_eq!(
877            u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
878                Tag::Integer.into(),
879                2,
880                0
881            ]))),
882            Err(Error::BadDer)
883        );
884    }
885}