Coverage Report

Created: 2025-11-16 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rustls-webpki-0.102.8/src/der.rs
Line
Count
Source
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")]
16
use alloc::vec::Vec;
17
use core::marker::PhantomData;
18
19
use crate::{error::DerTypeId, Error};
20
21
#[derive(Debug)]
22
pub struct DerIterator<'a, T> {
23
    reader: untrusted::Reader<'a>,
24
    marker: PhantomData<T>,
25
}
26
27
impl<'a, T> DerIterator<'a, T> {
28
    /// [`DerIterator`] will consume all of the bytes in `input` reading values of type `T`.
29
0
    pub(crate) fn new(input: untrusted::Input<'a>) -> Self {
30
0
        Self {
31
0
            reader: untrusted::Reader::new(input),
32
0
            marker: PhantomData,
33
0
        }
34
0
    }
Unexecuted instantiation: <webpki::der::DerIterator<webpki::cert::CrlDistributionPoint>>::new
Unexecuted instantiation: <webpki::der::DerIterator<webpki::subject_name::verify::GeneralName>>::new
Unexecuted instantiation: <webpki::der::DerIterator<webpki::crl::types::BorrowedRevokedCert>>::new
35
}
36
37
impl<'a, T: FromDer<'a>> Iterator for DerIterator<'a, T> {
38
    type Item = Result<T, Error>;
39
40
0
    fn next(&mut self) -> Option<Self::Item> {
41
0
        (!self.reader.at_end()).then(|| T::from_der(&mut self.reader))
Unexecuted instantiation: <webpki::der::DerIterator<webpki::cert::CrlDistributionPoint> as core::iter::traits::iterator::Iterator>::next::{closure#0}
Unexecuted instantiation: <webpki::der::DerIterator<webpki::subject_name::verify::GeneralName> as core::iter::traits::iterator::Iterator>::next::{closure#0}
Unexecuted instantiation: <webpki::der::DerIterator<webpki::crl::types::BorrowedRevokedCert> as core::iter::traits::iterator::Iterator>::next::{closure#0}
42
0
    }
Unexecuted instantiation: <webpki::der::DerIterator<webpki::cert::CrlDistributionPoint> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <webpki::der::DerIterator<webpki::subject_name::verify::GeneralName> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <webpki::der::DerIterator<webpki::crl::types::BorrowedRevokedCert> as core::iter::traits::iterator::Iterator>::next
43
}
44
45
pub(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
52
0
pub(crate) fn read_all<'a, T: FromDer<'a>>(input: untrusted::Input<'a>) -> Result<T, Error> {
53
0
    input.read_all(Error::TrailingData(T::TYPE_ID), T::from_der)
54
0
}
Unexecuted instantiation: webpki::der::read_all::<webpki::signed_data::SubjectPublicKeyInfo>
Unexecuted instantiation: webpki::der::read_all::<webpki::subject_name::verify::GeneralName>
Unexecuted instantiation: webpki::der::read_all::<webpki::crl::types::RevocationReason>
Unexecuted instantiation: webpki::der::read_all::<webpki::crl::types::BorrowedCertRevocationList>
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)]
60
pub(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
77
pub(crate) const CONSTRUCTED: u8 = 0x20;
78
pub(crate) const CONTEXT_SPECIFIC: u8 = 0x80;
79
80
impl From<Tag> for usize {
81
    #[allow(clippy::as_conversions)]
82
0
    fn from(tag: Tag) -> Self {
83
0
        tag as Self
84
0
    }
85
}
86
87
impl From<Tag> for u8 {
88
    #[allow(clippy::as_conversions)]
89
0
    fn from(tag: Tag) -> Self {
90
0
        tag as Self
91
0
    } // XXX: narrowing conversion.
92
}
93
94
#[inline(always)]
95
0
pub(crate) fn expect_tag_and_get_value_limited<'a>(
96
0
    input: &mut untrusted::Reader<'a>,
97
0
    tag: Tag,
98
0
    size_limit: usize,
99
0
) -> Result<untrusted::Input<'a>, Error> {
100
0
    let (actual_tag, inner) = read_tag_and_get_value_limited(input, size_limit)?;
101
0
    if usize::from(tag) != usize::from(actual_tag) {
102
0
        return Err(Error::BadDer);
103
0
    }
104
0
    Ok(inner)
105
0
}
106
107
0
pub(crate) fn nested_limited<'a, R>(
108
0
    input: &mut untrusted::Reader<'a>,
