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
//! ASN.1 `ANY` type.
#![cfg_attr(feature = "arbitrary", allow(clippy::arithmetic_side_effects))]
use crate::{
BytesRef, Choice, Decode, DecodeValue, DerOrd, EncodeValue, EncodingRules, Error, ErrorKind,
Header, Length, Reader, SliceReader, Tag, Tagged, ValueOrd, Writer,
};
use core::cmp::Ordering;
/// ASN.1 `ANY`: represents any explicitly tagged ASN.1 value.
///
/// This is a zero-copy reference type which borrows from the input data.
///
/// Technically `ANY` hasn't been a recommended part of ASN.1 since the X.209
/// revision from 1988. It was deprecated and replaced by Information Object
/// Classes in X.680 in 1994, and X.690 no longer refers to it whatsoever.
///
/// Nevertheless, this crate defines an `ANY` type as it remains a familiar
/// and useful concept which is still extensively used in things like
/// PKI-related RFCs.
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AnyRef<'a> {
/// Tag representing the type of the encoded value.
tag: Tag,
/// Inner value encoded as bytes.
value: &'a BytesRef,
}
impl<'a> AnyRef<'a> {
/// [`AnyRef`] representation of the ASN.1 `NULL` type.
pub const NULL: Self = Self {
tag: Tag::Null,
value: BytesRef::new_unchecked(&[]),
};
/// Create a new [`AnyRef`] from the provided [`Tag`] and DER bytes.
///
/// # Errors
/// Returns [`Error`] with [`ErrorKind::Length`] if `bytes` is too long.
pub const fn new(tag: Tag, bytes: &'a [u8]) -> Result<Self, Error> {
match BytesRef::new(bytes) {
Ok(value) => Ok(Self { tag, value }),
Err(_) => Err(Error::from_kind(ErrorKind::Length { tag })),
}
}
/// Infallible creation of an [`AnyRef`] from a [`BytesRef`].
pub(crate) fn from_tag_and_value(tag: Tag, value: &'a BytesRef) -> Self {
Self { tag, value }
}
/// Get the raw value for this [`AnyRef`] type as a byte slice.
#[must_use]
pub fn value(self) -> &'a [u8] {
self.value.as_slice()
}
/// Returns [`Tag`] and [`Length`] of self.
#[must_use]
pub fn header(&self) -> Header {
Header::new(self.tag, self.value.len())
}
/// Attempt to decode this [`AnyRef`] type into the inner value.
///
/// # Errors
/// Returns `T::Error` if a decoding error occurred.
pub fn decode_as<T>(self) -> Result<T, <T as DecodeValue<'a>>::Error>
where
T: Choice<'a> + DecodeValue<'a>,
{
self.decode_as_encoding(EncodingRules::Der)
}
/// Attempt to decode this [`AnyRef`] type into the inner value.
///
/// # Errors
/// Returns `T::Error` if a decoding error occurred.
pub fn decode_as_encoding<T>(
self,
encoding: EncodingRules,
) -> Result<T, <T as DecodeValue<'a>>::Error>
where
T: Choice<'a> + DecodeValue<'a>,
{
if !T::can_decode(self.tag) {
return Err(self.tag.unexpected_error(None).to_error().into());
}
let mut decoder = SliceReader::new_with_encoding_rules(self.value(), encoding)?;
let result = T::decode_value(&mut decoder, self.header())?;
decoder.finish()?;
Ok(result)
}
/// Is this value an ASN.1 `NULL` value?
#[must_use]
pub fn is_null(self) -> bool {
self == Self::NULL
}
/// Attempt to decode this value an ASN.1 `SEQUENCE`, creating a new
/// nested reader and calling the provided argument with it.
///
/// # Errors
/// Returns `E` in the event an error is returned from `F` or if a decoding error occurs.
pub fn sequence<F, T, E>(self, f: F) -> Result<T, E>
where
F: FnOnce(&mut SliceReader<'a>) -> Result<T, E>,
E: From<Error>,
{
self.tag.assert_eq(Tag::Sequence)?;
let mut reader = SliceReader::new(self.value.as_slice())?;
let result = f(&mut reader)?;
reader.finish()?;
Ok(result)
}
}
impl<'a> Choice<'a> for AnyRef<'a> {
fn can_decode(_: Tag) -> bool {
true
}
}
impl<'a> Decode<'a> for AnyRef<'a> {
type Error = Error;
fn decode<R: Reader<'a>>(reader: &mut R) -> Result<AnyRef<'a>, Error> {
let header = Header::decode(reader)?;
Self::decode_value(reader, header)
}
}
impl<'a> DecodeValue<'a> for AnyRef<'a> {
type Error = Error;
fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self, Error> {
Ok(Self {
tag: header.tag(),
value: <&'a BytesRef>::decode_value(reader, header)?,
})
}
}
impl EncodeValue for AnyRef<'_> {
fn value_len(&self) -> Result<Length, Error> {
Ok(self.value.len())
}
fn encode_value(&self, writer: &mut impl Writer) -> Result<(), Error> {
writer.write(self.value())
}
}
impl Tagged for AnyRef<'_> {
fn tag(&self) -> Tag {
self.tag
}
}
impl ValueOrd for AnyRef<'_> {
fn value_cmp(&self, other: &Self) -> Result<Ordering, Error> {
self.value.der_cmp(other.value)
}
}
impl<'a> From<AnyRef<'a>> for &'a BytesRef {
fn from(any: AnyRef<'a>) -> &'a BytesRef {
any.value
}
}
impl<'a> TryFrom<&'a [u8]> for AnyRef<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<AnyRef<'a>, Error> {
AnyRef::from_der(bytes)
}
}
#[cfg(feature = "alloc")]
pub use self::allocating::Any;
#[cfg(feature = "alloc")]
mod allocating {
use super::*;
use crate::{BytesOwned, encode::encode_value_to_slice, reader::read_value, referenced::*};
use alloc::boxed::Box;
/// ASN.1 `ANY`: represents any explicitly tagged ASN.1 value.
///
/// This type provides the same functionality as [`AnyRef`] but owns the
/// backing data.
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Any {
/// Tag representing the type of the encoded value.
tag: Tag,
/// Inner value encoded as bytes.
value: BytesOwned,
}
impl Any {
/// Create a new [`Any`] from the provided [`Tag`] and DER bytes.
///
/// # Errors
/// If `bytes` is too long.
pub fn new(tag: Tag, bytes: impl Into<Box<[u8]>>) -> Result<Self, Error> {
let value = BytesOwned::new(bytes)?;
Ok(Self { tag, value })
}
/// Allow access to value
#[must_use]
pub fn value(&self) -> &[u8] {
self.value.as_slice()
}
/// Returns [`Tag`] and [`Length`] of self.
#[must_use]
pub fn header(&self) -> Header {
Header::new(self.tag, self.value.len())
}
/// Attempt to decode this [`Any`] type into the inner value.
///
/// # Errors
/// Returns `T::Error` if a decoding error occurred.
pub fn decode_as<'a, T>(&'a self) -> Result<T, <T as DecodeValue<'a>>::Error>
where
T: Choice<'a> + DecodeValue<'a>,
{
self.decode_as_encoding(EncodingRules::Der)
}
/// Attempt to decode this [`Any`] type into the inner value with the given encoding rules.
///
/// # Errors
/// Returns `T::Error` if a decoding error occurred.
pub fn decode_as_encoding<'a, T>(
&'a self,
encoding: EncodingRules,
) -> Result<T, <T as DecodeValue<'a>>::Error>
where
T: Choice<'a> + DecodeValue<'a>,
{
self.to_ref().decode_as_encoding(encoding)
}
/// Encode the provided type as an [`Any`] value.
///
/// # Errors
/// If an encoding error occurred.
pub fn encode_from<T>(msg: &T) -> Result<Self, Error>
where
T: Tagged + EncodeValue,
{
let encoded_len = usize::try_from(msg.value_len()?)?;
let mut buf = vec![0u8; encoded_len];
encode_value_to_slice(&mut buf, msg)?;
Any::new(msg.tag(), buf)
}
/// Attempt to decode this value an ASN.1 `SEQUENCE`, creating a new
/// nested reader and calling the provided argument with it.
///
/// # Errors
/// If a decoding error occurred.
pub fn sequence<'a, F, T, E>(&'a self, f: F) -> Result<T, E>
where
F: FnOnce(&mut SliceReader<'a>) -> Result<T, E>,
E: From<Error>,
{
AnyRef::from(self).sequence(f)
}
/// [`Any`] representation of the ASN.1 `NULL` type.
#[must_use]
pub fn null() -> Self {
Self {
tag: Tag::Null,
value: BytesOwned::default(),
}
}
/// Create a new [`AnyRef`] from the provided [`Any`] owned tag and bytes.
#[must_use]
pub fn to_ref(&self) -> AnyRef<'_> {
AnyRef {
tag: self.tag,
value: self.value.as_ref(),
}
}
}
impl Choice<'_> for Any {
fn can_decode(_: Tag) -> bool {
true
}
}
impl<'a> Decode<'a> for Any {
type Error = Error;
fn decode<R: Reader<'a>>(reader: &mut R) -> Result<Self, Error> {
let header = Header::decode(reader)?;
read_value(reader, header, Self::decode_value)
}
}
impl<'a> DecodeValue<'a> for Any {
type Error = Error;
fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self, Error> {
Ok(Self {
tag: header.tag(),
value: BytesOwned::decode_value(reader, header)?,
})
}
}
impl EncodeValue for Any {
fn value_len(&self) -> Result<Length, Error> {
Ok(self.value.len())
}
fn encode_value(&self, writer: &mut impl Writer) -> Result<(), Error> {
writer.write(self.value.as_slice())
}
}
impl<'a> From<&'a Any> for AnyRef<'a> {
fn from(any: &'a Any) -> AnyRef<'a> {
any.to_ref()
}
}
impl Tagged for Any {
fn tag(&self) -> Tag {
self.tag
}
}
impl ValueOrd for Any {
fn value_cmp(&self, other: &Self) -> Result<Ordering, Error> {
self.value.der_cmp(&other.value)
}
}
impl<'a, T> From<T> for Any
where
T: Into<AnyRef<'a>>,
{
fn from(input: T) -> Any {
let anyref: AnyRef<'a> = input.into();
Self {
tag: anyref.tag(),
value: BytesOwned::from(anyref.value),
}
}
}
impl<'a> RefToOwned<'a> for AnyRef<'a> {
type Owned = Any;
fn ref_to_owned(&self) -> Self::Owned {
Any {
tag: self.tag(),
value: BytesOwned::from(self.value),
}
}
}
impl OwnedToRef for Any {
type Borrowed<'a> = AnyRef<'a>;
fn owned_to_ref(&self) -> Self::Borrowed<'_> {
self.into()
}
}
impl Any {
/// Is this value an ASN.1 `NULL` value?
#[must_use]
pub fn is_null(&self) -> bool {
self.owned_to_ref() == AnyRef::NULL
}
}
}