Skip to main content

webpki/
der.rs

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