image4 0.8.2

A no_std-friendly library for parsing and generation of Image4 images written in pure Rust.
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
use super::CertChainRef;
use crate::{property::DictRef, util};
use der::{
    asn1::{Ia5StringRef, OctetStringRef},
    DecodeValue, Encode, EncodeValue, ErrorKind, FixedTag, Header, Length, Reader, Writer,
};
#[cfg(any(feature = "alloc", test))]
use {
    super::{AnyManifest, Manifest, UnsignedManifest},
    crate::{property::Value, Tag},
    alloc::collections::BTreeMap,
    der::referenced::{OwnedToRef, RefToOwned},
};
#[cfg(feature = "signature")]
use {
    super::{CertChain, SigningError},
    signature::{SignatureEncoding, Signer},
};

fn decode_version<'a, R: Reader<'a>>(decoder: &mut R) -> der::Result<u32> {
    let position = decoder.position();
    let version = decoder.decode::<u32>()?;

    if version != 0 {
        return Err(ErrorKind::Value {
            tag: der::Tag::Integer,
        }
        .at(position));
    }

    Ok(version)
}

/// A signed Image4 manifest that doesn't own its contents.
///
/// # Validation
///
/// The manifest's body, signature and certificate chain **ARE NOT** required to be valid. Types
/// representing the body and the certificate chain were designed for lazy decoding and thus **DO
/// NOT VERIFY** their contents.
///
/// Currently the only way to check that a [`ManifestRef`] contains valid data is as follows:
///
/// ```
/// # use der::Decode;
/// # use image4::ManifestRef;
/// # fn main() -> der::Result<()> {
/// # let bytes = include_bytes!("../../tests/data/apticket.der");
/// let manifest = ManifestRef::from_der(bytes)?;
///
/// let _body = manifest.decode_body()?;
/// let _certs = manifest.cert_chain().decode_body()?;
/// # Ok(())
/// # }
/// ```
///
/// This **DOES NOT** check that the signature is valid and only ensures that the manifest is
/// properly encoded.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct ManifestRef<'a> {
    pub(super) tbs: UnsignedManifestRef<'a>,
    pub(super) signature: OctetStringRef<'a>,
    pub(super) cert_chain: CertChainRef<'a>,
}

impl<'a> ManifestRef<'a> {
    /// Decodes the part of a manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    pub fn decode_after_magic<R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        let tbs = UnsignedManifestRef::decode_after_magic(decoder)?;
        Self::decode_tail(decoder, tbs)
    }

    fn decode_tail<R: Reader<'a>>(
        decoder: &mut R,
        tbs: UnsignedManifestRef<'a>,
    ) -> der::Result<Self> {
        Ok(ManifestRef {
            tbs,
            signature: decoder.decode()?,
            cert_chain: decoder.decode()?,
        })
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        self.tbs.version
    }

    /// Returns a reference to the manifest's body.
    pub fn body(&self) -> &DictRef<'a> {
        &self.tbs.body
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    #[cfg(any(feature = "alloc", test))]
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        self.tbs.decode_body()
    }

    /// Returns a reference to the signature data.
    pub fn signature(&self) -> &[u8] {
        self.signature.as_bytes()
    }

    /// Returns an immutable reference to the encoded certificate chain.
    pub fn cert_chain(&self) -> &CertChainRef<'a> {
        &self.cert_chain
    }

    /// Sets a new certificate chain.
    pub fn set_cert_chain(&mut self, cert_chain: CertChainRef<'a>) {
        self.cert_chain = cert_chain;
    }

    /// Resigns a signed manifest with the specified key and certificate chain.
    #[cfg(feature = "signature")]
    pub fn resign<K, S>(
        &self,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<Manifest, SigningError>
    where
        K: Signer<S>,
        S: SignatureEncoding,
    {
        self.tbs.sign(key, cert_chain)
    }
}

impl FixedTag for ManifestRef<'_> {
    const TAG: der::Tag = der::Tag::Sequence;
}

impl<'a> DecodeValue<'a> for ManifestRef<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        debug_assert_eq!(header.tag, der::Tag::Sequence);

        reader.read_nested(header.length, |reader| {
            util::decode_and_check_magic(reader, b"IM4M")?;
            ManifestRef::decode_after_magic(reader)
        })
    }
}

