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