synta 0.1.6

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
//! ASN.1 Object Identifier (OID).
//!
//! An OID is a sequence of non-negative integers that globally identifies an
//! object (algorithm, attribute type, certificate extension, …).
//!
//! ## Encoding rules
//!
//! The first component must be 0, 1, or 2.  When the first component is 0 or
//! 1, the second must be less than 40.  On the wire the first two components
//! are combined into a single base-128 encoded integer (first × 40 + second);
//! subsequent components are each independently base-128 encoded.
//!
//! ## Matching OIDs efficiently
//!
//! Compare [`components`](ObjectIdentifier::components) slices directly rather
//! than converting to dotted-decimal strings:
//!
//! ```
//! use synta::ObjectIdentifier;
//!
//! // SHA-256: 2.16.840.1.101.3.4.2.1
//! let sha256 = ObjectIdentifier::new(&[2, 16, 840, 1, 101, 3, 4, 2, 1]).unwrap();
//! assert!(matches!(sha256.components(), [2, 16, 840, 1, 101, 3, 4, 2, 1]));
//! ```

#[cfg(all(not(feature = "std"), feature = "serde"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use smallvec::SmallVec;

/// ASN.1 OBJECT IDENTIFIER
///
/// Uses SmallVec to avoid allocations for most OIDs (< 10 components)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectIdentifier {
    // Most OIDs have fewer than 10 components
    components: SmallVec<[u32; 10]>,
}

impl ObjectIdentifier {
    /// Create a new `ObjectIdentifier` from a slice of component integers.
    ///
    /// # Validation
    ///
    /// - `components` must have at least 2 elements.
    /// - `components[0]` must be 0, 1, or 2.
    /// - If `components[0]` is 0 or 1, then `components[1]` must be < 40.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOid`](crate::Error::InvalidOid) if any
    /// validation rule is violated.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// // rsadsi (1.2.840.113549)
    /// let oid = ObjectIdentifier::new(&[1, 2, 840, 113549]).unwrap();
    /// assert_eq!(oid.to_string(), "1.2.840.113549");
    /// ```
    pub fn new(components: &[u32]) -> crate::Result<Self> {
        // OID must have at least 2 components
        if components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        // First component must be 0, 1, or 2
        if components[0] > 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        // If first is 0 or 1, second must be < 40
        if components[0] < 2 && components[1] >= 40 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        Ok(Self {
            components: SmallVec::from_slice(components),
        })
    }

    /// Return the OID as a slice of component integers.
    ///
    /// The slice begins with the two top-level arc values (e.g. `[1, 2, …]`).
    /// Matching against a known OID is most efficient by comparing the slice
    /// directly rather than converting to a dotted-decimal string:
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// let oid = ObjectIdentifier::new(&[1, 2, 840, 113549]).unwrap();
    /// assert!(matches!(oid.components(), [1, 2, 840, 113549]));
    /// ```
    pub fn components(&self) -> &[u32] {
        &self.components
    }

    /// Parse an OID from its DER/BER **content** bytes — the raw value bytes
    /// inside an OID TLV, with the tag (`0x06`) and length already stripped.
    ///
    /// This is the low-level counterpart to [`Decode`](crate::traits::Decode)
    /// for situations where the tag and length have already been consumed, for
    /// example after stripping an implicit context tag from a GeneralName
    /// `registeredID [8] IMPLICIT OID` alternative.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOid`](crate::Error::InvalidOid) if `data` is
    /// empty, contains a truncated base-128 sequence, or causes a `u32`
    /// overflow in any component.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// // commonName 2.5.4.3 — DER content bytes (tag+length stripped)
    /// let oid = ObjectIdentifier::from_content_bytes(&[0x55, 0x04, 0x03]).unwrap();
    /// assert_eq!(oid.to_string(), "2.5.4.3");
    /// ```
    pub fn from_content_bytes(data: &[u8]) -> crate::Result<Self> {
        if data.is_empty() {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        let mut i = 0;

        // First encoded value is base-128 and represents two OID components
        // combined as: arc0 * 40 + arc1  (with arc0 ∈ {0,1,2}).
        let mut combined: u32 = 0;
        loop {
            if i >= data.len() {
                return Err(crate::Error::InvalidOid { position: i });
            }
            let byte = data[i];
            i += 1;
            if combined > (u32::MAX >> 7) {
                return Err(crate::Error::InvalidOid { position: i });
            }
            combined = (combined << 7) | ((byte & 0x7F) as u32);
            if (byte & 0x80) == 0 {
                break;
            }
        }

        if combined < 40 {
            components.push(0);
            components.push(combined);
        } else if combined < 80 {
            components.push(1);
            components.push(combined - 40);
        } else {
            components.push(2);
            components.push(combined - 80);
        }

        // Remaining components, each independently base-128 encoded.
        while i < data.len() {
            let mut value: u32 = 0;
            loop {
                if i >= data.len() {
                    return Err(crate::Error::InvalidOid { position: i });
                }
                let byte = data[i];
                i += 1;
                if value > (u32::MAX >> 7) {
                    return Err(crate::Error::InvalidOid { position: i });
                }
                value = (value << 7) | ((byte & 0x7F) as u32);
                if (byte & 0x80) == 0 {
                    break;
                }
            }
            components.push(value);
        }

        Ok(Self { components })
    }

    /// Construct an OID from an already-validated `SmallVec` of components.
    ///
    /// # Safety (logical)
    ///
    /// The caller must guarantee that `components` encodes a valid OID:
    /// - At least 2 elements
    /// - `components[0]` ∈ {0, 1, 2}
    /// - If `components[0]` < 2, then `components[1]` < 40
    ///
    /// This constructor skips the validation check and the `from_slice` copy
    /// performed by [`Self::new`].  It is `pub(crate)` to keep the unsafe
    /// contract internal.
    #[inline]
    pub(crate) fn from_components_unchecked(components: SmallVec<[u32; 10]>) -> Self {
        Self { components }
    }
}

// `Display` produces canonical dotted-decimal notation, e.g. `"1.2.840.113549"`.
impl core::fmt::Display for ObjectIdentifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut iter = self.components.iter();
        if let Some(first) = iter.next() {
            write!(f, "{}", first)?;
            for component in iter {
                write!(f, ".{}", component)?;
            }
        }
        Ok(())
    }
}

