Debian Codegraph @

src/length.rs

raw symbols SCIP
1 //! Length calculations for encoded ASN.1 DER values
2
3 #[cfg(feature = "ber")]
4 pub(crate) mod indefinite;
5
6 /// Octet identifying an indefinite length as described in X.690 Section
7 /// 8.1.3.6.1:
8 ///
9 /// > The single octet shall have bit 8 set to one, and bits 7 to
10 /// > 1 set to zero.
11 pub(super) const INDEFINITE_LENGTH_OCTET: u8 = 0b10000000; // 0x80
12
13 use crate::{Decode, DerOrd, Encode, EncodingRules, Error, ErrorKind, Reader, Result, Tag, Writer};
14 use core::{
15 cmp::Ordering,
16 fmt,
17 ops::{Add, Sub},
18 };
19
20 /// ASN.1-encoded length.
21 ///
22 /// ## Examples
23 /// ```
24 /// use der::{Decode, Length, SliceReader};
25 ///
26 /// let mut reader = SliceReader::new(&[0x82, 0xAA, 0xBB]).unwrap();
27 /// let length = Length::decode(&mut reader).expect("valid length");
28 ///
29 /// assert_eq!(length, Length::new(0xAABB));
30 /// ```
31 ///
32 /// 5-byte lengths are supported:
33 /// ```
34 /// use der::{Encode, Length};
35 /// let length = Length::new(0x10000000);
36 ///
37 /// assert_eq!(length.encoded_len(), Ok(Length::new(5)));
38 /// ```
39 ///
40 /// Invalid lengths produce an error:
41 /// ```
42 /// use der::{Decode, Length, SliceReader};
43 ///
44 /// let mut reader = SliceReader::new(&[0x81, 0x7F]).unwrap();
45 ///
46 /// Length::decode(&mut reader).expect_err("non-canonical length should be rejected");
47 /// ```
48 #[derive(Copy, Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
49 pub struct Length {
50 /// Inner length as a `u32`. Note that the decoder and encoder also support a maximum length
51 /// of 32-bits.
52 inner: u32,
53
54 /// Flag bit which specifies whether the length was indeterminate when decoding ASN.1 BER.
55 ///
56 /// This should always be false when working with DER.
57 #[cfg(feature = "ber")]
58 indefinite: bool,
59 }
60
61 impl Length {
62 /// Length of `0`
63 pub const ZERO: Self = Self::new(0);
64
65 /// Length of `1`
66 pub const ONE: Self = Self::new(1);
67
68 /// Maximum length (`u32::MAX`).
69 pub const MAX: Self = Self::new(u32::MAX);
70
71 /// Length of end-of-content octets (i.e. `00 00`).
72 #[cfg(feature = "ber")]
73 pub(crate) const EOC_LEN: Self = Self::new(2);
74
75 /// Create a new [`Length`] for any value which fits inside of a [`u16`].
76 ///
77 /// This function is const-safe and therefore useful for [`Length`] constants.
78 #[must_use]
79 pub const fn new(value: u32) -> Self {
80 Self {
81 inner: value,
82
83 #[cfg(feature = "ber")]
84 indefinite: false,
85 }
86 }
87
88 /// Create a new [`Length`] for any value which fits inside the length type.
89 ///
90 /// This function is const-safe and therefore useful for [`Length`] constants.
91 #[allow(clippy::cast_possible_truncation)]
92 pub(crate) const fn new_usize(len: usize) -> Result<Self> {
93 if len > (u32::MAX as usize) {
94 Err(Error::from_kind(ErrorKind::Overflow))
95 } else {
96 Ok(Self::new(len as u32))
97 }
98 }
99
100 /// Is this length equal to zero?
101 #[must_use]
102 pub const fn is_zero(self) -> bool {
103 self.inner == 0
104 }
105
106 /// Was this length decoded from an indefinite length when decoding BER?
107 #[cfg(feature = "ber")]
108 pub(crate) const fn is_indefinite(self) -> bool {
109 self.indefinite
110 }
111
112 /// Get the length of DER Tag-Length-Value (TLV) encoded data if `self`
113 /// is the length of the inner "value" portion of the message.
114 ///
115 /// # Errors
116 /// Returns an error if an overflow occurred computing the length.
117 pub fn for_tlv(self, tag: Tag) -> Result<Self> {
118 tag.encoded_len()? + self.encoded_len()? + self
119 }
120
121 /// Perform saturating addition of two lengths.
122 #[must_use]
123 pub fn saturating_add(self, rhs: Self) -> Self {
124 Self::new(self.inner.saturating_add(rhs.inner))
125 }
126
127 /// Perform saturating subtraction of two lengths.
128 #[must_use]
129 pub fn saturating_sub(self, rhs: Self) -> Self {
130 Self::new(self.inner.saturating_sub(rhs.inner))
131 }
132
133 /// If the length is indefinite, compute a length with the EOC marker removed
134 /// (i.e. the final two bytes `00 00`).
135 ///
136 /// Otherwise (as should always be the case with DER), the length is unchanged.
137 ///
138 /// This method notably preserves the `indefinite` flag when performing arithmetic.
139 #[cfg(feature = "ber")]
140 pub(crate) fn sans_eoc(self) -> Self {
141 if self.indefinite {
142 // We expect EOC to be present when this is called.
143 debug_assert!(self >= Self::EOC_LEN);
144
145 Self {
146 inner: self.saturating_sub(Self::EOC_LEN).inner,
147 indefinite: true,
148 }
149 } else {
150 // Return DER length
151 self
152 }
153 }
154
155 /// Get initial octet of the encoded length (if one is required).
156 ///
157 /// From X.690 Section 8.1.3.5:
158 /// > In the long form, the length octets shall consist of an initial octet
159 /// > and one or more subsequent octets. The initial octet shall be encoded
160 /// > as follows:
161 /// >
162 /// > a) bit 8 shall be one;
163 /// > b) bits 7 to 1 shall encode the number of subsequent octets in the
164 /// > length octets, as an unsigned binary integer with bit 7 as the
165 /// > most significant bit;
166 /// > c) the value 11111111₂ shall not be used.
167 fn initial_octet(self) -> Option<u8> {
168 match self.inner {
169 0x80..=0xFF => Some(0x81),
170 0x100..=0xFFFF => Some(0x82),
171 0x10000..=0xFFFFFF => Some(0x83),
172 0x1000000..=0xFFFFFFFF => Some(0x84),
173 _ => None,
174 }
175 }
176 }
177
178 impl Add for Length {
179 type Output = Result<Self>;
180
181 fn add(self, other: Self) -> Result<Self> {
182 self.inner
183 .checked_add(other.inner)
184 .ok_or_else(|| ErrorKind::Overflow.into())
185 .map(Self::new)
186 }
187 }
188
189 impl Add<u8> for Length {
190 type Output = Result<Self>;
191
192 fn add(self, other: u8) -> Result<Self> {
193 self + Length::from(other)
194 }
195 }
196
197 impl Add<u16> for Length {
198 type Output = Result<Self>;
199
200 fn add(self, other: u16) -> Result<Self> {
201 self + Length::from(other)
202 }
203 }
204
205 impl Add<u32> for Length {
206 type Output = Result<Self>;
207
208 fn add(self, other: u32) -> Result<Self> {
209 self + Length::from(other)
210 }
211 }
212
213 impl Add<usize> for Length {
214 type Output = Result<Self>;
215
216 fn add(self, other: usize) -> Result<Self> {
217 self + Length::try_from(other)?
218 }
219 }
220
221 impl Add<Length> for Result<Length> {
222 type Output = Self;
223
224 fn add(self, other: Length) -> Self {
225 self? + other
226 }
227 }
228
229 impl Sub for Length {
230 type Output = Result<Self>;
231
232 fn sub(self, other: Length) -> Result<Self> {
233 self.inner
234 .checked_sub(other.inner)
235 .ok_or_else(|| ErrorKind::Overflow.into())
236 .map(Self::new)
237 }
238 }
239
240 impl Sub<Length> for Result<Length> {
241 type Output = Self;
242
243 fn sub(self, other: Length) -> Self {
244 self? - other
245 }
246 }
247
248 impl From<u8> for Length {
249 fn from(len: u8) -> Length {
250 Length::new(len.into())
251 }
252 }
253
254 impl From<u16> for Length {
255 fn from(len: u16) -> Length {
256 Length::new(len.into())
257 }
258 }
259
260 impl From<u32> for Length {
261 fn from(len: u32) -> Length {
262 Length::new(len)
263 }
264 }
265
266 impl From<Length> for u32 {
267 fn from(length: Length) -> u32 {
268 length.inner
269 }
270 }
271
272 impl TryFrom<usize> for Length {
273 type Error = Error;
274
275 fn try_from(len: usize) -> Result<Length> {
276 Length::new_usize(len)
277 }
278 }
279
280 impl TryFrom<Length> for usize {
281 type Error = Error;
282
283 fn try_from(len: Length) -> Result<usize> {
284 len.inner.try_into().map_err(|_| ErrorKind::Overflow.into())
285 }
286 }
287
288 impl<'a> Decode<'a> for Length {
289 type Error = Error;
290
291 fn decode<R: Reader<'a>>(reader: &mut R) -> Result<Length> {
292 match reader.read_byte()? {
293 len if len < INDEFINITE_LENGTH_OCTET => Ok(len.into()),
294 // Note: per X.690 Section 8.1.3.6.1 the byte 0x80 encodes indefinite lengths
295 INDEFINITE_LENGTH_OCTET => match reader.encoding_rules() {
296 // Indefinite lengths are allowed when decoding BER
297 #[cfg(feature = "ber")]
298 EncodingRules::Ber => indefinite::decode_indefinite_length(&mut reader.clone()),
299 // Indefinite lengths are disallowed when decoding DER
300 EncodingRules::Der => Err(reader.error(ErrorKind::IndefiniteLength)),
301 },
302 // 1-4 byte variable-sized length prefix
303 tag @ 0x81..=0x84 => {
304 let nbytes = tag
305 .checked_sub(0x80)
306 .ok_or_else(|| reader.error(ErrorKind::Overlength))?
307 as usize;
308
309 debug_assert!(nbytes <= 4);
310
311 let mut decoded_len = 0u32;
312 for _ in 0..nbytes {
313 decoded_len = decoded_len
314 .checked_shl(8)
315 .ok_or_else(|| reader.error(ErrorKind::Overflow))?
316 | u32::from(reader.read_byte()?);
317 }
318
319 let length = Length::from(decoded_len);
320
321 // X.690 Section 10.1: DER lengths must be encoded with a minimum
322 // number of octets
323 if length.initial_octet() == Some(tag) {
324 Ok(length)
325 } else {
326 Err(reader.error(ErrorKind::Overlength))
327 }
328 }
329 _ => {
330 // We specialize to a maximum 4-byte length (including initial octet)
331 Err(reader.error(ErrorKind::Overlength))
332 }
333 }
334 }
335 }
336
337 impl Encode for Length {
338 fn encoded_len(&self) -> Result<Length> {
339 match self.inner {
340 0..=0x7F => Ok(Length::new(1)),
341 0x80..=0xFF => Ok(Length::new(2)),
342 0x100..=0xFFFF => Ok(Length::new(3)),
343 0x10000..=0xFFFFFF => Ok(Length::new(4)),
344 0x1000000..=0xFFFFFFFF => Ok(Length::new(5)),
345 }
346 }
347
348 fn encode(&self, writer: &mut impl Writer) -> Result<()> {
349 match self.initial_octet() {
350 Some(tag_byte) => {
351 writer.write_byte(tag_byte)?;
352
353 // Strip leading zeroes
354 match self.inner.to_be_bytes() {
355 [0, 0, 0, byte] => writer.write_byte(byte),
356 [0, 0, bytes @ ..] => writer.write(&bytes),
357 [0, bytes @ ..] => writer.write(&bytes),
358 bytes => writer.write(&bytes),
359 }
360 }
361 #[allow(clippy::cast_possible_truncation)]
362 None => writer.write_byte(self.inner as u8),
363 }
364 }
365 }
366
367 impl DerOrd for Length {
368 fn der_cmp(&self, other: &Self) -> Result<Ordering> {
369 // The DER encoding has the same ordering as the integer value
370 Ok(self.inner.cmp(&other.inner))
371 }
372 }
373
374 impl fmt::Debug for Length {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 #[cfg(feature = "ber")]
377 if self.indefinite {
378 return write!(f, "Length([indefinite])");
379 }
380
381 f.debug_tuple("Length").field(&self.inner).finish()
382 }
383 }
384
385 impl fmt::Display for Length {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 self.inner.fmt(f)
388 }
389 }
390
391 // Implement by hand because the derive would create invalid values.
392 // Generate a u32 with a valid range.
393 #[cfg(feature = "arbitrary")]
394 impl<'a> arbitrary::Arbitrary<'a> for Length {
395 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
396 Ok(Self::new(u.arbitrary()?))
397 }
398
399 fn size_hint(depth: usize) -> (usize, Option<usize>) {
400 u32::size_hint(depth)
401 }
402 }
403
404 #[cfg(test)]
405 #[allow(clippy::unwrap_used)]
406 mod tests {
407 use super::Length;
408 use crate::{Decode, DerOrd, Encode, ErrorKind};
409 use core::cmp::Ordering;
410
411 #[test]
412 fn decode() {
413 assert_eq!(Length::ZERO, Length::from_der(&[0x00]).unwrap());
414
415 assert_eq!(Length::from(0x7Fu8), Length::from_der(&[0x7F]).unwrap());
416
417 assert_eq!(
418 Length::from(0x80u8),
419 Length::from_der(&[0x81, 0x80]).unwrap()
420 );
421
422 assert_eq!(
423 Length::from(0xFFu8),
424 Length::from_der(&[0x81, 0xFF]).unwrap()
425 );
426
427 assert_eq!(
428 Length::from(0x100u16),
429 Length::from_der(&[0x82, 0x01, 0x00]).unwrap()
430 );
431
432 assert_eq!(
433 Length::from(0x10000u32),
434 Length::from_der(&[0x83, 0x01, 0x00, 0x00]).unwrap()
435 );
436 assert_eq!(
437 Length::from(0xFFFFFFFFu32),
438 Length::from_der(&[0x84, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap()
439 );
440 }
441
442 #[test]
443 fn encode() {
444 let mut buffer = [0u8; 5];
445
446 assert_eq!(&[0x00], Length::ZERO.encode_to_slice(&mut buffer).unwrap());
447
448 assert_eq!(
449 &[0x7F],
450 Length::from(0x7Fu8).encode_to_slice(&mut buffer).unwrap()
451 );
452
453 assert_eq!(
454 &[0x81, 0x80],
455 Length::from(0x80u8).encode_to_slice(&mut buffer).unwrap()
456 );
457
458 assert_eq!(
459 &[0x81, 0xFF],
460 Length::from(0xFFu8).encode_to_slice(&mut buffer).unwrap()
461 );
462
463 assert_eq!(
464 &[0x82, 0x01, 0x00],
465 Length::from(0x100u16).encode_to_slice(&mut buffer).unwrap()
466 );
467
468 assert_eq!(
469 &[0x83, 0x01, 0x00, 0x00],
470 Length::from(0x10000u32)
471 .encode_to_slice(&mut buffer)
472 .unwrap()
473 );
474 assert_eq!(
475 &[0x84, 0xFF, 0xFF, 0xFF, 0xFF],
476 Length::from(0xFFFFFFFFu32)
477 .encode_to_slice(&mut buffer)
478 .unwrap()
479 );
480 }
481
482 #[test]
483 fn add_overflows_when_max_length_exceeded() {
484 let result = Length::MAX + Length::ONE;
485 assert_eq!(
486 result.err().map(super::super::error::Error::kind),
487 Some(ErrorKind::Overflow)
488 );
489 }
490
491 #[test]
492 fn der_ord() {
493 assert_eq!(Length::ONE.der_cmp(&Length::MAX).unwrap(), Ordering::Less);
494 assert_eq!(Length::ONE.der_cmp(&Length::ONE).unwrap(), Ordering::Equal);
495 assert_eq!(
496 Length::ONE.der_cmp(&Length::ZERO).unwrap(),
497 Ordering::Greater
498 );
499 }
500 }