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
use crate::ber::*;
use crate::*;
use std::{borrow::Cow, convert::TryInto};

/// The `Any` object is not strictly an ASN.1 type, but holds a generic description of any object
/// that could be encoded.
///
/// It contains a header, and either a reference to or owned data for the object content.
#[derive(Debug)]
pub struct Any<'a> {
    pub header: Header<'a>,
    pub data: Cow<'a, [u8]>,
}

impl<'a> Any<'a> {
    /// Create a new `Any` from BER/DER header and content
    pub const fn new(header: Header<'a>, data: Cow<'a, [u8]>) -> Self {
        Any { header, data }
    }

    /// Create a new `Any` from a tag, and BER/DER content
    pub const fn from_tag_and_data(tag: Tag, data: &'a [u8]) -> Self {
        let constructed = matches!(tag, Tag::Sequence | Tag::Set);
        Any {
            header: Header {
                tag,
                constructed,
                class: crate::Class::Universal,
                length: Length::Definite(data.len()),
                raw_tag: None,
            },
            data: Cow::Borrowed(data),
        }
    }

    /// Return the `Tag` of this object
    #[inline]
    pub const fn tag(&self) -> Tag {
        self.header.tag
    }

    /// Get the bytes representation of the *content*
    pub fn as_cow(&'a self) -> &Cow<'a, [u8]> {
        &self.data
    }

    /// Get the bytes representation of the *content*
    pub fn into_cow(self) -> Cow<'a, [u8]> {
        self.data
    }

    /// Get the bytes representation of the *content*
    pub fn as_bytes(&'a self) -> &'a [u8] {
        &self.data
    }

    pub fn parse_ber<T>(&'a self) -> ParseResult<'a, T>
    where
        T: FromBer<'a>,
    {
        T::from_ber(&self.data)
    }

    pub fn parse_der<T>(&'a self) -> ParseResult<'a, T>
    where
        T: FromDer<'a>,
    {
        T::from_der(&self.data)
    }
}

macro_rules! impl_any_into {
    (IMPL $sname:expr, $fn_name:ident => $ty:ty, $asn1:expr) => {
        #[doc = "Attempt to convert object to `"]
        #[doc = $sname]
        #[doc = "` (ASN.1 type: `"]
        #[doc = $asn1]
        #[doc = "`)."]
        pub fn $fn_name(self) -> Result<$ty> {
            self.try_into()
        }
    };
    ($fn_name:ident => $ty:ty, $asn1:expr) => {
        impl_any_into! {
            IMPL stringify!($ty), $fn_name => $ty, $asn1
        }
    };
}

impl<'a> Any<'a> {
    impl_any_into!(bitstring => BitString<'a>, "BIT STRING");
    impl_any_into!(bmpstring => BmpString<'a>, "BmpString");
    impl_any_into!(bool => bool, "BOOLEAN");
    impl_any_into!(boolean => Boolean, "BOOLEAN");
    impl_any_into!(enumerated => Enumerated, "ENUMERATED");
    impl_any_into!(generalizedtime => GeneralizedTime, "GeneralizedTime");
    impl_any_into!(generalstring => GeneralString<'a>, "GeneralString");
    impl_any_into!(ia5string => Ia5String<'a>, "IA5String");
    impl_any_into!(integer => Integer<'a>, "INTEGER");
    impl_any_into!(null => Null, "NULL");
    impl_any_into!(numericstring => NumericString<'a>, "NumericString");
    impl_any_into!(octetstring => OctetString<'a>, "OCTET STRING");
    impl_any_into!(oid => Oid<'a>, "OBJECT IDENTIFIER");
    /// Attempt to convert object to `Oid` (ASN.1 type: `RELATIVE-OID`).
    pub fn relative_oid(self) -> Result<Oid<'a>> {
        self.header.assert_tag(Tag::RelativeOid)?;
        self.try_into()
    }
    impl_any_into!(printablestring => PrintableString<'a>, "PrintableString");
    impl_any_into!(sequence => Sequence<'a>, "SEQUENCE");
    impl_any_into!(set => Set<'a>, "SET");
    impl_any_into!(string => String, "UTF8String");
    impl_any_into!(teletexstring => TeletexString<'a>, "TeletexString");
    impl_any_into!(u8 => u8, "INTEGER");
    impl_any_into!(u16 => u16, "INTEGER");
    impl_any_into!(u32 => u32, "INTEGER");
    impl_any_into!(u64 => u64, "INTEGER");
    impl_any_into!(universalstring => UniversalString<'a>, "UniversalString");
    impl_any_into!(utctime => UtcTime, "UTCTime");
    impl_any_into!(utf8string => Utf8String<'a>, "UTF8String");
    impl_any_into!(videotexstring => VideotexString<'a>, "VideotexString");
    impl_any_into!(visiblestring => VisibleString<'a>, "VisibleString");
}

impl<'a> FromBer<'a> for Any<'a> {
    fn from_ber(bytes: &'a [u8]) -> ParseResult<Self> {
        let (i, header) = Header::from_ber(bytes)?;
        let (i, data) = ber_get_object_content(i, &header, MAX_RECURSION)?;
        let data = Cow::Borrowed(data);
        Ok((i, Any { header, data }))
    }
}

impl<'a> FromDer<'a> for Any<'a> {
    fn from_der(bytes: &'a [u8]) -> ParseResult<Self> {
        let (i, header) = Header::from_der(bytes)?;
        // X.690 section 10.1: The definite form of length encoding shall be used
        header.length.assert_definite()?;
        let (i, data) = ber_get_object_content(i, &header, MAX_RECURSION)?;
        let data = Cow::Borrowed(data);
        Ok((i, Any { header, data }))
    }
}

impl DynTagged for Any<'_> {
    fn tag(&self) -> Tag {
        self.tag()
    }
}

impl<'a> ToStatic for Any<'a> {
    type Owned = Any<'static>;

    fn to_static(&self) -> Self::Owned {
        Any {
            header: self.header.to_static(),
            data: Cow::Owned(self.data.to_vec()),
        }
    }
}

impl ToDer for Any<'_> {
    fn to_der_len(&self) -> Result<usize> {
        let hdr_len = self.header.to_der_len()?;
        Ok(hdr_len + self.data.len())
    }

    fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
        // create fake header to have correct length
        let header = Header::new(
            self.header.class,
            self.header.constructed,
            self.header.tag,
            Length::Definite(self.data.len()),
        );
        let sz = header.write_der_header(writer)?;
        Ok(sz)
    }

    fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
        writer.write(&self.data).map_err(Into::into)
    }

    /// Similar to using `to_der`, but uses header without computing length value
    fn write_der_raw(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
        let sz = self.header.write_der_header(writer)?;
        let sz = sz + writer.write(&self.data)?;
        Ok(sz)
    }
}