Debian Codegraph @

src/length/indefinite.rs

raw symbols SCIP
1 //! Support for indefinite lengths as used by ASN.1 BER and described in X.690 Section 8.1.3.6:
2 //!
3 //! > 8.1.3.6 For the indefinite form, the length octets indicate that the
4 //! > contents octets are terminated by end-of-contents
5 //! > octets (see 8.1.5), and shall consist of a single octet.
6 //! >
7 //! > 8.1.3.6.1 The single octet shall have bit 8 set to one, and bits 7 to
8 //! > 1 set to zero.
9 //! >
10 //! > 8.1.3.6.2 If this form of length is used, then end-of-contents octets
11 //! > (see 8.1.5) shall be present in the encoding following the contents
12 //! > octets.
13 //! >
14 //! > [...]
15 //! >
16 //! > 8.1.5 End-of-contents octets
17 //! > The end-of-contents octets shall be present if the length is encoded as specified in 8.1.3.6,
18 //! > otherwise they shall not be present.
19 //! >
20 //! > The end-of-contents octets shall consist of two zero octets.
21
22 use crate::{Decode, ErrorKind, Header, Length, Reader};
23
24 #[cfg(feature = "alloc")]
25 use crate::Tag;
26
27 #[cfg(feature = "alloc")]
28 use alloc::vec::Vec;
29
30 /// The end-of-contents octets can be considered as the encoding of a value whose tag is
31 /// universal class, whose form is primitive, whose number of the tag is zero, and whose
32 /// contents are absent.
33 const EOC_TAG: u8 = 0x00;
34
35 /// Decode TLV records until an end-of-contents marker (`00 00`) is found, computing the
36 /// resulting length based on the amount of data decoded.
37 pub(super) fn decode_indefinite_length<'a>(reader: &mut impl Reader<'a>) -> crate::Result<Length> {
38 let start_pos = reader.position();
39
40 loop {
41 // Look for the end-of-contents marker
42 if reader.peek_byte() == Some(EOC_TAG) {
43 read_eoc(reader)?;
44
45 // Compute how much we read and flag the decoded length as indefinite
46 let mut ret = (reader.position() - start_pos)?;
47 ret.indefinite = true;
48 return Ok(ret);
49 }
50
51 let header = Header::decode(reader)?;
52 reader.drain(header.length())?;
53 }
54 }
55
56 /// Read an expected end-of-contents (EOC) marker: `00 00`.
57 ///
58 /// # Errors
59 ///
60 /// - Returns `ErrorKind::IndefiniteLength` if the EOC marker isn't present as expected.
61 pub(crate) fn read_eoc<'a>(reader: &mut impl Reader<'a>) -> crate::Result<()> {
62 for _ in 0..Length::EOC_LEN.inner as usize {
63 if reader.read_byte()? != 0 {
64 return Err(reader.error(ErrorKind::IndefiniteLength));
65 }
66 }
67
68 Ok(())
69 }
70
71 /// Read a constructed value into a [`Vec`], removing intermediate headers and assembling the result
72 /// into a single contiguous bytestring.
73 ///
74 /// The end-of-content marker is not handled by this function. Instead, it's expected for this to
75 /// be called with a nested reader which ends immediately before the EOC.
76 #[cfg(feature = "alloc")]
77 pub(crate) fn read_constructed_vec<'r, R: Reader<'r>>(
78 reader: &mut R,
79 length: Length,
80 inner_tag: Tag,
81 ) -> crate::Result<Vec<u8>> {
82 if !length.is_indefinite() {
83 return Err(reader.error(ErrorKind::IndefiniteLength));
84 }
85
86 let mut bytes = Vec::with_capacity(length.try_into()?);
87 let mut offset = 0;
88
89 while !reader.is_finished() {
90 let h = Header::decode(reader)?;
91 h.tag().assert_eq(inner_tag)?;
92
93 // This constructed string is ‘recursively constructed’
94 // as one of its segments is itself encoded with
95 // constructed, indefinite-length method.
96 // This is currently chosen to be unsupported.
97 //
98 // See discussion:
99 // - https://github.com/RustCrypto/formats/issues/779#issuecomment-3049589340
100 if h.length().is_indefinite() {
101 return Err(reader.error(ErrorKind::IndefiniteLength));
102 }
103
104 // Add enough zeroes into the `Vec` to store the chunk
105 let l = usize::try_from(h.length())?;
106 bytes.extend(core::iter::repeat_n(0, l));
107 reader.read_into(&mut bytes[offset..(offset + l)])?;
108 offset += l;
109 }
110
111 Ok(bytes)
112 }
113
114 #[cfg(test)]
115 #[allow(clippy::unwrap_used)]
116 mod tests {
117 use crate::{Decode, EncodingRules, Length, Reader, SliceReader, Tag};
118 use hex_literal::hex;
119
120 #[test]
121 fn decode() {
122 /// Length of example in octets.
123 const EXAMPLE_LEN: usize = 68;
124
125 /// Test vector from: <https://github.com/RustCrypto/formats/issues/779#issuecomment-2902948789>
126 ///
127 /// Notably this example contains nested indefinite lengths to ensure the decoder handles
128 /// them correctly.
129 const EXAMPLE_BER: [u8; EXAMPLE_LEN] = hex!(
130 "30 80 06 09 2A 86 48 86 F7 0D 01 07 01
131 30 1D 06 09 60 86 48 01 65 03 04 01 2A 04 10 37
132 34 3D F1 47 0D F6 25 EE B6 F4 BF D2 F1 AC C3 A0
133 80 04 10 CC 74 AD F6 5D 97 3C 8B 72 CD 51 E1 B9
134 27 F0 F0 00 00 00 00"
135 );
136
137 // Ensure the indefinite bit isn't set when decoding DER
138 assert!(!Length::from_der(&[0x00]).unwrap().indefinite);
139
140 let mut reader =
141 SliceReader::new_with_encoding_rules(&EXAMPLE_BER, EncodingRules::Ber).unwrap();
142
143 // Decode initial tag of the message, leaving the reader at the length
144 let tag = Tag::decode(&mut reader).unwrap();
145 assert_eq!(tag, Tag::Sequence);
146
147 // Decode indefinite length
148 let length = Length::decode(&mut reader).unwrap();
149 assert!(length.is_indefinite());
150
151 // Decoding the length should leave the position at the end of the indefinite length octet
152 let pos = usize::try_from(reader.position()).unwrap();
153 assert_eq!(pos, 2);
154
155 // The first two bytes are the header and the rest is the length of the message.
156 // The last four are two end-of-content markers (2 * 2 bytes).
157 assert_eq!(usize::try_from(length).unwrap(), EXAMPLE_LEN - pos);
158
159 // Read OID
160 reader.tlv_bytes().unwrap();
161 // Read SEQUENCE
162 reader.tlv_bytes().unwrap();
163
164 // We're now at the next indefinite length record
165 let tag = Tag::decode(&mut reader).unwrap();
166 assert_eq!(
167 tag,
168 Tag::ContextSpecific {
169 constructed: true,
170 number: 0u32.into()
171 }
172 );
173
174 // Parse the inner indefinite length
175 let length = Length::decode(&mut reader).unwrap();
176 assert!(length.is_indefinite());
177 assert_eq!(usize::try_from(length).unwrap(), 20);
178 }
179 }