109
0
    tag: Tag,
110
0
    error: Error,
111
0
    decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
112
0
    size_limit: usize,
113
0
) -> Result<R, Error> {
114
0
    expect_tag_and_get_value_limited(input, tag, size_limit)
115
0
        .map_err(|_| error)?
116
0
        .read_all(error, decoder)
117
0
}
Unexecuted instantiation: webpki::der::nested_limited::<rustls_pki_types::TrustAnchor, webpki::trust_anchor::extract_trust_anchor_from_v1_cert_der::{closure#0}::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<rustls_pki_types::TrustAnchor, webpki::trust_anchor::extract_trust_anchor_from_v1_cert_der::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<rustls_pki_types::UnixTime, <rustls_pki_types::UnixTime as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<webpki::cert::CrlDistributionPoint, <webpki::cert::CrlDistributionPoint as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<untrusted::input::Input, webpki::der::bit_string_with_no_unused_bits::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<webpki::crl::types::BorrowedRevokedCert, <webpki::crl::types::BorrowedRevokedCert as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(untrusted::input::Input, webpki::signed_data::SignedData), <webpki::cert::Cert>::from_der::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(untrusted::input::Input, webpki::signed_data::SignedData), <webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<bool, <bool as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), webpki::der::nested_of_mut<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), webpki::der::nested_of_mut<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), webpki::der::nested_of_mut<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), webpki::der::nested_of_mut<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), <webpki::cert::Cert>::from_der::{closure#1}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), <webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), <webpki::crl::types::BorrowedRevokedCert as webpki::der::FromDer>::from_der::{closure#0}::{closure#1}>
Unexecuted instantiation: webpki::der::nested_limited::<(), <webpki::crl::types::IssuingDistributionPoint>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested_limited::<(), webpki::cert::version3::{closure#0}>
118
119
// TODO: investigate taking decoder as a reference to reduce generated code
120
// size.
121
0
pub(crate) fn nested<'a, R>(
122
0
    input: &mut untrusted::Reader<'a>,
123
0
    tag: Tag,
124
0
    error: Error,
125
0
    decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
126
0
) -> Result<R, Error> {
127
0
    nested_limited(input, tag, error, decoder, TWO_BYTE_DER_SIZE)
128
0
}
Unexecuted instantiation: webpki::der::nested::<rustls_pki_types::TrustAnchor, webpki::trust_anchor::extract_trust_anchor_from_v1_cert_der::{closure#0}::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<rustls_pki_types::TrustAnchor, webpki::trust_anchor::extract_trust_anchor_from_v1_cert_der::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<rustls_pki_types::UnixTime, <rustls_pki_types::UnixTime as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<webpki::cert::CrlDistributionPoint, <webpki::cert::CrlDistributionPoint as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<untrusted::input::Input, webpki::der::bit_string_with_no_unused_bits::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<webpki::crl::types::BorrowedRevokedCert, <webpki::crl::types::BorrowedRevokedCert as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(untrusted::input::Input, webpki::signed_data::SignedData), <webpki::cert::Cert>::from_der::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<bool, <bool as webpki::der::FromDer>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), webpki::der::nested_of_mut<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), webpki::der::nested_of_mut<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), webpki::der::nested_of_mut<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), webpki::der::nested_of_mut<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), <webpki::cert::Cert>::from_der::{closure#1}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), <webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), <webpki::crl::types::BorrowedRevokedCert as webpki::der::FromDer>::from_der::{closure#0}::{closure#1}>
Unexecuted instantiation: webpki::der::nested::<(), <webpki::crl::types::IssuingDistributionPoint>::from_der::{closure#0}>
Unexecuted instantiation: webpki::der::nested::<(), webpki::cert::version3::{closure#0}>
129
130
0
pub(crate) fn expect_tag<'a>(
131
0
    input: &mut untrusted::Reader<'a>,
132
0
    tag: Tag,
133
0
) -> Result<untrusted::Input<'a>, Error> {
134
0
    let (actual_tag, value) = read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)?;
135
0
    if usize::from(tag) != usize::from(actual_tag) {
136
0
        return Err(Error::BadDer);
137
0
    }
138
139
0
    Ok(value)
140
0
}
141
142
#[inline(always)]
143
0
pub(crate) fn read_tag_and_get_value<'a>(
144
0
    input: &mut untrusted::Reader<'a>,
145
0
) -> Result<(u8, untrusted::Input<'a>), Error> {
146
0
    read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)
