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