impl EncodeValue for ManifestRef<'_> {
    fn value_len(&self) -> der::Result<Length> {
        let tbs_len = self.tbs.value_len()?;
        let signature_len = self.signature.encoded_len()?;
        let cert_chain_len = self.cert_chain.encoded_len()?;

        tbs_len + signature_len + cert_chain_len
    }

    fn encode_value(&self, encoder: &mut impl Writer) -> der::Result<()> {
        self.tbs.encode_value(encoder)?;
        self.signature.encode(encoder)?;
        self.cert_chain.encode(encoder)
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> From<&'a Manifest> for ManifestRef<'a> {
    fn from(value: &'a Manifest) -> Self {
        Self {
            tbs: value.tbs.owned_to_ref(),
            signature: value.signature.owned_to_ref(),
            cert_chain: value.cert_chain.owned_to_ref(),
        }
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> RefToOwned<'a> for ManifestRef<'a> {
    type Owned = Manifest;

    fn ref_to_owned(&self) -> Self::Owned {
        self.into()
    }
}

impl<'a> AsRef<UnsignedManifestRef<'a>> for ManifestRef<'a> {
    fn as_ref(&self) -> &UnsignedManifestRef<'a> {
        &self.tbs
    }
}

/// An unsigned Image4 manifest that doesn't own its contents.
///
/// # Validation
///
/// The manifest's body **IS NOT** required to be valid.
///
/// Currently the only way to check that an [`UnsignedManifestRef`] contains valid data is to decode
/// its body using the [`UnsignedManifestRef::decode_body`] method.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct UnsignedManifestRef<'a> {
    pub(super) version: u32,
    pub(super) body: DictRef<'a>,
}

impl<'a> UnsignedManifestRef<'a> {
    /// Creates a new unsigned manifest from its body contents.
    pub fn new(body: DictRef<'a>) -> Self {
        Self { version: 0, body }
    }

    /// Decodes the part of an unsigned manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    pub fn decode_after_magic<R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        Ok(UnsignedManifestRef {
            version: decode_version(decoder)?,
            body: decoder.decode()?,
        })
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Returns a reference to the manifest's body.
    pub fn body(&self) -> &DictRef<'a> {
        &self.body
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    #[cfg(any(feature = "alloc", test))]
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        self.body.decode_owned()
    }

    /// Signs an unsigned manifest with the specified key and certificate chain.
    #[cfg(feature = "signature")]
    pub fn sign<K: Signer<S>, S: SignatureEncoding>(
        &self,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<Manifest, SigningError> {
        self.ref_to_owned().sign(key, cert_chain)
    }
}

impl FixedTag for UnsignedManifestRef<'_> {
    const TAG: der::Tag = der::Tag::Sequence;
}

impl<'a> DecodeValue<'a> for UnsignedManifestRef<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        debug_assert_eq!(header.tag, der::Tag::Sequence);

        reader.read_nested(header.length, |reader| {
            util::decode_and_check_magic(reader, b"IM4M")?;
            UnsignedManifestRef::decode_after_magic(reader)
        })
    }
}

impl EncodeValue for UnsignedManifestRef<'_> {
    fn value_len(&self) -> der::Result<Length> {
        let magic = Ia5StringRef::new(b"IM4M")?;
        let magic_len = magic.encoded_len()?;
        let version_len = self.version.encoded_len()?;
        let body_len = self.body.encoded_len()?;

        magic_len + version_len + body_len
    }

    fn encode_value(&self, encoder: &mut impl Writer) -> der::Result<()> {
        let magic = Ia5StringRef::new(b"IM4M")?;

        magic.encode(encoder)?;
        self.version.encode(encoder)?;
        self.body.encode(encoder)
    }
}