147
0
}
148
149
#[inline(always)]
150
0
pub(crate) fn read_tag_and_get_value_limited<'a>(
151
0
    input: &mut untrusted::Reader<'a>,
152
0
    size_limit: usize,
153
0
) -> Result<(u8, untrusted::Input<'a>), Error> {
154
0
    let tag = input.read_byte().map_err(end_of_input_err)?;
155
0
    if (tag & HIGH_TAG_RANGE_START) == HIGH_TAG_RANGE_START {
156
0
        return Err(Error::BadDer); // High tag number form is not allowed.
157
0
    }
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
0
    let length = match input.read_byte().map_err(end_of_input_err)? {
163
0
        n if (n & SHORT_FORM_LEN_MAX) == 0 => usize::from(n),
164
        LONG_FORM_LEN_ONE_BYTE => {
165
0
            let length_byte = input.read_byte().map_err(end_of_input_err)?;
166
0
            if length_byte < SHORT_FORM_LEN_MAX {
167
0
                return Err(Error::BadDer); // Not the canonical encoding.
168
0
            }
169
0
            usize::from(length_byte)
170
        }
171
        LONG_FORM_LEN_TWO_BYTES => {
172
0
            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
173
0
            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
174
0
            let combined = (length_byte_one << 8) | length_byte_two;
175
0
            if combined <= LONG_FORM_LEN_ONE_BYTE_MAX {
176
0
                return Err(Error::BadDer); // Not the canonical encoding.
177
0
            }
178
0
            combined
179
        }
180
        LONG_FORM_LEN_THREE_BYTES => {
181
0
            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
182
0
            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
183
0
            let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
184
0
            let combined = (length_byte_one << 16) | (length_byte_two << 8) | length_byte_three;
185
0
            if combined <= LONG_FORM_LEN_TWO_BYTES_MAX {
186
0
                return Err(Error::BadDer); // Not the canonical encoding.
187
0
            }
188
0
            combined
189
        }
190
        LONG_FORM_LEN_FOUR_BYTES => {
191
0
            let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
192
0
            let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
193
0
            let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
194
0
            let length_byte_four = usize::from(input.read_byte().map_err(end_of_input_err)?);
195
0
            let combined = (length_byte_one << 24)
196
0
                | (length_byte_two << 16)
197
0
                | (length_byte_three << 8)
198
0
                | length_byte_four;
199
0
            if combined <= LONG_FORM_LEN_THREE_BYTES_MAX {
200
0
                return Err(Error::BadDer); // Not the canonical encoding.
201
0
            }
202
0
            combined
203
        }
204
        _ => {
205
0
            return Err(Error::BadDer); // We don't support longer lengths.
206
        }
207
    };
208
209
0
    if length >= size_limit {
210
0
        return Err(Error::BadDer); // The length is larger than the caller accepts.
211
0
    }
212
213
0
    let inner = input.read_bytes(length).map_err(end_of_input_err)?;
214
0
    Ok((tag, inner))
215
0
}
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)]
221
0
pub(crate) fn asn1_wrap(tag: Tag, bytes: &[u8]) -> Vec<u8> {
222
0
    let len = bytes.len();
223
    // The length is encoded differently depending on how many bytes there are
224
0
    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
0
        let mut ret = Vec::with_capacity(2 + len);
228
0
        ret.push(tag.into()); // Tag byte
229
0
        ret.push(len as u8); // Single length byte
230
0
        ret.extend_from_slice(bytes); // Passed bytes
231
0
        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
0
        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
0
        let leading_zero_bytes = size
241
0
            .iter()
242
0
            .position(|&byte| byte != 0)
243
0
            .unwrap_or(size.len());
244
0
        assert!(leading_zero_bytes < size.len());
245
        // Number of bytes used - number of not needed bytes = smallest number needed
246
0
        let encoded_bytes = size.len() - leading_zero_bytes;
247
0
        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
0
        let number_of_length_bytes_byte = SHORT_FORM_LEN_MAX + encoded_bytes as u8;
250
0
        ret.push(tag.into()); // Tag byte
251
0
        ret.push(number_of_length_bytes_byte); // Number-of-length-bytes byte
252
0
        ret.extend_from_slice(&size[leading_zero_bytes..]); // Length bytes
253
0
        ret.extend_from_slice(bytes); // Passed bytes
254
0
        ret
255
    }
