Skip to main content

mediation/
ber.rs

1//! Basic Encoding Rules — the framing every 3GPP charging record is wrapped in.
2//!
3//! 3GPP TS 32.298 defines its records in ASN.1 (X.680) and transfers them in
4//! BER (X.690). This module reads the **framing**: tags, lengths, nesting and
5//! bounds. It does not know what any particular tag means, because that is the
6//! schema, and a schema is thousands of generated lines that belong beside a
7//! generator rather than here.
8//!
9//! Framing alone is enough to walk a record file, find a field by its tag path,
10//! check that a record's declared length matches what arrived, and reject a
11//! truncated one — which is most of what a mediation layer needs from the bytes.
12//!
13//! # Zero copy
14//!
15//! [`BerElement::content`] borrows from the input. Decoding a 200 MB record file
16//! copies nothing, which matters at the volumes this crate is built for.
17//!
18//! ```rust
19//! use mediation::{BerReader, TagClass};
20//!
21//! // A constructed context-specific 0 holding an INTEGER 42 and an INTEGER 7.
22//! let bytes = [0xA0, 0x06, 0x02, 0x01, 0x2A, 0x02, 0x01, 0x07];
23//!
24//! let outer = BerReader::new(&bytes).next().unwrap().unwrap();
25//! assert_eq!(outer.tag().class(), TagClass::ContextSpecific);
26//! assert_eq!(outer.tag().number(), 0);
27//! assert!(outer.tag().is_constructed());
28//!
29//! let inner: Vec<_> = outer.children().unwrap().collect::<Result<_, _>>().unwrap();
30//! assert_eq!(inner.len(), 2);
31//! assert_eq!(inner[0].content(), &[0x2A]);
32//! // Offsets point into the original input, not into the parent's contents.
33//! assert_eq!(inner[0].offset(), 2);
34//! ```
35//!
36//! # What BER permits, and what it does not
37//!
38//! BER leaves the length form to the sender: a definite length may use the
39//! long form even when the short form would do, with any number of length
40//! octets (X.690 §8.1.3.5, NOTE 2). Such lengths are **accepted** — a
41//! conforming sender may produce them. DER (X.690 §10.1) is the stricter
42//! subset that forbids them; this module reads BER.
43//!
44//! The encodings X.690 forbids even in BER are **rejected**: a high-tag-number
45//! form with a leading `0x80` octet (§8.1.2.4.2 c), the high-tag form for a
46//! number below 31 (§8.1.2.2), the reserved length octet `0xFF` (§8.1.3.5 c),
47//! and an INTEGER with redundant leading octets (§8.3.2). A raw-byte hash of a
48//! BER record is therefore not a canonical key; hash decoded fields instead.
49//!
50//! # Depth is bounded
51//!
52//! Nesting is attacker-controlled in a record that arrived over a network.
53//! [`BerElement::validate`] walks a structure to a caller-supplied depth and
54//! refuses to go deeper, so a pathological file cannot exhaust the stack. The
55//! iterators themselves never recurse.
56
57use std::fmt;
58
59use crate::error::DecodeError;
60
61// ── Tag ──────────────────────────────────────────────────────────────────────
62
63/// The class of a BER tag (X.690 §8.1.2.2).
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
65pub enum TagClass {
66    /// Types defined by X.680 itself — `INTEGER`, `OCTET STRING`, `SEQUENCE`.
67    Universal,
68    /// Types defined by an application, which is where 3GPP's records sit.
69    Application,
70    /// Tags whose meaning depends on where they appear.
71    ///
72    /// The overwhelming majority of a charging record: its fields are
73    /// context-specific and numbered by position in the ASN.1 definition.
74    ContextSpecific,
75    /// Private-use tags.
76    Private,
77}
78
79impl TagClass {
80    /// Every variant, in the order X.690 numbers them.
81    pub const ALL: &'static [Self] = &[
82        Self::Universal,
83        Self::Application,
84        Self::ContextSpecific,
85        Self::Private,
86    ];
87
88    /// The class encoded in the top two bits of an identifier octet.
89    #[must_use]
90    pub const fn from_bits(bits: u8) -> Self {
91        match bits >> 6 {
92            0b00 => Self::Universal,
93            0b01 => Self::Application,
94            0b10 => Self::ContextSpecific,
95            _ => Self::Private,
96        }
97    }
98
99    /// The top two bits of an identifier octet for this class.
100    #[must_use]
101    pub const fn to_bits(self) -> u8 {
102        match self {
103            Self::Universal => 0b0000_0000,
104            Self::Application => 0b0100_0000,
105            Self::ContextSpecific => 0b1000_0000,
106            Self::Private => 0b1100_0000,
107        }
108    }
109
110    /// The canonical string form.
111    #[must_use]
112    pub const fn as_str(self) -> &'static str {
113        match self {
114            Self::Universal => "UNIVERSAL",
115            Self::Application => "APPLICATION",
116            Self::ContextSpecific => "CONTEXT",
117            Self::Private => "PRIVATE",
118        }
119    }
120}
121
122impl fmt::Display for TagClass {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(self.as_str())
125    }
126}
127
128/// A decoded BER tag: class, constructed flag and number.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
130pub struct BerTag {
131    class: TagClass,
132    constructed: bool,
133    number: u32,
134}
135
136impl BerTag {
137    /// The largest tag number this reader accepts.
138    ///
139    /// A 32-bit ceiling: X.690 places no limit, but a tag beyond this is a
140    /// misaligned read rather than a field, and accepting an unbounded integer
141    /// from untrusted input is how a decoder becomes a denial of service.
142    pub const MAX_NUMBER: u32 = u32::MAX >> 1;
143
144    /// A tag from its three parts.
145    ///
146    /// `None` for a number above [`MAX_NUMBER`](Self::MAX_NUMBER).
147    #[must_use]
148    pub const fn new(class: TagClass, constructed: bool, number: u32) -> Option<Self> {
149        if number > Self::MAX_NUMBER {
150            return None;
151        }
152        Some(Self {
153            class,
154            constructed,
155            number,
156        })
157    }
158
159    /// The tag's class.
160    #[must_use]
161    pub const fn class(self) -> TagClass {
162        self.class
163    }
164
165    /// `true` when the contents are further elements rather than raw bytes.
166    #[must_use]
167    pub const fn is_constructed(self) -> bool {
168        self.constructed
169    }
170
171    /// The tag number.
172    #[must_use]
173    pub const fn number(self) -> u32 {
174        self.number
175    }
176
177    /// `true` when this is the universal end-of-contents marker.
178    #[must_use]
179    pub const fn is_end_of_contents(self) -> bool {
180        matches!(self.class, TagClass::Universal) && !self.constructed && self.number == 0
181    }
182}
183
184impl fmt::Display for BerTag {
185    /// Writes `CONTEXT 3` or `CONTEXT 3 (constructed)`.
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        write!(f, "{} {}", self.class, self.number)?;
188        if self.constructed {
189            f.write_str(" (constructed)")?;
190        }
191        Ok(())
192    }
193}
194
195// ── Length ───────────────────────────────────────────────────────────────────
196
197/// How a BER element's contents are delimited (X.690 §8.1.3).
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub enum BerLength {
200    /// A stated octet count.
201    Definite(usize),
202    /// Terminated by an end-of-contents marker, valid only for constructed
203    /// elements.
204    Indefinite,
205}
206
207impl BerLength {
208    /// The stated octet count, when there is one.
209    #[must_use]
210    pub const fn definite(self) -> Option<usize> {
211        match self {
212            Self::Definite(n) => Some(n),
213            Self::Indefinite => None,
214        }
215    }
216}
217
218// ── Element ──────────────────────────────────────────────────────────────────
219
220/// One tag-length-value element, borrowing its contents from the input.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub struct BerElement<'a> {
223    tag: BerTag,
224    length: BerLength,
225    content: &'a [u8],
226    /// Octets this element occupies in the input, header and contents together.
227    encoded_len: usize,
228    /// Where the element began, for error reporting against the original input.
229    offset: usize,
230    /// Where the **contents** began, so a child's reported offset points into
231    /// the original input rather than into its parent.
232    content_offset: usize,
233}
234
235impl<'a> BerElement<'a> {
236    /// The element's tag.
237    #[must_use]
238    pub const fn tag(&self) -> BerTag {
239        self.tag
240    }
241
242    /// How the contents were delimited.
243    #[must_use]
244    pub const fn length(&self) -> BerLength {
245        self.length
246    }
247
248    /// The contents, borrowed from the input.
249    ///
250    /// For a constructed element these are the encoded children; use
251    /// [`children`](Self::children) to walk them.
252    #[must_use]
253    pub const fn content(&self) -> &'a [u8] {
254        self.content
255    }
256
257    /// How many octets the whole element occupies, header included.
258    #[must_use]
259    pub const fn encoded_len(&self) -> usize {
260        self.encoded_len
261    }
262
263    /// Where the element began in the input it was read from.
264    #[must_use]
265    pub const fn offset(&self) -> usize {
266        self.offset
267    }
268
269    /// A reader over this element's children.
270    ///
271    /// # Errors
272    ///
273    /// [`DecodeError`] when the element is primitive: its contents are raw
274    /// bytes, and reading them as elements would produce fields that are not
275    /// there.
276    pub fn children(&self) -> Result<BerReader<'a>, DecodeError> {
277        if !self.tag.constructed {
278            return Err(DecodeError::new(
279                self.offset,
280                "a constructed element; a primitive one has no children",
281            ));
282        }
283        Ok(BerReader::at_offset(self.content, self.content_offset))
284    }
285
286    /// The contents as an unsigned integer.
287    ///
288    /// # Errors
289    ///
290    /// [`DecodeError`] for an empty field, one wider than eight octets, a
291    /// negative value, or a non-minimal encoding — X.690 §8.3 requires the
292    /// shortest form, and a padded integer is a second encoding of one value.
293    pub fn as_u64(&self) -> Result<u64, DecodeError> {
294        let bytes = self.content;
295        if bytes.is_empty() {
296            return Err(DecodeError::new(self.offset, "at least one content octet"));
297        }
298        if bytes[0] & 0x80 != 0 {
299            return Err(DecodeError::new(self.offset, "a non-negative integer"));
300        }
301        if bytes.len() > 1 && bytes[0] == 0x00 && bytes[1] & 0x80 == 0 {
302            return Err(DecodeError::new(
303                self.offset,
304                "a minimally encoded integer, without leading padding",
305            ));
306        }
307        // Nine octets are the widest a `u64` can hold: X.690 integers are
308        // signed, so `u64::MAX` is encoded as a `0x00` sign octet followed by
309        // eight value octets. Rejecting that form would put the top bit of the
310        // range out of reach for no reason.
311        let value = if bytes[0] == 0x00 { &bytes[1..] } else { bytes };
312        if value.len() > 8 {
313            return Err(DecodeError::new(
314                self.offset,
315                "an integer that fits in 64 unsigned bits",
316            ));
317        }
318        Ok(value.iter().fold(0u64, |acc, b| (acc << 8) | u64::from(*b)))
319    }
320
321    /// Walk this element's structure, refusing to descend past `max_depth`.
322    ///
323    /// Returns how many elements were visited, this one included.
324    ///
325    /// Nesting is attacker-controlled in a record that arrived over a network,
326    /// so the bound is mandatory rather than optional. The walk is iterative
327    /// and never recurses, so exceeding the bound is reported rather than
328    /// crashing.
329    ///
330    /// # Errors
331    ///
332    /// [`DecodeError`] when the structure is malformed, or nests deeper than
333    /// `max_depth`.
334    pub fn validate(&self, max_depth: usize) -> Result<usize, DecodeError> {
335        let mut visited = 1;
336        // (contents, offset, depth) — an explicit stack, so the recursion depth
337        // of this function is one whatever the input does.
338        let mut pending = Vec::new();
339        if self.tag.constructed {
340            pending.push((self.content, self.content_offset, 1usize));
341        }
342
343        while let Some((bytes, offset, depth)) = pending.pop() {
344            if depth > max_depth {
345                return Err(DecodeError::new(
346                    offset,
347                    "a structure within the depth limit",
348                ));
349            }
350            for element in BerReader::at_offset(bytes, offset) {
351                let element = element?;
352                visited += 1;
353                if element.tag.constructed {
354                    pending.push((element.content, element.content_offset, depth + 1));
355                }
356            }
357        }
358        Ok(visited)
359    }
360
361    /// The first child whose tag matches, searching only this element's own
362    /// children.
363    ///
364    /// Not recursive: a tag number is only meaningful at the level its schema
365    /// places it, and a deep search would happily return a field from an
366    /// unrelated nested structure.
367    ///
368    /// # Errors
369    ///
370    /// [`DecodeError`] when the element is primitive or its children are
371    /// malformed.
372    pub fn find(&self, tag: BerTag) -> Result<Option<Self>, DecodeError> {
373        for child in self.children()? {
374            let child = child?;
375            if child.tag == tag {
376                return Ok(Some(child));
377            }
378        }
379        Ok(None)
380    }
381}
382
383impl fmt::Display for BerElement<'_> {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        write!(
386            f,
387            "{} at {}, {} content octet(s)",
388            self.tag,
389            self.offset,
390            self.content.len()
391        )
392    }
393}
394
395// ── Reader ───────────────────────────────────────────────────────────────────
396
397/// An iterator over the BER elements at one nesting level.
398///
399/// Yields `Result`, so a malformed element stops the walk rather than being
400/// skipped — a decoder that steps over what it could not read produces a record
401/// missing the fields it failed on, which is worse than no record.
402#[derive(Debug, Clone)]
403pub struct BerReader<'a> {
404    bytes: &'a [u8],
405    position: usize,
406    /// Offset of `bytes[0]` in the original input, so errors and elements
407    /// report positions a caller can find in the file they hold.
408    base: usize,
409    finished: bool,
410}
411
412impl<'a> BerReader<'a> {
413    /// How deep indefinite-length constructions may nest.
414    ///
415    /// X.690 sets no limit, and a real charging record nests a handful of
416    /// levels. The bound exists because resolving an indefinite length means
417    /// walking the element's subtree, so an unbounded chain of them is
418    /// quadratic in the file size — and because the input is untrusted.
419    pub const MAX_INDEFINITE_DEPTH: usize = 128;
420
421    /// A reader over `bytes`.
422    #[must_use]
423    pub const fn new(bytes: &'a [u8]) -> Self {
424        Self::at_offset(bytes, 0)
425    }
426
427    /// A reader over `bytes`, which begin at `base` in the original input.
428    #[must_use]
429    pub const fn at_offset(bytes: &'a [u8], base: usize) -> Self {
430        Self {
431            bytes,
432            position: 0,
433            base,
434            finished: false,
435        }
436    }
437
438    /// How many octets remain unread.
439    #[must_use]
440    pub const fn remaining(&self) -> usize {
441        self.bytes.len() - self.position
442    }
443
444    /// Read one element, or `None` at the end of the input.
445    fn read(&mut self) -> Option<Result<BerElement<'a>, DecodeError>> {
446        if self.finished || self.position >= self.bytes.len() {
447            return None;
448        }
449        // Every reported offset is `base + i` with `i <= bytes.len()`; one
450        // check here keeps all of them from overflowing.
451        if self.base.checked_add(self.bytes.len()).is_none() {
452            self.finished = true;
453            return Some(Err(DecodeError::new(
454                self.base,
455                "a base offset that leaves room for the input",
456            )));
457        }
458        let start = self.position;
459        match self.read_element(start) {
460            Ok(element) => {
461                self.position += element.encoded_len;
462                Some(Ok(element))
463            }
464            Err(e) => {
465                self.finished = true;
466                Some(Err(e))
467            }
468        }
469    }
470
471    /// Read the element beginning at `start`.
472    ///
473    /// An end-of-contents marker is an **error** here rather than a quiet stop.
474    /// A reader only ever walks a region whose extent is already known — an
475    /// element's contents, or the caller's whole input — so a marker inside one
476    /// closes nothing. Treating it as a terminator would silently drop every
477    /// remaining field of a definite-length structure, which is exactly the
478    /// "decoder that steps over what it could not read" this module refuses to
479    /// be. The scan that resolves an indefinite length recognises the marker by
480    /// inspection, before reaching here.
481    fn read_element(&self, start: usize) -> Result<BerElement<'a>, DecodeError> {
482        let absolute = self.base + start;
483        let (tag, after_tag) = self.read_tag(start)?;
484        let (length, after_length) = self.read_length(after_tag)?;
485
486        if tag.is_end_of_contents() {
487            return Err(DecodeError::new(
488                absolute,
489                "an element; an end-of-contents marker closes nothing here",
490            ));
491        }
492
493        let (content, encoded_len) = match length {
494            BerLength::Definite(n) => {
495                let end = after_length
496                    .checked_add(n)
497                    .ok_or_else(|| DecodeError::new(absolute, "a length that does not overflow"))?;
498                if end > self.bytes.len() {
499                    return Err(DecodeError::new(
500                        absolute,
501                        "contents that fit within the input",
502                    ));
503                }
504                (&self.bytes[after_length..end], end - start)
505            }
506            BerLength::Indefinite => {
507                if !tag.constructed {
508                    return Err(DecodeError::new(
509                        absolute,
510                        "a definite length; only constructed elements may be indefinite",
511                    ));
512                }
513                let content_end = self.scan_to_end_of_contents(after_length)?;
514                // The contents stop before the two-octet marker, but the
515                // element occupies them too.
516                (
517                    &self.bytes[after_length..content_end],
518                    content_end + 2 - start,
519                )
520            }
521        };
522
523        Ok(BerElement {
524            tag,
525            length,
526            content,
527            encoded_len,
528            offset: absolute,
529            content_offset: self.base + after_length,
530        })
531    }
532
533    /// Decode the identifier octets (X.690 §8.1.2).
534    fn read_tag(&self, start: usize) -> Result<(BerTag, usize), DecodeError> {
535        let absolute = self.base + start;
536        let first = *self
537            .bytes
538            .get(start)
539            .ok_or_else(|| DecodeError::new(absolute, "an identifier octet"))?;
540        let class = TagClass::from_bits(first);
541        let constructed = first & 0b0010_0000 != 0;
542        let low = first & 0b0001_1111;
543
544        if low != 0b0001_1111 {
545            let tag = BerTag::new(class, constructed, u32::from(low))
546                .ok_or_else(|| DecodeError::new(absolute, "a tag number within range"))?;
547            return Ok((tag, start + 1));
548        }
549
550        // High-tag-number form: base-128, most significant first, bit 8 set on
551        // every octet but the last.
552        let mut number = 0u32;
553        let mut index = start + 1;
554        let mut octets = 0usize;
555        loop {
556            let byte = *self
557                .bytes
558                .get(index)
559                .ok_or_else(|| DecodeError::new(absolute, "a complete high-tag-number form"))?;
560            if octets == 0 && byte == 0x80 {
561                return Err(DecodeError::new(
562                    absolute,
563                    "a minimally encoded tag number, without leading padding",
564                ));
565            }
566            number = number
567                .checked_mul(128)
568                .and_then(|n| n.checked_add(u32::from(byte & 0x7F)))
569                .ok_or_else(|| DecodeError::new(absolute, "a tag number within range"))?;
570            index += 1;
571            octets += 1;
572            if byte & 0x80 == 0 {
573                break;
574            }
575        }
576        if number < 31 {
577            return Err(DecodeError::new(
578                absolute,
579                "the short tag form for numbers below 31",
580            ));
581        }
582        let tag = BerTag::new(class, constructed, number)
583            .ok_or_else(|| DecodeError::new(absolute, "a tag number within range"))?;
584        Ok((tag, index))
585    }
586
587    /// Decode the length octets (X.690 §8.1.3).
588    fn read_length(&self, start: usize) -> Result<(BerLength, usize), DecodeError> {
589        let absolute = self.base + start;
590        let first = *self
591            .bytes
592            .get(start)
593            .ok_or_else(|| DecodeError::new(absolute, "a length octet"))?;
594
595        if first & 0x80 == 0 {
596            return Ok((BerLength::Definite(usize::from(first)), start + 1));
597        }
598        let count = usize::from(first & 0x7F);
599        if count == 0 {
600            return Ok((BerLength::Indefinite, start + 1));
601        }
602        if count == 0x7F {
603            return Err(DecodeError::new(absolute, "a length form X.690 defines"));
604        }
605        let end = start + 1 + count;
606        if end > self.bytes.len() {
607            return Err(DecodeError::new(absolute, "complete length octets"));
608        }
609        // BER lets the sender choose the long form and pad it with leading
610        // zero octets (X.690 §8.1.3.5); only the value matters.
611        let octets = &self.bytes[start + 1..end];
612        let significant = octets
613            .iter()
614            .position(|b| *b != 0)
615            .map_or(&octets[octets.len()..], |i| &octets[i..]);
616        if significant.len() > 8 {
617            return Err(DecodeError::new(absolute, "a length that fits in 64 bits"));
618        }
619        let value = significant
620            .iter()
621            .fold(0u64, |acc, b| (acc << 8) | u64::from(*b));
622        let value = usize::try_from(value)
623            .map_err(|_| DecodeError::new(absolute, "a length this platform can address"))?;
624        Ok((BerLength::Definite(value), end))
625    }
626
627    /// Find the end-of-contents marker closing an indefinite-length element.
628    ///
629    /// Walks the nested elements rather than scanning for `00 00`, because two
630    /// zero octets occur inside contents all the time.
631    ///
632    /// **Iterative, and depth-bounded.** Nesting is attacker-controlled in a
633    /// record that arrived over a network, so a scan that recursed once per
634    /// level would abort the process on a file that is a few hundred kilobytes
635    /// of `30 80` — no allocation and no cleverness required of the attacker.
636    /// This walk keeps a counter instead, and refuses input nested deeper than
637    /// [`MAX_INDEFINITE_DEPTH`](Self::MAX_INDEFINITE_DEPTH). The bound also caps
638    /// the cost of descending: resolving an indefinite length is inherently a
639    /// walk of the element's whole subtree, so an unbounded chain of them would
640    /// be quadratic in the file size even without the stack.
641    fn scan_to_end_of_contents(&self, start: usize) -> Result<usize, DecodeError> {
642        let mut position = start;
643        let mut open = 1usize;
644        loop {
645            if position + 2 > self.bytes.len() {
646                return Err(DecodeError::new(
647                    self.base + start,
648                    "an end-of-contents marker",
649                ));
650            }
651            if self.bytes[position] == 0x00 && self.bytes[position + 1] == 0x00 {
652                open -= 1;
653                if open == 0 {
654                    return Ok(position);
655                }
656                position += 2;
657                continue;
658            }
659
660            // Read the header only. A definite-length element is stepped over
661            // wholesale; an indefinite one opens another level of this loop.
662            let (tag, after_tag) = self.read_tag(position)?;
663            let (length, after_length) = self.read_length(after_tag)?;
664            if tag.is_end_of_contents() {
665                return Err(DecodeError::new(
666                    self.base + position,
667                    "an end-of-contents marker with zero length",
668                ));
669            }
670            match length {
671                BerLength::Definite(n) => {
672                    let end = after_length.checked_add(n).ok_or_else(|| {
673                        DecodeError::new(self.base + position, "a length that does not overflow")
674                    })?;
675                    if end > self.bytes.len() {
676                        return Err(DecodeError::new(
677                            self.base + position,
678                            "contents that fit within the input",
679                        ));
680                    }
681                    position = end;
682                }
683                BerLength::Indefinite => {
684                    if !tag.is_constructed() {
685                        return Err(DecodeError::new(
686                            self.base + position,
687                            "a definite length; only constructed elements may be indefinite",
688                        ));
689                    }
690                    open += 1;
691                    if open > Self::MAX_INDEFINITE_DEPTH {
692                        return Err(DecodeError::new(
693                            self.base + position,
694                            "indefinite lengths nested within the depth limit",
695                        ));
696                    }
697                    position = after_length;
698                }
699            }
700        }
701    }
702}
703
704impl<'a> Iterator for BerReader<'a> {
705    type Item = Result<BerElement<'a>, DecodeError>;
706
707    fn next(&mut self) -> Option<Self::Item> {
708        self.read()
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715
716    /// A constructed context-specific 0 holding two integers.
717    const NESTED: [u8; 8] = [0xA0, 0x06, 0x02, 0x01, 0x2A, 0x02, 0x01, 0x07];
718
719    fn one(bytes: &[u8]) -> BerElement<'_> {
720        BerReader::new(bytes).next().unwrap().unwrap()
721    }
722
723    #[test]
724    fn a_constructed_element_yields_its_children() {
725        let outer = one(&NESTED);
726        assert_eq!(outer.tag().class(), TagClass::ContextSpecific);
727        assert_eq!(outer.tag().number(), 0);
728        assert!(outer.tag().is_constructed());
729        assert_eq!(outer.encoded_len(), 8);
730
731        let children: Vec<_> = outer
732            .children()
733            .unwrap()
734            .collect::<Result<Vec<_>, _>>()
735            .unwrap();
736        assert_eq!(children.len(), 2);
737        assert_eq!(children[0].as_u64().unwrap(), 42);
738        assert_eq!(children[1].as_u64().unwrap(), 7);
739        // Offsets are reported against the original input.
740        assert_eq!(children[0].offset(), 2);
741        assert_eq!(children[1].offset(), 5);
742    }
743
744    /// Contents are borrowed, so walking a large file copies nothing.
745    #[test]
746    fn contents_borrow_from_the_input() {
747        let outer = one(&NESTED);
748        let content = outer.content();
749        assert_eq!(content.as_ptr(), NESTED[2..].as_ptr());
750    }
751
752    #[test]
753    fn a_primitive_element_has_no_children() {
754        let primitive = one(&[0x02, 0x01, 0x2A]);
755        assert!(!primitive.tag().is_constructed());
756        assert!(primitive.children().is_err());
757        assert_eq!(primitive.as_u64().unwrap(), 42);
758    }
759
760    // ── Minimality ───────────────────────────────────────────────────────────
761
762    /// BER leaves the length form to the sender (X.690 §8.1.3.5): a long
763    /// form that would fit the short form, or one with leading zero octets,
764    /// is a valid encoding of the same length.
765    #[test]
766    fn a_non_minimal_length_is_accepted() {
767        let element = one(&[0x04, 0x81, 0x05, 1, 2, 3, 4, 5]);
768        assert_eq!(element.content(), &[1, 2, 3, 4, 5]);
769        let element = one(&[0x04, 0x82, 0x00, 0x02, 9, 9]);
770        assert_eq!(element.content(), &[9, 9]);
771        // The reserved form 0xFF stays refused.
772        assert!(BerReader::new(&[0x04, 0xFF]).next().unwrap().is_err());
773        // A genuine long form is fine too.
774        let long = [&[0x04u8, 0x81, 0x80][..], &[0xAA; 128][..]].concat();
775        let element = one(&long);
776        assert_eq!(element.content().len(), 128);
777    }
778
779    #[test]
780    fn a_non_minimal_tag_number_is_rejected() {
781        // High-tag form with a leading 0x80 padding octet.
782        assert!(
783            BerReader::new(&[0x1F, 0x80, 0x7F, 0x00])
784                .next()
785                .unwrap()
786                .is_err()
787        );
788        // High-tag form encoding a number the short form covers.
789        assert!(BerReader::new(&[0x1F, 0x05, 0x00]).next().unwrap().is_err());
790        // …while a genuine high tag decodes.
791        let element = one(&[0x1F, 0x81, 0x00, 0x00]);
792        assert_eq!(element.tag().number(), 128);
793    }
794
795    /// X.690 §8.3 requires the shortest integer form, so a padded one is a
796    /// second encoding of one value.
797    #[test]
798    fn a_non_minimal_integer_is_rejected() {
799        assert!(one(&[0x02, 0x02, 0x00, 0x2A]).as_u64().is_err());
800        // A leading zero *is* required when the next octet's top bit is set,
801        // because otherwise the value would read as negative.
802        assert_eq!(one(&[0x02, 0x02, 0x00, 0x80]).as_u64().unwrap(), 128);
803        // A negative integer is not a length, a count or an identifier.
804        assert!(one(&[0x02, 0x01, 0xFF]).as_u64().is_err());
805        assert!(one(&[0x02, 0x00]).as_u64().is_err(), "empty");
806    }
807
808    // ── Bounds ───────────────────────────────────────────────────────────────
809
810    /// A truncated record must be reported, never partially decoded.
811    #[test]
812    fn contents_running_past_the_input_are_rejected() {
813        assert!(
814            BerReader::new(&[0x04, 0x0A, 0x01, 0x02])
815                .next()
816                .unwrap()
817                .is_err()
818        );
819        assert!(BerReader::new(&[0x04]).next().unwrap().is_err());
820        assert!(BerReader::new(&[0x02, 0x81]).next().unwrap().is_err());
821    }
822
823    #[test]
824    fn an_absurd_length_is_rejected_rather_than_allocated() {
825        // Nine length octets exceeds what X.690 needs for any real record.
826        assert!(
827            BerReader::new(&[0x04, 0x89, 1, 1, 1, 1, 1, 1, 1, 1, 1])
828                .next()
829                .unwrap()
830                .is_err()
831        );
832        // 0xFF is the reserved length form.
833        assert!(BerReader::new(&[0x04, 0xFF]).next().unwrap().is_err());
834    }
835
836    /// A malformed element stops the walk: a decoder that skips what it could
837    /// not read produces a record missing exactly the fields it failed on.
838    #[test]
839    fn a_malformed_element_stops_the_walk() {
840        let bytes = [0x02, 0x01, 0x2A, 0x04, 0x7F, 0x00];
841        let results: Vec<_> = BerReader::new(&bytes).collect();
842        assert_eq!(results.len(), 2);
843        assert!(results[0].is_ok());
844        assert!(results[1].is_err());
845    }
846
847    // ── Indefinite length ────────────────────────────────────────────────────
848
849    #[test]
850    fn an_indefinite_length_element_ends_at_its_marker() {
851        // Constructed, indefinite, holding one INTEGER, then 00 00.
852        let bytes = [0xA0, 0x80, 0x02, 0x01, 0x2A, 0x00, 0x00];
853        let element = one(&bytes);
854
855        assert_eq!(element.length(), BerLength::Indefinite);
856        assert_eq!(element.content(), &[0x02, 0x01, 0x2A]);
857        assert_eq!(element.encoded_len(), bytes.len());
858
859        let children: Vec<_> = element
860            .children()
861            .unwrap()
862            .collect::<Result<Vec<_>, _>>()
863            .unwrap();
864        assert_eq!(children.len(), 1);
865        assert_eq!(children[0].as_u64().unwrap(), 42);
866    }
867
868    /// Two zero octets occur inside contents all the time, so the scan walks
869    /// elements rather than searching for the byte pair.
870    #[test]
871    fn a_zero_pair_inside_contents_is_not_mistaken_for_the_marker() {
872        // An OCTET STRING whose contents are 00 00, then the real marker.
873        let bytes = [0xA0, 0x80, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00];
874        let element = one(&bytes);
875        assert_eq!(element.content(), &[0x04, 0x02, 0x00, 0x00]);
876        assert_eq!(element.encoded_len(), bytes.len());
877    }
878
879    #[test]
880    fn an_indefinite_length_primitive_is_rejected() {
881        // Only constructed elements may use the indefinite form.
882        assert!(
883            BerReader::new(&[0x04, 0x80, 0x00, 0x00])
884                .next()
885                .unwrap()
886                .is_err()
887        );
888    }
889
890    #[test]
891    fn a_missing_end_of_contents_marker_is_rejected() {
892        assert!(
893            BerReader::new(&[0xA0, 0x80, 0x02, 0x01, 0x2A])
894                .next()
895                .unwrap()
896                .is_err()
897        );
898    }
899
900    // ── Depth ────────────────────────────────────────────────────────────────
901
902    /// Nesting is attacker-controlled, so the bound is mandatory and exceeding
903    /// it is reported rather than crashing.
904    #[test]
905    fn deep_nesting_is_reported_rather_than_exhausting_the_stack() {
906        // 5 000 nested constructed elements, each wrapping the next.
907        let mut bytes = vec![0x05u8, 0x00]; // a NULL at the core
908        for _ in 0..5_000 {
909            let len = bytes.len();
910            assert!(len < 128, "kept short so the length stays one octet");
911            let mut wrapped = vec![0xA0, u8::try_from(len).unwrap()];
912            wrapped.extend_from_slice(&bytes);
913            bytes = wrapped;
914            if bytes.len() >= 120 {
915                break;
916            }
917        }
918
919        let element = one(&bytes);
920        assert!(element.validate(1_000).is_ok());
921        assert!(
922            element.validate(2).is_err(),
923            "a shallow bound must refuse to descend"
924        );
925    }
926
927    #[test]
928    fn validate_counts_every_element_it_visits() {
929        let outer = one(&NESTED);
930        assert_eq!(
931            outer.validate(10).unwrap(),
932            3,
933            "the outer plus two children"
934        );
935
936        let primitive = one(&[0x02, 0x01, 0x2A]);
937        assert_eq!(primitive.validate(10).unwrap(), 1);
938    }
939
940    #[test]
941    fn validate_reports_a_malformed_child() {
942        // Outer claims 4 octets; the inner element claims more than it has.
943        let bytes = [0xA0, 0x04, 0x04, 0x7F, 0x00, 0x00];
944        assert!(one(&bytes).validate(10).is_err());
945    }
946
947    // ── Searching ────────────────────────────────────────────────────────────
948
949    #[test]
950    fn find_searches_one_level_only() {
951        // Outer holds a nested constructed element, which holds tag 1.
952        let bytes = [0xA0, 0x05, 0xA1, 0x03, 0x02, 0x01, 0x2A];
953        let outer = one(&bytes);
954
955        let nested_tag = BerTag::new(TagClass::ContextSpecific, true, 1).unwrap();
956        assert!(outer.find(nested_tag).unwrap().is_some());
957
958        // The INTEGER lives one level deeper and is deliberately not found.
959        let integer_tag = BerTag::new(TagClass::Universal, false, 2).unwrap();
960        assert!(outer.find(integer_tag).unwrap().is_none());
961        assert!(
962            outer
963                .find(nested_tag)
964                .unwrap()
965                .unwrap()
966                .find(integer_tag)
967                .unwrap()
968                .is_some()
969        );
970    }
971
972    // ── Tag encoding ─────────────────────────────────────────────────────────
973
974    #[test]
975    fn tag_classes_round_trip_through_their_bits() {
976        for class in TagClass::ALL {
977            assert_eq!(TagClass::from_bits(class.to_bits()), *class);
978        }
979        assert_eq!(TagClass::from_bits(0xA0), TagClass::ContextSpecific);
980        assert_eq!(TagClass::from_bits(0x02), TagClass::Universal);
981    }
982
983    #[test]
984    fn tags_render_legibly() {
985        let tag = BerTag::new(TagClass::ContextSpecific, true, 3).unwrap();
986        assert_eq!(tag.to_string(), "CONTEXT 3 (constructed)");
987        let primitive = BerTag::new(TagClass::Universal, false, 2).unwrap();
988        assert_eq!(primitive.to_string(), "UNIVERSAL 2");
989        assert_eq!(BerTag::new(TagClass::Universal, false, u32::MAX), None);
990    }
991
992    #[test]
993    fn an_end_of_contents_tag_is_recognised() {
994        let eoc = BerTag::new(TagClass::Universal, false, 0).unwrap();
995        assert!(eoc.is_end_of_contents());
996        let not_eoc = BerTag::new(TagClass::ContextSpecific, false, 0).unwrap();
997        assert!(!not_eoc.is_end_of_contents());
998    }
999
1000    #[test]
1001    fn an_empty_input_yields_nothing() {
1002        assert_eq!(BerReader::new(&[]).count(), 0);
1003        assert_eq!(BerReader::new(&[]).remaining(), 0);
1004    }
1005}