synta 0.2.1

ASN.1 parser, decoder, and encoder library with DER/BER support and C FFI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! DER/BER decoder implementation

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};

use crate::config::DecoderConfig;
use crate::error::{Error, Result};
use crate::{Encoding, Length, Tag};

/// Decoder for ASN.1 DER/BER encoded data
///
/// Uses a cursor-based design for efficient zero-copy parsing.
/// For BER indefinite-length encoding, assembled content is stored inside
/// the decoder and freed when the decoder is dropped.
pub struct Decoder<'a> {
    /// Original input for position calculation
    original: &'a [u8],
    /// Remaining input to decode
    cursor: &'a [u8],
    /// Encoding type (DER, BER, or CER)
    encoding: Encoding,
    /// Configuration limits (borrowed to avoid cloning on every nested construct)
    config: &'a DecoderConfig,
    /// Current nesting depth
    current_depth: usize,
    /// Cached position in original input (for O(1) access)
    position: usize,
    /// Buffers assembled from BER/CER indefinite-length content.
    /// `cursor` (or sub-slices of it) may point into these allocations.
    /// `Box<[u8]>` heap data is stable across moves, so the raw pointers
    /// embedded in `cursor` remain valid after the decoder is moved.
    indefinite_buffers: Vec<Box<[u8]>>,
}

/// Default decoder configuration (shared by all decoders using default config)
static DEFAULT_CONFIG: DecoderConfig = DecoderConfig {
    max_depth: 32,
    max_sequence_elements: 10_000,
    max_length: 16 * 1024 * 1024, // 16 MB
};

impl<'a> Decoder<'a> {
    /// Create a new decoder for the given input
    pub fn new(input: &'a [u8], encoding: Encoding) -> Self {
        Self {
            original: input,
            cursor: input,
            encoding,
            config: &DEFAULT_CONFIG,
            current_depth: 0,
            position: 0,
            indefinite_buffers: Vec::new(),
        }
    }

    /// Create a new decoder with custom configuration
    pub fn new_with_config(input: &'a [u8], encoding: Encoding, config: &'a DecoderConfig) -> Self {
        Self {
            original: input,
            cursor: input,
            encoding,
            config,
            current_depth: 0,
            position: 0,
            indefinite_buffers: Vec::new(),
        }
    }

    /// Get current position in original input
    #[inline]
    pub fn position(&self) -> usize {
        self.position
    }

