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