impl<'a> From<ManifestRef<'a>> for UnsignedManifestRef<'a> {
    fn from(value: ManifestRef<'a>) -> Self {
        value.tbs
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> From<&'a Manifest> for UnsignedManifestRef<'a> {
    fn from(value: &'a Manifest) -> Self {
        (&value.tbs).into()
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> From<&'a UnsignedManifest> for UnsignedManifestRef<'a> {
    fn from(value: &'a UnsignedManifest) -> Self {
        Self {
            version: value.version,
            body: value.body.owned_to_ref(),
        }
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> RefToOwned<'a> for UnsignedManifestRef<'a> {
    type Owned = UnsignedManifest;

    fn ref_to_owned(&self) -> Self::Owned {
        self.into()
    }
}

/// Either a signed or an unsigned Image4 manifest that doesn't own its contents.
///
/// This is a helper for cases when either one is expected.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub enum AnyManifestRef<'a> {
    /// A signed manifest.
    Signed(ManifestRef<'a>),
    /// An unsigned manifest.
    Unsigned(UnsignedManifestRef<'a>),
}

impl<'a> AnyManifestRef<'a> {
    /// Decodes the part of a manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    ///
    /// # Differences from other `decode_after_magic` implementations
    ///
    /// This method works by first decoding the unsigned part and then, in case there is some data
    /// left in the decoder, the tail of a signed manifest is decoded. That naturally expects the
    /// decoder to not have any data after the manifest. Usually that doesn't affect anything since
    /// the manifest is a single DER sequence that is decoded with a nested decoder anyway and there
    /// is a check for trailing data in the [`Decode`] implementations, but I decided to document
    /// this difference anyway.
    ///
    /// [`Decode`]: der::Decode
    pub fn decode_after_magic<R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        let tbs = UnsignedManifestRef::decode_after_magic(decoder)?;
        if decoder.is_finished() {
            Ok(Self::Unsigned(tbs))
        } else {
            ManifestRef::decode_tail(decoder, tbs).map(Self::Signed)
        }
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        match self {
            AnyManifestRef::Signed(m) => m.version(),
            AnyManifestRef::Unsigned(m) => m.version(),
        }
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    #[cfg(any(feature = "alloc", test))]
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        match self {
            AnyManifestRef::Signed(m) => m.decode_body(),
            AnyManifestRef::Unsigned(m) => m.decode_body(),
        }
    }
}

impl FixedTag for AnyManifestRef<'_> {
    const TAG: der::Tag = der::Tag::Sequence;
}

impl<'a> DecodeValue<'a> for AnyManifestRef<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        debug_assert_eq!(header.tag, der::Tag::Sequence);

        reader.read_nested(header.length, |reader| {
            util::decode_and_check_magic(reader, b"IM4M")?;
            Self::decode_after_magic(reader)
        })
    }
}

impl EncodeValue for AnyManifestRef<'_> {
    fn value_len(&self) -> der::Result<Length> {
        match self {
            AnyManifestRef::Signed(m) => m.value_len(),
            AnyManifestRef::Unsigned(m) => m.value_len(),
        }
    }

    fn encode_value(&self, encoder: &mut impl Writer) -> der::Result<()> {
        match self {
            AnyManifestRef::Signed(m) => m.encode_value(encoder),
            AnyManifestRef::Unsigned(m) => m.encode_value(encoder),
        }
    }
}

impl<'a> From<ManifestRef<'a>> for AnyManifestRef<'a> {
    fn from(value: ManifestRef<'a>) -> Self {
        Self::Signed(value)
    }
}

impl<'a> From<UnsignedManifestRef<'a>> for AnyManifestRef<'a> {
    fn from(value: UnsignedManifestRef<'a>) -> Self {
        Self::Unsigned(value)
    }
}

impl<'a> AsRef<UnsignedManifestRef<'a>> for AnyManifestRef<'a> {
    fn as_ref(&self) -> &UnsignedManifestRef<'a> {
        match self {
            AnyManifestRef::Signed(m) => &m.tbs,
            AnyManifestRef::Unsigned(m) => m,
        }
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> From<&'a AnyManifest> for AnyManifestRef<'a> {
    fn from(value: &'a AnyManifest) -> Self {
        match value {
            AnyManifest::Signed(m) => Self::Signed(m.into()),
            AnyManifest::Unsigned(m) => Self::Unsigned(m.into()),
        }
    }
}

#[cfg(any(feature = "alloc", test))]
impl<'a> RefToOwned<'a> for AnyManifestRef<'a> {
    type Owned = AnyManifest;

    fn ref_to_owned(&self) -> Self::Owned {
        self.into()
    }
}