    /// Get remaining bytes in current scope
    pub fn remaining(&self) -> &'a [u8] {
        self.cursor
    }

    /// Check if at end of current scope
    pub fn is_empty(&self) -> bool {
        self.cursor.is_empty()
    }

    /// Advance the cursor past all remaining bytes in the current scope.
    ///
    /// After this call `is_empty()` returns `true`.  Used by sequence
    /// iterators to terminate cleanly after a decode error: without this the
    /// iterator would keep retrying the same failing position forever.
    #[inline]
    pub(crate) fn exhaust(&mut self) {
        self.position += self.cursor.len();
        self.cursor = &self.cursor[self.cursor.len()..];
    }

    /// Get the encoding type
    pub fn encoding(&self) -> Encoding {
        self.encoding
    }

    /// Read exactly `n` bytes from the current cursor position, advancing it.
    ///
    /// Returns a slice borrowed from the original input with lifetime `'a`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnexpectedEof`] if fewer than `n` bytes remain in
    /// the current scope.
    #[inline]
    pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> {
        if self.cursor.len() < n {
            return Err(Error::UnexpectedEof {
                position: self.position,
            });
        }
        let (chunk, rest) = self.cursor.split_at(n);
        self.cursor = rest;
        self.position += n;
        Ok(chunk)
    }

    /// Peek at the next tag without consuming any bytes.
    ///
    /// Returns the [`Tag`] that would be read by the next call to
    /// [`read_tag`](Self::read_tag).  The cursor position is unchanged.
    ///
    /// Useful for dispatching on the tag type before committing to a specific
    /// `Decode` implementation.
    ///
    /// # Errors
    ///
    /// Returns an error if the remaining input is empty or if the tag encoding
    /// is invalid.
    pub fn peek_tag(&self) -> Result<Tag> {
        let (tag, _) = Tag::decode(self.cursor, self.position)?;
        Ok(tag)
    }

    /// Read and consume the next ASN.1 tag from the input.
    ///
    /// Advances the cursor past the tag bytes (1 byte for low-tag-number form;
    /// more for high-tag-number form).
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnexpectedEof`] if the input is empty, or an error if
    /// the tag encoding is malformed (e.g. an overlong high-tag-number form
    /// that would overflow a `u32`).
    pub fn read_tag(&mut self) -> Result<Tag> {
        let (tag, consumed) = Tag::decode(self.cursor, self.position)?;
        self.cursor = &self.cursor[consumed..];
        self.position += consumed;
        Ok(tag)
    }

    /// Assemble indefinite-length content into an owned buffer.
    ///
    /// Reads TLV elements from the cursor until the outermost end-of-contents
    /// octets (`0x00 0x00`) are reached, advancing the cursor past them.
    /// Nested indefinite-length encodings are handled transparently: inner
    /// end-of-contents pairs are copied into the returned buffer and the depth
    /// counter is decremented accordingly.
    ///
    /// The returned `Box<[u8]>` contains all assembled bytes, excluding the
    /// outermost terminating `0x00 0x00` pair.  Callers must store the box
    /// (e.g. in `indefinite_buffers`) before constructing any slice into it.
    fn assemble_indefinite_content(&mut self) -> Result<Box<[u8]>> {
        // Pre-allocate to reduce reallocations (typical ASN.1 indefinite content is < 4KB)
        let mut content = Vec::with_capacity(4096);
        let mut depth = 0usize;
        let start_position = self.position;

        loop {
            // Need at least 2 bytes to check for end-of-contents
            if self.cursor.len() < 2 {
                return Err(Error::UnexpectedEof {
                    position: self.position,
                });
            }

            // Check for end-of-contents octets (0x00 0x00)
            if self.cursor[0] == 0x00 && self.cursor[1] == 0x00 {
                if depth == 0 {
                    // Found the terminator at our level
                    self.cursor = &self.cursor[2..]; // Skip the 0x00 0x00
                    self.position += 2;
                    break;
                } else {
                    // This terminates a nested indefinite length
                    depth -= 1;
                    content.extend_from_slice(&self.cursor[..2]);
                    self.cursor = &self.cursor[2..];
                    self.position += 2;
                    continue;
                }
            }

            // Read tag
            let (_tag, tag_len) = Tag::decode(self.cursor, self.position)?;
            content.extend_from_slice(&self.cursor[..tag_len]);
            self.cursor = &self.cursor[tag_len..];
            self.position += tag_len;

            // Read length
            let (length, length_len) = Length::decode(self.cursor, self.position)?;
            content.extend_from_slice(&self.cursor[..length_len]);
            self.cursor = &self.cursor[length_len..];
            self.position += length_len;

            // Handle length
            match length {
                Length::Definite(len) => {
                    // Read the definite length content
                    if len > self.config.max_length {
                        return Err(Error::LengthExceedsMaximum {
                            position: self.position,
                            length: len,
                            max_length: self.config.max_length,
                        });
                    }
                    let bytes = self.read_bytes(len)?;
                    content.extend_from_slice(bytes);
                }
                Length::Indefinite => {
                    // Nested indefinite length - increase depth
                    depth += 1;
                }
            }

            // Safety check: prevent infinite loops with huge buffers
            if content.len() > self.config.max_length {
                return Err(Error::LengthExceedsMaximum {
                    position: start_position,
                    length: content.len(),
                    max_length: self.config.max_length,
                });
            }
        }

        Ok(content.into_boxed_slice())
    }

    /// Read indefinite-length content until end-of-contents octets.
    ///
    /// Assembles the bytes, stores the buffer in `self.indefinite_buffers`, and
    /// returns a `&'a [u8]` into it.
    ///
    /// # Safety invariant
    ///
    /// The returned reference is valid for as long as `self` is alive.  All
    /// current call sites satisfy this: the result is either discarded or used
    /// to construct a local decoder that does not outlive `self`.  Do **not**
    /// pass the returned slice to a decoder that may outlive `self`; use
    /// [`enter_constructed`](Self::enter_constructed) instead, which places the
    /// buffer in the child decoder.
    pub(crate) fn read_indefinite_content(&mut self) -> Result<&'a [u8]> {
        let boxed = self.assemble_indefinite_content()?;
        let ptr = boxed.as_ptr();
        let len = boxed.len();
        self.indefinite_buffers.push(boxed);
        // SAFETY: `boxed` was just pushed into `self.indefinite_buffers`; the
        // heap allocation is stable across moves of `Box<[u8]>`, so `ptr`
        // remains valid until `self` is dropped.  All callers use the returned
        // slice only within the lifetime of `self`.
        Ok(unsafe { core::slice::from_raw_parts(ptr, len) })
    }

    /// Read length
    pub fn read_length(&mut self) -> Result<Length> {
        let position_before = self.position;
        let (length, consumed) = Length::decode(self.cursor, self.position)?;

        // DER doesn't allow indefinite length
        if self.encoding == Encoding::Der && length.is_indefinite() {
            return Err(Error::IndefiniteLengthInDer {
                position: self.position,
            });
        }

        // DER requires shortest form for length encoding
        if self.encoding == Encoding::Der {
            if let Length::Definite(len) = length {
                let first_byte = self.cursor[0];

                // Check if long form was used when short form should have been used
                if first_byte > 0x80 {
                    // Long form: check if length < 128 (should have used short form)
                    if len < 128 {
                        return Err(Error::DerViolation {
                            position: position_before,
                            #[cfg(feature = "std")]
                            reason: "DER requires short form for lengths < 128".to_string(),
                            #[cfg(not(feature = "std"))]
                            reason: "DER requires shortest length form",
                        });
                    }

                    // Check for unnecessary leading zeros in long form
                    if consumed > 2 {
                        let first_length_byte = self.cursor[1];
                        if first_length_byte == 0 {
                            return Err(Error::DerViolation {
                                position: position_before,
                                #[cfg(feature = "std")]
                                reason: "DER requires minimal length encoding (no leading zeros)"
                                    .to_string(),
                                #[cfg(not(feature = "std"))]
                                reason: "DER requires minimal length encoding",
                            });
                        }
                    }
                }
            }
        }

        self.cursor = &self.cursor[consumed..];
        self.position += consumed;
        Ok(length)
    }

    /// Enter a constructed ASN.1 element and return a child decoder scoped to its content.
    ///
    /// Reads the leading tag and verifies it equals `tag`, then reads the
    /// length and returns a new `Decoder` whose input is limited to the
    /// content bytes of this element.  The parent decoder's cursor advances
    /// past the entire TLV.
    ///
    /// The child decoder's nesting depth is the parent's depth plus one.
    /// If that would exceed [`DecoderConfig::max_depth`], the method returns
    /// [`Error::MaxDepthExceeded`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnexpectedTag`] if the tag does not match `tag`,
    /// [`Error::MaxDepthExceeded`] if the depth limit is reached, or any
    /// encoding-rule violation error (e.g. indefinite length in DER mode).
    pub fn enter_constructed(&mut self, tag: Tag) -> Result<Decoder<'a>> {
        if self.current_depth >= self.config.max_depth {
            return Err(Error::MaxDepthExceeded {
                position: self.position,
                max_depth: self.config.max_depth,
            });
        }

        let content_tag = self.read_tag()?;
        if content_tag != tag {
            return Err(Error::UnexpectedTag {
                position: self.position,
                expected: tag,
                actual: content_tag,
            });
        }

        let length = self.read_length()?;

        // CER validation: constructed types >1000 bytes must use indefinite length
        if self.encoding == Encoding::Cer {
            match length {
                Length::Definite(len) if len > 1000 => {
                    #[cfg(feature = "std")]
                    return Err(Error::CerViolation {
                        position: self.position,
                        reason: "CER requires indefinite length for constructed types >1000 bytes"
                            .into(),
                    });
                    #[cfg(not(feature = "std"))]
                    return Err(Error::CerViolation {
                        position: self.position,
                        reason: "CER requires indefinite length for constructed types >1000 bytes",
                    });
                }
                _ => {}
            }
        }

        match length {
            Length::Definite(len) => {
                if len > self.config.max_length {
                    return Err(Error::LengthExceedsMaximum {
                        position: self.position,
                        length: len,
                        max_length: self.config.max_length,
                    });
                }
                let content_bytes = self.read_bytes(len)?;
                Ok(Decoder {
                    original: self.original,
                    cursor: content_bytes,
                    encoding: self.encoding,
                    config: self.config,
                    current_depth: self.current_depth + 1,
                    position: 0,
                    indefinite_buffers: Vec::new(),
                })
            }
            Length::Indefinite => {
                // Indefinite length is only allowed in BER/CER
                if self.encoding == Encoding::Der {
                    return Err(Error::IndefiniteLengthInDer {
                        position: self.position,
                    });
                }
                // Store the assembled buffer in the *child* decoder so it is
                // freed when the child is dropped, regardless of when `self`
                // (the parent) is dropped.
                let boxed = self.assemble_indefinite_content()?;
                let ptr = boxed.as_ptr();
                let len = boxed.len();
                // SAFETY: `boxed` is moved into the child's `indefinite_buffers`.
                // `Box<[u8]>` heap data does not move when the `Box` is moved,
                // so `ptr` stays valid for the child's entire lifetime.
                let cursor: &'a [u8] = unsafe { core::slice::from_raw_parts(ptr, len) };
                Ok(Decoder {
                    original: self.original,
                    cursor,
                    encoding: self.encoding,
                    config: self.config,
                    current_depth: self.current_depth + 1,
                    position: 0,
                    indefinite_buffers: vec![boxed],
                })
            }
        }
    }

    /// Decode the next ASN.1 value using the [`Decode`](crate::traits::Decode) trait.
    ///
    /// Convenience wrapper equivalent to `T::decode(self)`.
    ///
    /// # Errors
    ///
    /// Propagates any error returned by `T::decode`.
    pub fn decode<T: crate::traits::Decode<'a>>(&mut self) -> Result<T> {
        T::decode(self)
    }

    /// Decode the next ASN.1 value after verifying its tag matches `expected_tag`.
    ///
    /// Peeks at the next tag and returns [`Error::UnexpectedTag`] without
    /// consuming any bytes if it does not match.  On a tag match, delegates
    /// to `T::decode`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnexpectedTag`] if the leading tag does not match, or
    /// any error from `T::decode`.
    pub fn decode_with_tag<T: crate::traits::Decode<'a>>(
        &mut self,
        expected_tag: Tag,
    ) -> Result<T> {
        let tag = self.peek_tag()?;
        if tag != expected_tag {
            return Err(Error::UnexpectedTag {
                position: self.position,
                expected: expected_tag,
                actual: tag,
            });
        }
        self.decode()
    }
}