256
0
}
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.
263
pub(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.
269
pub(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.
275
const 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.
280
const SHORT_FORM_LEN_MAX: u8 = 128;
281
282
// Leading octet for long definite form DER length expressed in second byte.
283
const LONG_FORM_LEN_ONE_BYTE: u8 = 0x81;
284
285
// Maximum size that can be expressed in a one byte long form len.
286
const LONG_FORM_LEN_ONE_BYTE_MAX: usize = 0xff;
287
288
// Leading octet for long definite form DER length expressed in subsequent two bytes.
289
const LONG_FORM_LEN_TWO_BYTES: u8 = 0x82;
290
291
// Maximum size that can be expressed in a two byte long form len.
292
const LONG_FORM_LEN_TWO_BYTES_MAX: usize = 0xff_ff;
293
294
// Leading octet for long definite form DER length expressed in subsequent three bytes.
295
const LONG_FORM_LEN_THREE_BYTES: u8 = 0x83;
296
297
// Maximum size that can be expressed in a three byte long form len.
298
const 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.
301
const LONG_FORM_LEN_FOUR_BYTES: u8 = 0x84;
302
303
// Maximum size that can be expressed in a four byte long form der len.
304
const 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.
308
0
pub(crate) fn nested_of_mut<'a>(
309
0
    input: &mut untrusted::Reader<'a>,
310
0
    outer_tag: Tag,
311
0
    inner_tag: Tag,
312
0
    error: Error,
313
0
    mut decoder: impl FnMut(&mut untrusted::Reader<'a>) -> Result<(), Error>,
314
0
) -> Result<(), Error> {
315
0
    nested(input, outer_tag, error, |outer| {
316
        loop {
317
0
            nested(outer, inner_tag, error, |inner| decoder(inner))?;
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}::{closure#0}
318
0
            if outer.at_end() {
319
0
                break;
320
0
            }
321
        }
322
0
        Ok(())
323
0
    })
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>::{closure#0}
324
0
}
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::cert::Cert>::from_der::{closure#1}::{closure#0}::{closure#0}>
Unexecuted instantiation: webpki::der::nested_of_mut::<<webpki::crl::types::BorrowedCertRevocationList as webpki::der::FromDer>::from_der::{closure#1}::{closure#0}::{closure#0}>
325
326
0
pub(crate) fn bit_string_with_no_unused_bits<'a>(
327
0
    input: &mut untrusted::Reader<'a>,
328
0
) -> Result<untrusted::Input<'a>, Error> {
329
0
    nested(
330
0
        input,
331
0
        Tag::BitString,
332
0
        Error::TrailingData(DerTypeId::BitString),
333
0
        |value| {
334
0
            let unused_bits_at_end = value.read_byte().map_err(|_| Error::BadDer)?;
335
0
            if unused_bits_at_end != 0 {
336
0
                return Err(Error::BadDer);
337
0
            }
338
0
            Ok(value.read_bytes_to_end())
339
0
        },
340
    )
341
0
}
342
343
pub(crate) struct BitStringFlags<'a> {
344
    raw_bits: &'a [u8],
345
}
346
347
impl<'a> BitStringFlags<'a> {
348
0
    pub(crate) fn bit_set(&self, bit: usize) -> bool {
349
0
        let byte_index = bit / 8;
350
0
        let bit_shift = 7 - (bit % 8);
351
352
0
        if self.raw_bits.len() < (byte_index + 1) {
353
0
            false
354
        } else {
355
0
            ((self.raw_bits[byte_index] >> bit_shift) & 1) != 0
356
        }
357
0
    }
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
367
0
pub(crate) fn bit_string_flags(input: untrusted::Input<'_>) -> Result<BitStringFlags<'_>, Error> {
368
0
    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
0
        let padding_bits = bit_string.read_byte().map_err(|_| Error::BadDer)?;
374
0
        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
0
        if padding_bits > 7 || (raw_bits.is_empty() && padding_bits != 0) {
379
0
            return Err(Error::BadDer);
380
0
        }
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
0
        let last_byte = raw_bits[raw_bits.len() - 1];
385
0
        let padding_mask = (1 << padding_bits) - 1;
386
387
0
        match padding_bits > 0 && (last_byte & padding_mask) != 0 {
388
0
            true => Err(Error::BadDer),
389
0
            false => Ok(BitStringFlags { raw_bits }),
390
        }
391
0
    })
392
0
}
393
394
impl<'a> FromDer<'a> for u8 {
395
0
    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
396
0
        match *nonnegative_integer(reader)?.as_slice_less_safe() {
397
0
            [b] => Ok(b),
398
0
            _ => Err(Error::BadDer),
399
        }
400
0
    }
401
402
    const TYPE_ID: DerTypeId = DerTypeId::U8;
403
}
404
405
0
pub(crate) fn nonnegative_integer<'a>(
406
0
    input: &mut untrusted::Reader<'a>,
407
0
) -> Result<untrusted::Input<'a>, Error> {
408
0
    let value = expect_tag(input, Tag::Integer)?;