// `FromStr` parses dotted-decimal notation (`"1.2.840.113549"`) and validates
// the resulting components.  Only available with the `std` feature.
#[cfg(feature = "std")]
impl core::str::FromStr for ObjectIdentifier {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        for part in s.split('.') {
            let v: u32 = part
                .parse()
                .map_err(|_| crate::Error::InvalidOid { position: 0 })?;
            components.push(v);
        }
        if components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        if components[0] > 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        if components[0] < 2 && components[1] >= 40 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        Ok(Self { components })
    }
}

// Implement Decode trait for ObjectIdentifier
impl crate::traits::Decode<'_> for ObjectIdentifier {
    fn decode(decoder: &mut crate::der::decoder::Decoder) -> crate::Result<Self> {
        use crate::tag::TAG_OBJECT_IDENTIFIER;

        let tag = decoder.read_tag()?;
        let expected_tag = crate::Tag::universal(TAG_OBJECT_IDENTIFIER);

        if tag != expected_tag {
            return Err(crate::Error::UnexpectedTag {
                position: decoder.position(),
                expected: expected_tag,
                actual: tag,
            });
        }

        let length = decoder.read_length()?;
        let len = length.definite()?;

        if len == 0 {
            return Err(crate::Error::InvalidOid {
                position: decoder.position(),
            });
        }

        let bytes = decoder.read_bytes(len)?;

        ObjectIdentifier::from_content_bytes(bytes).map_err(|_| crate::Error::InvalidOid {
            position: decoder.position(),
        })
    }
}

// Implement Encode trait for ObjectIdentifier
impl crate::traits::Encode for ObjectIdentifier {
    fn encode(&self, encoder: &mut crate::der::encoder::Encoder) -> crate::Result<()> {
        use crate::tag::TAG_OBJECT_IDENTIFIER;

        if self.components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let tag = crate::Tag::universal(TAG_OBJECT_IDENTIFIER);
        encoder.write_tag(tag)?;

        // Calculate content and encode
        let mut content = Vec::new();

        // First two components are encoded as: first * 40 + second
        let first = self.components[0];
        let second = self.components[1];

        let combined = first * 40 + second;
        encode_base128(combined, &mut content);

        // Encode remaining components using base-128 encoding
        for &component in &self.components[2..] {
            encode_base128(component, &mut content);
        }

        encoder.write_length(content.len())?;
        encoder.write_bytes(&content);
        Ok(())
    }

    fn encoded_len(&self) -> crate::Result<usize> {
        if self.components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let tag_len = 1;

        // Calculate content length
        // First two components are combined as: first * 40 + second
        let first = self.components[0];
        let second = self.components[1];
        let combined = first * 40 + second;
        let mut content_len = base128_len(combined);

        // Add lengths of remaining components
        for &component in &self.components[2..] {
            content_len += base128_len(component);
        }

        let length_len = crate::Length::Definite(content_len).encoded_len()?;
        Ok(tag_len + length_len + content_len)
    }
}

// Implement Tagged trait
impl crate::traits::Tagged for ObjectIdentifier {
    fn tag() -> crate::Tag {
        crate::Tag::universal(crate::tag::TAG_OBJECT_IDENTIFIER)
    }
}

// Helper function to encode a u32 in base-128
fn encode_base128(mut value: u32, buffer: &mut Vec<u8>) {
    if value == 0 {
        buffer.push(0);
        return;
    }

    // Collect bytes in reverse order
    let mut bytes = Vec::new();
    while value > 0 {
        bytes.push((value & 0x7F) as u8);
        value >>= 7;
    }

    // Write in correct order with high bit set on all but last
    for (i, &byte) in bytes.iter().rev().enumerate() {
        if i < bytes.len() - 1 {
            buffer.push(byte | 0x80);
        } else {
            buffer.push(byte);
        }
    }
}

// ---- serde support ----

/// `ObjectIdentifier` serializes as a dotted-decimal string (e.g. `"1.2.840.113549"`).
#[cfg(feature = "serde")]
impl serde::Serialize for ObjectIdentifier {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use core::fmt::Write;
        let mut buf = String::new();
        for (i, &component) in self.components().iter().enumerate() {
            if i > 0 {
                buf.push('.');
            }
            let _ = write!(buf, "{}", component);
        }
        s.serialize_str(&buf)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ObjectIdentifier {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct OidVisitor;
        impl<'de> serde::de::Visitor<'de> for OidVisitor {
            type Value = ObjectIdentifier;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "an OID in dotted-decimal notation (e.g. \"1.2.840\")")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<ObjectIdentifier, E> {
                let components: Result<Vec<u32>, _> =
                    v.split('.').map(|p| p.parse::<u32>()).collect();
                let components = components.map_err(|_| E::custom("invalid OID component"))?;
                ObjectIdentifier::new(&components).map_err(|_| E::custom("invalid OID"))
            }
        }
        d.deserialize_str(OidVisitor)
    }
}

// Helper function to calculate base-128 encoded length
fn base128_len(value: u32) -> usize {
    if value == 0 {
        return 1;
    }

    let mut len = 0;
    let mut v = value;
    while v > 0 {
        len += 1;
        v >>= 7;
    }
    len
}