409
0
    match value
410
0
        .as_slice_less_safe()
411
0
        .split_first()
412
0
        .ok_or(Error::BadDer)?
413
    {
414
        // Zero or leading zero.
415
0
        (0, rest) => {
416
0
            match rest.first() {
417
                // Zero
418
0
                None => Ok(value),
419
                // Necessary leading zero.
420
0
                Some(&second) if second & 0x80 == 0x80 => Ok(untrusted::Input::from(rest)),
421
                // Unnecessary leading zero.
422
0
                _ => Err(Error::BadDer),
423
            }
424
        }
425
        // Positive value with no leading zero.
426
0
        (first, _) if first & 0x80 == 0x00 => Ok(value),
427
        // Negative value.
428
0
        (_, _) => Err(Error::BadDer),
429
    }
430
0
}
431
432
0
pub(crate) fn end_of_input_err(_: untrusted::EndOfInput) -> Error {
433
0
    Error::BadDer
434
0
}
435
436
// Like mozilla::pkix, we accept the nonconformant explicit encoding of
437
// the default value (false) for compatibility with real-world certificates.
438
impl<'a> FromDer<'a> for bool {
439
0
    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
440
0
        if !reader.peek(Tag::Boolean.into()) {
441
0
            return Ok(false);
442
0
        }
443
444
0
        nested(
445
0
            reader,
446
0
            Tag::Boolean,
447
0
            Error::TrailingData(Self::TYPE_ID),
448
0
            |input| match input.read_byte() {
449
0
                Ok(0xff) => Ok(true),
450
0
                Ok(0x00) => Ok(false),
451
0
                _ => Err(Error::BadDer),
452
0
            },
453
        )
454
0
    }
455
456
    const TYPE_ID: DerTypeId = DerTypeId::Bool;
457
}
458
459
macro_rules! oid {
460
    ( $first:expr, $second:expr, $( $tail:expr ),* ) =>
461
    (
462
        [(40 * $first) + $second, $( $tail ),*]
463
    )
464
}
465
466
#[cfg(test)]
467
mod 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
}